<?php
defined('BASEPATH') or exit('No direct script access allowed');

class ProductController extends CI_Controller
{


	public function __construct()
	{

		parent::__construct();

		if ($this->session->userdata('admin_logged_in') !== TRUE) {
			redirect('/');
		}

		$this->load->model('dataHandling/crud', 'crud');
		$this->load->model('pages/ProductModel', 'model');
		$this->load->model('TableModel/product/FetchProductData', 'TableModel');
	}

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

	public function newProductEntryProcess()
	{
		if ($this->input->is_ajax_request()) {
			$this->form_validation->set_rules('product_name', 'Product Name', 'required|trim');
			$this->form_validation->set_rules('product_size', 'Product Size', 'required|trim');
			$this->form_validation->set_rules('product_model', 'Product Model', 'required|trim');
			$this->form_validation->set_rules('brand_id', 'Manufacturer', 'required|trim');
			$this->form_validation->set_rules('category_id', 'Category', 'required|trim');
			$this->form_validation->set_rules('sub_category_id', 'Sub Category', 'required|trim');
			$this->form_validation->set_rules('description', 'Description', 'required|trim');

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

				$product_name = $this->input->post('product_name', TRUE);
				$product_size = $this->input->post('product_size', TRUE);
				$product_model = $this->input->post('product_model', TRUE);
				$brand_id = $this->input->post('brand_id', TRUE);
				$category_id = $this->input->post('category_id', TRUE);
				$sub_category_id = $this->input->post('sub_category_id', TRUE);
				$description = $this->input->post('description', TRUE);
				$url = strtolower(trim(str_replace(" ", "-", $product_name)));
				$filtered_url = preg_replace('/[^A-Za-z0-9\-]/', '', $url);
				$tag = $this->input->post('tag', true);
				$filter_result = $this->model->exist_url($filtered_url);
				if($filter_result){
					$dataSet = array(
						'product_name' => $product_name,
						'product_model' => $product_model,
						'brand_id' => $brand_id,
						'category_id' => $category_id,
						'sub_category_id' => $sub_category_id,
						'size' => $product_size,
						'description' => $description,
						'url' => $filtered_url,
						'meta_description' => $this->input->post('meta_description'),
						'tag' => $tag,
					);

					$table = "product";

					if ($this->crud->insertReturnData($dataSet, $table)) {
						$data['response'] = 'Product Added successfully';
						$data['type']='success';
					} else {
						$data['response'] = 'Error Occured';
						$data['type']='error';
					}
				}
				else{
					$data['response'] = 'Product already exist';
					$data['type']='warning';
				}
			} else {
				$data['response'] = 'Validation Error';
				$data['type']='error';
			}
			echo json_encode($data);
		}
	}
	public function getProductData()
	{
		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->product_name;
				$row[] = $data_n->product_model;
				$row[] = $data_n->category_name;
				$row[] = $data_n->sub_category_name;
				$row[] = $data_n->size;
				$row[] = $data_n->availability;
				$row[] = $data_n->status;
				$row[] = $data_n->publish_status;
				$row[] = sha1($data_n->product_id);
				$row[] = $data_n->picture;
				$row[] = $data_n->category_id;
				$row[] = $data_n->sub_category_id;
				$row[] = $data_n->description;
				$row[] = $data_n->brand_id;
				$row[] = $data_n->brand_name;
				$row[] = $data_n->tag;
				$row[] = $data_n->meta_description;
				$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 addProductPicture()
	{
		if ($this->input->is_ajax_request()) {
			$product_id_sha1 = $this->input->post('product_id', TRUE);
			$result = $this->crud->getIDProcessing($product_id_sha1, 'product_id', 'product');
			$product_id = $result->product_id;
			$image_exist = $this->model->exist_image($product_id);
			if (!empty($image_exist->picture)) {
				unlink('assets/img/products/' . $image_exist->picture);
			}
			$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/products/' . $imageName, $image_data);

			$dataSet = array(
				'picture' => $imageName,
				'publish_status' => "Published",
			);
			$table = "product";

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

	public function productEditProcess()
	{
		if ($this->input->is_ajax_request()) {
			$this->form_validation->set_rules('product_name', 'Product Name', 'required|trim');
			$this->form_validation->set_rules('product_size', 'Product Size', 'required|trim');
			$this->form_validation->set_rules('product_model', 'Product Model', 'required|trim');
			$this->form_validation->set_rules('brand_id', 'Manufacturer', 'required|trim');
			$this->form_validation->set_rules('category_id', 'Category', 'required|trim');
			$this->form_validation->set_rules('sub_category_id', 'Sub Category', 'required|trim');
			$this->form_validation->set_rules('description', 'Description', 'required|trim');
			$this->form_validation->set_rules('status', 'Status', 'required|trim');

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

				$product_id_sha1 = $this->input->post('product_id', TRUE);
				$result = $this->crud->getIDProcessing($product_id_sha1, 'product_id', 'product');
				$product_id = $result->product_id;

				$product_name = $this->input->post('product_name', TRUE);
				$product_size = $this->input->post('product_size', TRUE);
				$product_model = $this->input->post('product_model', TRUE);
				$brand_id = $this->input->post('brand_id', TRUE);
				$category_id = $this->input->post('category_id', TRUE);
				$sub_category_id = $this->input->post('sub_category_id', TRUE);
				$description = $this->input->post('description', TRUE);
				$status = $this->input->post('status', TRUE);
				$url = strtolower(trim(str_replace(" ", "-", $product_name)));
				$filtered_url = preg_replace('/[^A-Za-z0-9\-]/', '', $url);
				$tag = $this->input->post('tag', true);
				$filter_result = $this->model->exist_url($filtered_url,$product_id);
				if($filter_result){
					$dataSet = array(
						'product_name' => $product_name,
						'product_model' => $product_model,
						'brand_id' => $brand_id,
						'category_id' => $category_id,
						'sub_category_id' => $sub_category_id,
						'size' => $product_size,
						'description' => $description,
						'status' => $status,
						'url' => $filtered_url,
						'meta_description' => $this->input->post('meta_description'),
						'tag' => $tag,
					);
					$table = "product";

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

	public function deleteProduct()
	{
		if ($this->input->is_ajax_request()) {
			$product_id_sha1 = $this->input->post('product_id', TRUE);
			$result = $this->crud->getIDProcessing($product_id_sha1, 'product_id', 'product');
			$product_id = $result->product_id;
			$table = 'product';

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

			if(!empty($product_picture)){
				unlink('assets/img/products/'.$product_picture);
			}

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