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

class products extends Admin_Controller
{

	function __construct()
	{
		parent::__construct();
	}

	public function index()
	{

		$products  = $this->db->query("SELECT * FROM `products`")->result();
		$warehouse = $this->db->query("SELECT Name, id FROM `warehouse`")->result();
		foreach ($products as $product) {

			$product->all_units = $this->db->query("SELECT SUM(`unit`) as AllUnits
													FROM `customer_invoice_items`
													WHERE store_id > 0
													AND `product_id` = '$product->id'")->row();

			$product->all_units_stores = reindex_by_key($this->db->query("SELECT customer_invoice_items.store_id, warehouse.Name, SUM(`customer_invoice_items`.`unit`) as AllUnits
															FROM `customer_invoice_items`
															LEFT JOIN `warehouse` ON customer_invoice_items.store_id = warehouse.ID
															WHERE store_id > 0
															AND `product_id` = '$product->id'
															GROUP BY `store_id`")->result(), 'store_id');

			$product->all_units_orders	= $this->db->query("SELECT SUM(`unit`) as AllUnits
															FROM `order_items`
															WHERE `store_id` > 0
															AND `product_id` = '$product->id'")->row();
		}

		// if (!empty($product['all_units_stores'])) {
		// 	foreach ($product['all_units_stores'] as $Units) {
		// 		debug($Units['allUnits']);
		// 	}
		// }
		// debug($products);

		// debug($store_amounts);
		$this->template
			->set('view', 'admin/products/index')
			->set('products', $products)
			->set('warehouse', $warehouse)
			->render();
	}

	public function productForm($product_id = '')
	{

		if ($product_id !== NULL && $product_id != '' && $product_id > 0) {
			$product =  $this->general_model->getRowById('products', 'id', $product_id);
			$mode = 'edit';
		} else {
			$product = array();
			$mode = 'add';
		}


		$this->template
			->set('view', 'admin/products/productForm')
			->set('product', $product)
			->render();
	}

	public function productAction($product_id = '')
	{

		$product_data = array(
			'name'              => !empty($this->input->post('name')) ? $this->input->post('name') : '',
			'type'              => $this->input->post('product_type'),
			'description'       => !empty($this->input->post('description')) ? $this->input->post('description') : '',
			'price'             => !empty($this->input->post('price')) ? $this->input->post('price') : '',
			'code'              => !empty($this->input->post('code')) ? $this->input->post('code') : '',
			'category_id'       => !empty($this->input->post('category_id')) ? $this->input->post('category_id') : '',
			'quantity'          => !empty($this->input->post('quantity')) ? $this->input->post('quantity') : '',
			'cartoon_price'     => !empty($this->input->post('cartoon_price')) ? $this->input->post('cartoon_price') : '',
			'manufacturer_id'   => !empty($this->input->post('manufacturer_id')) ? $this->input->post('manufacturer_id') : '',
			'colors'            => !empty($this->input->post('colors')) ? implode(",", $this->input->post('colors')) : '',
			'discount'          => !empty($this->input->post('discount')) ? $this->input->post('discount') : '',
			'status'            => $this->input->post('status') ? 1 : 0,
			'special'           => $this->input->post('special') ? 1 : 0,
			'dateCreation'      => date('Y-m-d H:i:s'),
			'lastUpdate'        => date('Y-m-d H:i:s')
		);
		if ($product_id !== NULL && $product_id != '' && $product_id > 0) {
			$product = $this->general_model->getRowById('products', 'id', $product_id);
			if (!empty($product)) {
				if (!empty($_FILES) && isset($_FILES["main_image"]) && !empty($_FILES["main_image"]["name"])) {
					$upload = $this->uploadImage($_FILES);
					if ($upload !== false) {
						$product_data['main_image'] = $upload['file'];
					} else {
						$product_data['main_image'] = $product->main_image;
					}
				}
				$updateProduct = $this->general_model->updateRowById('products', 'id', $product_id, $product_data);
				$this->session->set_flashdata('flashMsgType', 'Success');
				$this->session->set_flashdata('flashMsg', 'השינויים נשמרו בהצלחה!');
				redirect("admin/products/productForm/$product_id", "refresh");
			} else {
				redirect("admin/products", "refresh");
			}
		} else {
			if (!empty($_FILES) && isset($_FILES["main_image"])) {
				$upload = $this->uploadImage($_FILES);
				if ($upload !== false) {
					$product_data['main_image'] = $upload['file'];
				} else {
					$product_data['main_image'] = '';
				}
			}
			$product_data['cartoon_quantity'] = !empty($this->input->post('cartoon_quantity')) ? $this->input->post('cartoon_quantity') : '';
			$this->session->set_flashdata('flashMsgType', 'Success');
			$this->session->set_flashdata('flashMsg', 'השינויים נשמרו בהצלחה!');
			$product_id = $this->general_model->insertRow('products', $product_data);
			redirect("admin/products/productForm/$product_id", "refresh");
		}
	}

	private function uploadImage()
	{
		if (!empty($_FILES) && isset($_FILES["main_image"]) && !empty($_FILES["main_image"]["name"])) {
			$target_dir     = "/home/callup2bur/public_html/assets/products/";
			$new_name       = time() . basename($_FILES["main_image"]["name"]);
			$target_file    = $target_dir . $new_name;
			$uploadOk       = 1;
			$imageFileType  = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
			$check          = getimagesize($_FILES["main_image"]["tmp_name"]);
			if ($check !== false) {
				if ($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg") {
					if (move_uploaded_file($_FILES["main_image"]["tmp_name"], $target_file)) {
						return array("result" =>  true, "file" => $new_name);
					} else {
						return false;
					}
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public function productTraffic()
	{
		$id = $this->uri->segment('4');;
		$all_traffic =   $this->db->query(" SELECT * FROM 
		                                                (SELECT  `order_id` as `id`, `order_items`.`price`, `order_items`.`product_id`, `unit`, `full_price`, `is_Exit`, (`warehouse`.`Name`) as warehouse, 
			                                         `products`.`name`, `products`.code,  `date_creation` as `dateCreation`, `last_update` as `lastUpdate`, `store_id`, 0 as `is_in`
													FROM `order_items`
													LEFT JOIN `warehouse` ON order_items.store_id = warehouse.ID
													LEFT JOIN `products` ON order_items.product_id = products.id
													WHERE order_items.product_id = '$id'
                                                    UNION    
                                                     SELECT `item_id` as `id`, `item_price` as `price`, `customer_invoice_items`.`product_id`, `unit`, `full_price`, 2 as `is_Exit`,(`warehouse`.`Name`) as warehouse,
												     `products`.`name`, `products`.code, `customer_invoice_items`.`dateCreation`, `customer_invoice_items`.`lastUpdate`,`store_id`, 1 as `is_in`
													FROM `customer_invoice_items`
													LEFT JOIN `warehouse` ON customer_invoice_items.store_id = warehouse.ID
													LEFT JOIN `products` ON customer_invoice_items.product_id = products.id
													WHERE customer_invoice_items.product_id = '$id') AS T order by `lastUpdate`")->result();
		$this->template
			->set('view', 'admin/products/productTraffic')
			->set('all_traffic', $all_traffic)->render();
	}
}
