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

class orders extends Admin_Controller
{

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

	public function index()
	{
		$orders = reindex_by_key($this->db->query("SELECT orders.*, customers.customerName FROM `orders`
		LEFT JOIN `customers` ON orders.customerId = customers.customerId
		WHERE orders.`is_closed` = 0 ")->result(), 'id');
		$products   =  reindex_by_key($this->db->query("SELECT * FROM `products`")->result(), 'id');
		foreach($products as $product){
			//$product->quantity = getWarehouseQuantity($warehouse_id, $products_id);
		}
		$customers   =  reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
		foreach ($orders as $o) {
			$o->items  = $this->db->query("SELECT * FROM `order_items` WHERE order_id = $o->id")->result();
		}
		$statues = $this->db->query("SELECT `id`, `text` FROM `status`")->result();
		$warehouse = $this->db->query("SELECT * FROM `warehouse`")->result();




		$this->template
			->set('view', 'admin/orders/index')
			->set('orders', $orders)
			->set('products', $products)
			->set('customers', $customers)
			->set('warehouse', $warehouse)
			->set('statues', $statues)
			->render();
	}

	public function getQuantity()
	{

		if (!empty($_POST) && isset($_POST['productId'])) {

			$productId       = $_POST['productId'];

			$productdata = $this->db->query("SELECT * FROM `products` WHERE `id` = $productId")->row();
			if (!empty($productdata)) {
				$productdata->result   = true;
				echo json_encode($productdata);
			} else {
				echo json_encode(array("result" => false));
			}
		} else {
			echo json_encode(array("result" => false));
		}
	}

	public function action()
	{
		$data = (object)$_POST;
		// debug($data);

		$order_id = getNewOrderNo();
		$date_order = str_replace("/", "-", $data->order_date);
		$delivery_date = str_replace("/", "-", $data->delivery_date);
		if (!empty($data) && !empty($data->items)) {
			$finall_total = 0;
			$items = (object)$data->items;
			for ($i = 0; $i < count($data->items['product_id']); $i++) {
				$price           =  $items->price[$i];
				$units           =  $items->unit[$i];
				$total_price     =  $price * $units;
				$finall_total   += $total_price;
				$productid       = $items->product_id[$i];
				$productDetails  =  getProductDetails($productid);
				// debug($productDetails);
				$instock = getWarehouseQuantity($data->warehouse, $productid);

				$orderItemsData = array(
					'order_id'       => $order_id,
					'product_id'     => $productid,
					'customer_id'    => $data->order_for,
					'item_name'      => $productDetails->name,
					'product_code'   => $items->code[$i],
					'price'          => $items->price[$i],
					'unit'           => $items->unit[$i],
					'left_unit'      => $items->unit[$i],
					'discount'       => 0,
					'full_price'     => $total_price,
					'store_id'       => $data->warehouse,
					'order_date'     => date("Y-m-d H:i:s", strtotime($date_order)),
					'date_creation'  => date('Y-m-d H:i:s'),
					'last_update'    => date('Y-m-d H:i:s')
				);
				$item_insert = $this->general_model->insertRow('order_items', $orderItemsData);
				if (empty($instock)) {
					$ItemData = array(
						'product_id'     => $productid,
						'quantity'       => - ($items->unit[$i]),
						'warehouse_id'   => $data->warehouse,
						'entry_date'     => date('Y-m-d H:i:s'),
						'update_date'    => date('Y-m-d H:i:s')
					);
					$warehouse_insert = $this->general_model->insertRow('warehouse_items', $ItemData);
				}
			}

			$orderData = array(
				'customerId'    => $data->order_for,
				'total'         => $finall_total,
				'status'        => 1,
				'order_date'    =>  date("Y-m-d H:i:s", strtotime($date_order)),
				'delivery_date' =>  date("Y-m-d H:i:s", strtotime($delivery_date)),
				'dateCreation'  => date('Y-m-d H:i:s'),
				'warehouse_id'  => $data->warehouse,
				'lastUpdate'    => date('Y-m-d H:i:s'),
				'bossComment'   => $data->boss_Comment,
				'custComment'   => $data->custComment,
				'comment1'      => $data->comment1,
				'comment2'      => $data->comment2,
			);

			$order_id = $this->general_model->insertRow('orders', $orderData);

			$logData = array(
				'userId	'     => getUserId(),
				'type'        => "orders",
				'type_id'     => $order_id,
				'action'      => "add order",
				'befor'       => "nothing",
				'after'       => "new order & new order items",
				'action_date' => date('Y-m-d H:i:s'),
			);
			$log_id = $this->general_model->insertRow('activities_log', $logData);

			redirect('admin/orders', 'refresh');
		}
		redirect('admin/orders', 'refresh');
	}
	public function orderOutwithInvoice()
	{
		$data = (object)$_POST;
		//  debug($data);
		$status = $this->db->query("SELECT `status` FROM orders WHERE `id` = $data->order_id")->row();
		$is_close =  $this->db->query("SELECT `is_closed` FROM orders WHERE `id` = $data->order_id")->row();
		$items = (object)$data->items;
		$date_invoice = str_replace("/", "-", $data->invoice_date);
		$finall_total = 0;
		if (!empty($data) && !empty($items)) {
			if ($status->status > 1 && $status->status < 4) {
				if ($is_close->is_closed == 0) {
					$invoice_id =  getCustomerNewInvoiceNo();
					for ($i = 0; $i < count($data->items['product']); $i++) {
						$product_id      =  $items->product_id[$i];
						$price           =  $items->price[$i];
						$units           =  $items->unit[$i];
						$total_price     =  $price * $units;
						$finall_total   += $total_price;

						$invoiceItemsData = array(
							'invoice_Id'    => $invoice_id,
							'customerId'    => $data->invoice_customer,
							'product_Id'    => $product_id,
							'item_title'    => $items->product[$i],
							'item_price'    => $items->price[$i],
							'unit'          => $items->unit[$i],
							'full_price'    => $total_price,
							'store_id'      => $data->warehouse,
							'invoice_date'  => date("Y-m-d H:i:s", strtotime($date_invoice)),
							'dateCreation'  => date('Y-m-d H:i:s'),
							'lastUpdate'    => date('Y-m-d H:i:s')
						);

						$item_id = $this->general_model->insertRow('customer_invoice_items', $invoiceItemsData);

						$quantity = getWarehouseQuantity($data->warehouse, $product_id);
						if (!empty($quantity)) {
							$itemWarehouse = $this->db->query("SELECT `ID` FROM `warehouse_items` WHERE `warehouse_id` = $data->warehouse AND  `product_id` = $product_id ")->row();
							$finall_quantity = $quantity - $items->unit[$i];
							$warehouseUpdateData = array(
								'quantity'      => $finall_quantity,
								'update_date'   => date('Y-m-d H:i:s')
							);

							$item_id =  $this->general_model->updateRowById('warehouse_items', 'ID', $itemWarehouse->ID, $warehouseUpdateData);
						}

						if (!empty($data->order_id) && isset($data->order_id)) {
							$oreder_item_details = $this->db->query("SELECT `item_id` , `left_unit` FROM `order_items` WHERE `order_id` = $data->order_id AND `product_id` = $product_id AND `store_id` = $data->warehouse  ")->row();
							// debug($oreder_item_details);
							$unitLeft =  $oreder_item_details->left_unit - $items->unit[$i];
							$update_item = array(
								'left_unit'   => $unitLeft,
								'is_Exit'     => 1,
								'last_update' => date('Y-m-d H:i:s')
							);
							$item_row =  $this->general_model->updateRowById('order_items', 'item_id', $oreder_item_details->item_id, $update_item);
						}
					}
					$order_items = $this->db->query("SELECT `product_id`,`left_unit` FROM `order_items` WHERE `order_id` = $data->order_id AND `is_deleted` = 0 ")->result();
					$counter = 0;
					foreach ($order_items as $item) {
						if ($item->left_unit <> 0) {
							$counter++;
						}
					}
					if ($counter == 0) {
						$status_data = array(
							'is_Exit'    => 1,
							'complete'   => 1,
							'status'     => 4,
						);
						if ($status->status == 1) {
							$update_status = $this->general_model->updateRowById('orders', 'id', $data->order_id, $status_data);
							$logData = array(
								'userId	'     => getUserId(),
								'type'        => "orders",
								'type_id'     => $data->order_id,
								'action'      => "checkout full order with invoice",
								'befor'       => "nothing",
								'after'       => " full order exit, reducing order items from warehouse items",
								'action_date' => date('Y-m-d H:i:s'),
							);
							$log_id = $this->general_model->insertRow('activities_log', $logData);
						} else {
							$update_status = $this->general_model->updateRowById('orders', 'id', $data->order_id, $status_data);
							$logData = array(
								'userId	'     => getUserId(),
								'type'        => "orders",
								'type_id'     =>  $data->order_id,
								'action'      => "checkout partly order with invoice",
								'befor'       => "nothing",
								'after'       => "partly order exit, reducing order items from warehouse items",
								'action_date' => date('Y-m-d H:i:s'),
							);
							$log_id = $this->general_model->insertRow('activities_log', $logData);
						}
					} else {
						$status_data = array(
							'is_Exit'    => 1,
							'status'     => 3,
						);
						$update_status = $this->general_model->updateRowById('orders', 'id', $data->order_id, $status_data);
						$logData = array(
							'userId	'     => getUserId(),
							'type'        => "orders",
							'type_id'     =>  $data->order_id,
							'action'      => "checkout partly order with invoice",
							'befor'       => "nothing",
							'after'       => "partly order exit, reducing order items from warehouse items",
							'action_date' => date('Y-m-d H:i:s'),
						);
						$log_id = $this->general_model->insertRow('activities_log', $logData);
					}

					$MainInvoiceData = array(
						'total'           => $finall_total,
						'invoice_date'    =>  date("Y-m-d H:i:s", strtotime($date_invoice)),
						'customerId'      => $data->invoice_customer,
						'warehouse_id'    => $data->warehouse,
						'order_id'        => $data->order_id,
						'dateCreation'    => date('Y-m-d H:i:s'),
						'lastUpdate'      => date('Y-m-d H:i:s'),
						'bossComment'     => $data->boss_Comment,
						'custComment'     => $data->custComment,
						'Comment1'        => $data->comment1,
						'Comment2'        => $data->comment2,
					);

					$invoice_id = $this->general_model->insertRow('customer_invoices', $MainInvoiceData);
					$logData = array(
						'userId	'     => getUserId(),
						'type'        => "invoices",
						'type_id'     => $invoice_id,
						'action'      => "invoice for exit order",
						'befor'       => "nothing",
						'after'       => " new invoice, new invoice items",
						'action_date' => date('Y-m-d H:i:s'),
					);
					$log_id = $this->general_model->insertRow('activities_log', $logData);

					redirect("admin/orders", 'refresh');
				}
				redirect("admin/orders", 'refresh');
			}
			redirect("admin/orders", 'refresh');
		}
		redirect("admin/orders", 'refresh');
	}
	public function updateaction()
	{
		$data = (object)$_POST;
		// debug($data);
		if ($data->is_closed == 1) {
			if (!empty($data) && isset($data)) {
				$order_row = $this->db->query("SELECT * FROM `order_items` WHERE `order_id` = $data->order_id ")->result();
				if (!empty($order_row) && isset($order_row)) {
					$total = 0;
					$unit  = 0;
					$price = 0;
					$items = (object)$data->items;
					for ($i = 0; $i < count($data->items['product_id']); $i++) {
						$product_id = $items->product_id[$i];
						$order_items = $this->db->query("SELECT `item_id` FROM `order_items` WHERE `order_id` = $data->order_id AND `product_id` = $product_id")->row();
						$unit  = $items->unit[$i];
						$price = $items->price[$i];
						if (!empty($order_items) && isset($order_items)) {
							$updateItemsData = array(
								'item_name'     => $items->name[$i],
								'price'         => $items->price[$i],
								'unit'          => $items->unit[$i],
								'left_unit'      => $items->unit[$i],
								'full_price'    => $unit * $price,
								'store_id'      => $data->warehouse,
								'last_update'   => date('Y-m-d H:i:s')
							);
							$itemUpdate = $this->general_model->updateRowById('order_items', 'item_id', $order_items->item_id, $updateItemsData);
							$logData = array(
								'userId	'     => getUserId(),
								'type'        => "orders",
								'type_id'     => $data->order_id,
								'action'      => "edit_order",
								'befor'       => "nothing",
								'after'       => "change item details",
								'action_date' => date('Y-m-d H:i:s'),
							);
							$log_id = $this->general_model->insertRow('activities_log', $logData);
						} else {
							$addItemsData = array(
								'order_id'       => $data->order_id,
								'product_id'     => $items->product_id[$i],
								'customer_id'    => $data->order_for,
								'item_name'      => $items->name[$i],
								'product_code'   => $items->code[$i],
								'price'          => $items->price[$i],
								'unit'           => $items->unit[$i],
								'left_unit'      => $items->unit[$i],
								'discount'       => 0,
								'full_price'     => $unit * $price,
								'store_id'       => $data->warehouse,
								'order_date'     => date("Y-m-d H:i:s", strtotime($data->order_date)),
								'date_creation'  => date('Y-m-d H:i:s'),
								'last_update'    => date('Y-m-d H:i:s'),
							);
							$itemAdd = $this->general_model->insertRow('order_items', $addItemsData);
							$logData = array(
								'userId	'     => getUserId(),
								'type'        => "orders",
								'type_id'     => $data->order_id,
								'action'      => "edit_order",
								'befor'       => "nothing",
								'after'       => "add item to order",
								'action_date' => date('Y-m-d H:i:s'),
							);
							$log_id = $this->general_model->insertRow('activities_log', $logData);
						}
						$total += $unit * $price;
					}
					$orderData = array(
						'total'          => $total,
						'warehouse_id'   => $data->warehouse,
						'delivery_date'  => date("Y-m-d H:i:s", strtotime($data->delivery_date)),
						'LastUpdate'     => date('Y-m-d H:i:s'),
						'updateComment'  => $data->comment,
					);
					$order = $this->general_model->updateRowById('orders', 'id', $data->order_id, $orderData);
					$logData = array(
						'userId	'     => getUserId(),
						'type'        => "orders",
						'type_id'     => $data->order_id,
						'action'      => "edit_order",
						'befor'       => "nothing",
						'after'       => "edit order details",
						'action_date' => date('Y-m-d H:i:s'),
					);
					$log_id = $this->general_model->insertRow('activities_log', $logData);
					redirect('admin/orders', 'refresh');
				}
				redirect('admin/orders', 'refresh');
			}
			redirect('admin/orders', 'refresh');
		}
		redirect('admin/orders', 'refresh');
	}

	public function view()
	{
		$id = intval($this->uri->segment(4));
		$order = $this->db->query("SELECT * FROM `orders` WHERE id = $id")->row();
		$customerId = $order->customerId;
		$customer = $this->db->query("SELECT * FROM `customers` WHERE customerId = $customerId")->row();
		$order_items  = $this->db->query("SELECT * FROM `order_items` WHERE order_id = $id")->result();


		$this->template
			->set('view', 'admin/orders/view')
			->set('order_items', $order_items)
			->set('order', $order)
			->set('customer', $customer)
			->render();
	}
	public function viewForWarehouse()
	{
		$id = intval($this->uri->segment(4));
		$order = $this->db->query("SELECT * FROM `orders` WHERE id = $id")->row();
		$customerId = $order->customerId;
		$customer = $this->db->query("SELECT * FROM `customers` WHERE customerId = $customerId")->row();
		$order_items  = $this->db->query("SELECT * FROM `order_items` WHERE order_id = $id")->result();


		$this->template
			->set('view', 'admin/orders/viewForWarehouse')
			->set('order_items', $order_items)
			->set('order', $order)
			->set('customer', $customer)
			->render();
	}

	// ajax functions 

	public function editOrder()
	{
		$order_id = $this->input->post('order_id');
		// debug($order_id);
		if (!empty($order_id) && $order_id > 0) {
			$products = $this->db->query("SELECT `product_id` FROM `order_items` WHERE `order_id` = $order_id ")->result();
			// debug($products);
			foreach ($products as $pId) {
				$order_items = $this->db->query("SELECT `item_id` , `unit`, `item_name`, `price`, `discount`, `full_price` , `product_id`, `customer_id` FROM `order_items` WHERE `order_id` = $order_id")->result();
				// debug($order_items);
				foreach ($order_items as $item) {
					$quantity = $this->db->query("SELECT `quantity` FROM `products` WHERE `id` = $item->product_id")->row();
					if (!empty($quantity)) {
						$product_quantity = $quantity->quantity;
					} else {
						$product_quantity = 0;
					}
					$item->quantity = $product_quantity;
					// debug($item->quantity);
				}
			}
			// debug($order_items);
			// foreach( $order_items as $items ){
			//     $items->last_update = date('d/m/Y', strtotime($items->last_update));
			// }
			if (!empty($order_items)) {
				echo json_encode(array("result" => true, "data" => $order_items));
			} else {
				echo json_encode(array("result" => false));
			}
		} else {
			echo json_encode(array("result" => false));
		}
	}

	public function deliveryData()
	{
		$order_id = $this->input->post('order_id');
		// debug($order_id);
		if (!empty($order_id) && $order_id > 0) {
			$order = $this->db->query("SELECT * FROM `orders` WHERE `id` = $order_id ")->row();
			$order->customerName = getCustomerName($order->customerId);
			$order->customerCredite = getCustomerCredit($order->customerId);
			$order->WarehouseName = getWarehouseById($order->warehouse_id);
			$order->order_items = $this->db->query("SELECT * FROM `order_items` WHERE `order_id` = $order_id And `left_unit` <> 0 AND `is_deleted` = 0")->result();
			foreach ($order->order_items as $items) {
				$items->instock =  getWarehouseQuantity($items->store_id, $items->product_id);
			}

			if (!empty($order)) {
				echo json_encode(array("result" => true, "order" => $order,));
			} else {
				echo json_encode(array("result" => false));
			}
		} else {
			echo json_encode(array("result" => false));
		}
	}
	public function deleteOrder()
	{
		$data = $_POST;
		//  debug($_POST['orderArray']);
		$status = "";
		if (isset($_POST['orderArray']) && !empty($_POST['orderArray'])) {
			for ($i = 0; $i < count($_POST['orderArray']); $i++) {
				$order_id = $data['orderArray'][$i];
				$order_data = $this->db->query("SELECT * FROM `orders` WHERE `id` = $order_id")->row();
				if (!empty($order_data) && $order_data->is_closed == 0) {
					$items = $this->db->query("SELECT * FROM `order_items` WHERE `order_id` = $order_id")->result();
					if ($order_data->status == 1) {
						$status = "new";
					} else if ($order_data->status == 2) {
						$status = "approved";
					} else if ($order_data->status == 3) {
						$status = "not complete";
					} else if ($order_data->status == 4) {
						$status = "completed";
					}
					if (!empty($items)) {
						$update_data = array(
							'is_closed'    => 1,
						);
						$updatrow = $this->general_model->updateRowById('orders', 'id', $order_id, $update_data);
						$logData = array(
							'userId	'     => getUserId(),
							'type'        => "orders",
							'type_id'     => $order_id,
							'action'      => "close order",
							'befor'       => "the status is " . $status,
							'after'       => "the status is closed",
							'action_date' => date('Y-m-d H:i:s'),
						);
						$log_id = $this->general_model->insertRow('activities_log', $logData);
					}
				}
			}
			echo json_encode(array("result" => true));
			// } else {
			// 	echo json_encode(array("result" => false, "message" => "Invoice has no items connected to it"));
			// }
			// } else {
			// 	echo json_encode(array("result" => false, "message" => "either the invoice doesn't have data or it has been canceled before"));
			// }
		} else {
			echo json_encode(array("result" => false, "message" => "No Invoice selected"));
		}
	}
	public function deleteOrderItem()
	{
		$data = (object)$_POST;
		if (isset($_POST['order_id']) && !empty($_POST['order_id'])) {
			if (!empty($data->product_id) && isset($data->product_id)) {
				$order_data = $this->db->query("SELECT * FROM `order_items` WHERE `order_id` = $data->order_id AND `product_id` = $data->product_id")->row();
				if (!empty($order_data) && $order_data->is_closed == 0) {
					$updateArray = array(
						'is_deleted'   => 1
					);
					$delete_item =  $this->general_model->updateRowById('order_items', 'item_id', $order_data->item_id, $updateArray);
					$logData = array(
						'userId	'     => getUserId(),
						'type'        => "order_items",
						'type_id'     => $order_data->item_id,
						'action'      => "delete_item",
						'befor'       => "item in order",
						'after'       => "delete item from order",
						'action_date' => date('Y-m-d H:i:s'),
					);
					$log_id = $this->general_model->insertRow('activities_log', $logData);


					echo json_encode(array("result" => true));
				} else {
					echo json_encode(array("result" => false, "message" => "either the invoice doesn't have data or it has been canceled before"));
				}
			} else {
				echo json_encode(array("result" => false, "message" => "No Invoice selected"));
			}
		} else {
			echo json_encode(array("result" => false, "message" => "No Invoice selected"));
		}
	}

	public function confirmOrder()
	{
		$data = (object)$_POST;
		// debug($data->order_id);
		if (isset($data) && !empty($data)) {

			$order_id = $data->order_id;
			$order_data = $this->db->query("SELECT * FROM `orders` WHERE `id` = $order_id")->row();
			if (!empty($order_data) && isset($order_data) && $order_data->status == 1) {
				$items = $this->db->query("SELECT * FROM `order_items` WHERE `order_id` =  $order_id")->result();
				if (!empty($items) && isset($items)) {
					$update_data = array(
						'status'       => $data->status,
						'status_text'  => $data->text,
					);
					$updatrow = $this->general_model->updateRowById('orders', 'id',  $order_id, $update_data);
					$logData = array(
						'userId	'     => getUserId(),
						'type'        => "orders",
						'type_id'     =>  $order_id,
						'action'      => "confirm order",
						'befor'       => "the status is new",
						'after'       => "the status is approved",
						'action_date' => date('Y-m-d H:i:s'),
					);
					$log_id = $this->general_model->insertRow('activities_log', $logData);
				}
			}

			echo json_encode(array("result" => true));
		} else {
			echo json_encode(array("result" => false, "message" => "No Invoice selected"));
		}
	}

	public function getOrderData()
	{
		$id = $_POST['id'];
		if (isset($id) && !empty($id)) {
			$order_data['order_info'] = $this->db->query("SELECT * FROM `orders` WHERE `id` = $id")->row();
			$customerName = getCustomerName($order_data['order_info']->customerId);
			$warehouseName = getWarehouseById($order_data['order_info']->warehouse_id);
			$order_data['order_info']->customerName = $customerName;
			$order_data['order_info']->warehouseName = $warehouseName;
			$customerId = $order_data['order_info']->customerId;

			$order_data['order_info']->order_date = date("d/m/Y", strtotime($order_data['order_info']->order_date));
			$order_data['order_info']->delivery_date = date("d/m/Y", strtotime($order_data['order_info']->delivery_date));
			$customerCredit = $this->db->query("SELECT `credits` FROM `customers` WHERE `customerId` = '$customerId'")->row();
			if (!empty($customerCredit)) {
				$order_data['order_info']->customerCredit = $customerCredit->credits;
			}
			$invoice_items = $this->db->query("SELECT * FROM `order_items` WHERE `order_id` = $id And `is_deleted` = 0 ")->result();
			$order_data['items'] = $invoice_items;

			foreach ($invoice_items as $item) {
				$item->item_title = getItemNameById($item->product_id);
				$item->item_instock = getWarehouseQuantity($order_data['order_info']->warehouse_id, $item->product_id);
				$item->code = $item->product_id;
			}


			// debug($invoice_items);

			echo json_encode(array("result" => true, "data" => $order_data));
		}
	}
	public function getCanceledOrder()
	{
		// $id = $_POST['id'];
		if (1 === 1) {
			$orders = $this->db->query("SELECT * FROM `orders`")->result();
			foreach ($orders as $order) {
				$customerName =  getCustomerName($order->customerId);
				$warehouseName = getWarehouseById($order->warehouse_id);
				$order->customerName = $customerName;
				$order->warehouseName = $warehouseName;
			}


			// debug($invoice_items);

			echo json_encode(array("result" => true, "data" => $orders));
		}
	}
	public function getCustomerDetailsforOrder()
	{
		if (!empty($_POST) && isset($_POST['customerId'])) {
			$customerId        = $_POST['customerId'];
			$customer           = $this->db->query("SELECT `customerId`, `customerName`, `credits`  FROM `customers` WHERE `customerId` = '$customerId' ")->row();
			if (!empty($customer)) {
				$customer->result   = true;
				echo json_encode($customer);
			} else {
				echo json_encode(array("result" => false));
			}
		} else {
			echo json_encode(array("result" => false));
		}
	}
	public function getItems()
	{
		$data = array();
		if (isset($_GET['term']) && !empty($_GET['term'])) {
			$term = $_GET['term'];
			$this->db->select('id, name as text, price');
			$this->db->from('products');
			$this->db->like('name', $term);
			$this->db->group_by(array("name", "price"));
			$data['results'] = $this->db->get()->result();
		} else {
			$data = array();
			$data['results'] = array();
		}
		echo json_encode($data);
	}
	public function getItemPrice()
	{
		$data = array();
		if (isset($_POST['id']) && !empty($_POST['id'])) {
			$id   = $_POST['id'];
			$name = $_POST['text'];
			$warehouse = $_POST['warehouse'];
			$quantity_type = $_POST['quantity_type'];
			
			$this->db->select('id, name as text, price, cartoon_price');
			$this->db->from('products');
			$this->db->where('id', $id);
			$query = $this->db->get()->row();
			if (!empty($query)) {
			    if( $quantity_type == 'cartoon_quantity' ){
				    $data['price'] = $query->cartoon_price;
			    }else{
			        $data['price'] = $query->price;
			    }
				$data['product_id'] = $query->id;
				$data['name'] = $query->text;
				$instock = $this->db->query("SELECT `quantity` FROM `warehouse_items` WHERE `warehouse_id` = $warehouse AND `product_id`= $id ")->row();
				!empty($instock) ? $data['instock'] = $instock->quantity : $data['instock'] = 0;
				echo json_encode($data);
			}
		}
	}
	public function getItemDetails()
	{
		if (isset($_POST['activitiesArray']) && !empty($_POST['activitiesArray'])) {
			$data = array();
			$product = array();
			// debug($_POST);
			foreach ($_POST['activitiesArray'] as $array) {
				// debug($array['productId']);
				if (!empty($array['unitLeft'])) {
					$this->db->select('code, name, order_items.price');
					$this->db->from('products');
					$this->db->join('order_items', 'order_items.product_id = products.id', 'left');
					$this->db->where('id', $array['productId']);
					$query = $this->db->get()->row();
					$product['productId'] = $array['productId'];
					$product['unite'] = $array['unitLeft'];
					$product['price'] = $query->price;
					$product['name'] = $query->name;
					$product['code'] = $query->code;


					$data[] = $product;
				}
			}

			//debug($data);

			echo json_encode(array('result' => true, "data" => $data));
		}
	}
	public function getStatus()
	{
		debug("test");
		if (isset($_GET['term']) && !empty($_GET['term'])) {
			$term = $_GET['term'];
			$result = array();
			$status = $this->db->query("SELECT `id`, `text`
                                         FROM `status` 
                                         WHERE `name` LIKE '%$term%'")->result();

			if (!empty($status)) {
				$result['results'] = $status;
				echo json_encode($result);
			}
		} else {
			$result = array();
			$result['results'] = $_GET['term'];
			echo json_encode($result);
		}
	}
}
