<?php

class BrandController extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        if ($this->session->userdata('admin_logged_in') !== TRUE) {
            redirect('/');
        }

        $this->load->model('dataHandling/crud', 'crud');
        $this->load->model('pages/BrandModel', 'model');
        $this->load->model('TableModel/brand/FetchBrandData', 'TableModel');
    }

    public function index()
    {
        $this->layouts->add_includes('assets/backend/js/pages/brand.js');
        $data['title'] = "Brand";
        $data['content'] = 'pages/main/brand';
        $this->load->view('layout/backend-access', $data);
    }

    public function getBrandData()
    {
        if ($this->input->is_ajax_request()) {
            $list = $this->TableModel->get_datatables();
            $data = array();
            $no = $_POST['start'];

            foreach ($list as $data_n) {
                $no++;
                $row = array();
                $row[] = $no;
                $row[] = $data_n->brand_name;
                $row[] = $data_n->serial;
                $row[] = $data_n->status;
                $row[] = $data_n->publish_status;
                $row[] = sha1($data_n->brand_id);
                $row[] = $data_n->logo;

                $data[] = $row;
            }

            $output = array(
                "draw" => $_POST['draw'],
                "recordsTotal" => $this->TableModel->count_all(),
                "recordsFiltered" => $this->TableModel->count_filtered(),
                "data" => $data,
            );
            //output to json format
            echo json_encode($output);
        }
    }

    public function newBrandEntryProcess()
    {
        if ($this->input->is_ajax_request()) {
            $this->form_validation->set_rules('brand_name', 'Brand Name', 'required|trim');
            $this->form_validation->set_rules('serial', 'Serial', 'required|trim');

            if ($this->form_validation->run()) {

                $brand_name = $this->input->post('brand_name', TRUE);
				$serial=$this->input->post('serial',TRUE);
				$url = strtolower(trim(str_replace(" ", "-", $brand_name)));
				$filtered_url = preg_replace('/[^A-Za-z0-9\-]/', '', $url);
				$filter_result = $this->model->exist_url($filtered_url);
				if($filter_result){
					$dataSet = array(
						'brand_name' => $brand_name,
						'url'=>$filtered_url,
						'serial'=>$serial,
					);

					$table = "brand";

					if ($this->crud->insertReturnData($dataSet, $table)) {
						$data['response'] = 'Brand save successfully';
						$data['type']='success';
					} else {
						$data['response'] = 'Error Occured';
						$data['type']='error';
					}
				}
				else{
					$data['response']='Brand already exist';
					$data['type']='warning';
				}
            } else {
                $data['response'] = 'Validation Error';
				$data['type']='error';
            }
			echo json_encode($data);
        }
    }

    public function brandEditProcess()
    {
        if ($this->input->is_ajax_request()) {
            $this->form_validation->set_rules('brand_name', 'Brand Name', 'required|trim');
            $this->form_validation->set_rules('serial', 'Serial', 'required|trim');
            $this->form_validation->set_rules('status', 'Status', 'required|trim');

            if ($this->form_validation->run()) {

                $brand_id_sha1 = $this->input->post('brand_id', TRUE);
                $result = $this->crud->getIDProcessing($brand_id_sha1, 'brand_id', 'brand');
                $brand_id = $result->brand_id;

                $brand_name = $this->input->post('brand_name', TRUE);
                $status = $this->input->post('status', TRUE);

				$serial=$this->input->post('serial',TRUE);
				$url = strtolower(trim(str_replace(" ", "-", $brand_name)));
				$filtered_url = preg_replace('/[^A-Za-z0-9\-]/', '', $url);
				$filter_result = $this->model->exist_url($filtered_url, $brand_id);
				if($filter_result){
					$dataSet = array(
						'brand_name' => $brand_name,
						'url'=>$filtered_url,
						'serial'=>$serial,
						'status' => $status,
					);
					$table = "brand";
					if ($this->crud->updateData($brand_id, $dataSet, 'brand_id', $table)) {
						$data['response'] = 'Brand update successfully';
						$data['type']='success';
					} else {
						$data['response'] = 'Error Occured';
						$data['type']='error';
					}
				}
				else{
					$data['response'] = 'Brand already exist';
					$data['type']='warning';
				}
            } else {
                $data['response'] = 'Validation Error';
				$data['type']='error';
            }
			echo json_encode($data);
        }
    }

    public function addBrandLogo()
    {
        if ($this->input->is_ajax_request()) {
            $brand_id_sha1 = $this->input->post('brand_id', TRUE);
            $result = $this->crud->getIDProcessing($brand_id_sha1, 'brand_id', 'brand');
            $brand_id = $result->brand_id;
            $image_exist = $this->model->exist_image($brand_id);
            if (!empty($image_exist->picture)) {
                unlink('assets/img/brand/' . $image_exist->logo);
            }
            $image_data = $this->input->post('image');
            list($type, $image_data) = explode(';', $image_data);
            list(, $image_data)      = explode(',', $image_data);
            $image_data = base64_decode($image_data);
            $imageName = time() . '.png';
            file_put_contents('assets/img/brand/' . $imageName, $image_data);

            $dataSet = array(
                'logo' => $imageName,
                'publish_status' => "Published",
            );
            $table = "brand";

            if ($this->crud->updateData($brand_id, $dataSet, 'brand_id', $table)) {
                $data['response'] = 'Logo Add successfully';
            } else {
                $data['response'] = 'Error Occured';
            }
            echo json_encode($data);
        }
    }

    public function getBrandJsonData()
    {
        if ($this->input->is_ajax_request()) {
            $this->model->getBrandJsonData();
        }
    }

	public function deleteBrand()
	{
		if ($this->input->is_ajax_request()) {
			$brand_id_sha1 = $this->input->post('brand_id', TRUE);
			$result = $this->crud->getIDProcessing($brand_id_sha1, 'brand_id', 'brand');
			$brand_id = $result->brand_id;
			$table = 'brand';

			$this->db->select('*');
			$this->db->where('brand_id',$brand_id);
			$query=$this->db->get('product');
			if($query->num_rows()>0){
				$data['response'] = 'Sorry! Reference in Product';
				$data['type'] = 'error';
			}
			else{
				$brand_picture = $this->input->post('brand_picture', TRUE);

				if(!empty($brand_picture)){
					unlink('assets/img/brand/'.$brand_picture);
				}

				if ($this->crud->deleteData($brand_id, 'brand_id', $table)) {
					$data['response'] = 'Deleted Successfully';
					$data['type'] = 'success';
				} else {
					$data['response'] = 'Error occurred';
					$data['type'] = 'error';
				}
			}
			echo json_encode($data);
		}
	}
}
