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

class Stock extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('stock_model','stock');
	}

	// public function update($id){
	// 	$this->permission_check('brand_edit');
	// 	$data=$this->data;

	// 	$this->load->model('brand_model');
	// 	$result=$this->brand_model->get_details($id,$data);
	// 	$data=array_merge($data,$result);
	// 	$data['page_title']=$this->lang->line('brand');
	// 	$this->load->view('brand', $data);
	// }
	// public function update_brand(){
	// 	$this->form_validation->set_rules('brand', 'Brand', 'trim|required');
	// 	$this->form_validation->set_rules('q_id', '', 'trim|required');

	// 	if ($this->form_validation->run() == TRUE) {
	// 		$this->load->model('brand_model');
	// 		$result=$this->brand_model->update_brand();
	// 		echo $result;
	// 	} else {
	// 		echo "Please Enter Brand name.";
	// 	}
	// }

    // public function update_itm_stock(){
	// 	$this->form_validation->set_rules('e_st_id', 'Stock id', 'trim|required');

	// 	if ($this->form_validation->run() == TRUE) {
	// 		$this->load->model('stock_model');
	// 		$result=$this->stock_model->update_itm_stock();
	// 		echo $result;
	// 	} else {
	// 		echo "Please Enter Stock ID.";
	// 	}
	// }


	public function view(){
		$this->permission_check('brand_view');
		$data=$this->data;
		$data['page_title']='Stock List';
		$this->load->view('brand-view', $data);
	}

    public function stock_history(){
		$this->permission_check('expired_items_report');
		$data=$this->data;
		$data['page_title']='Stock History';
		$this->load->view('report-expired-items', $data);
	}

    public function st_details_get(){
		$filter_none_stock = $this->input->post('filter_none_stock');
		$section_id = $this->input->post('section_id');

		if($filter_none_stock=='yes'){
	    	$query=$this->db->query("SELECT db_stock.id , db_items.item_name , db_stock.sku , db_stock.stock_qty , db_stock.cost_price , db_stock.unit_sales_price_01 , db_stock.unit_sales_price_02 , db_stock.unit_sales_price_03 FROM db_stock INNER JOIN db_items ON (db_stock.item_id = db_items.id) WHERE db_stock.stock_qty >0 AND db_stock.section='$section_id';");
		}else{
			$query=$this->db->query("SELECT db_stock.id , db_items.item_name , db_stock.sku , db_stock.stock_qty , db_stock.cost_price , db_stock.unit_sales_price_01 , db_stock.unit_sales_price_02 , db_stock.unit_sales_price_03 FROM db_stock INNER JOIN db_items ON db_stock.item_id = db_items.id WHERE db_stock.section='$section_id'");
		}
		$res['st_info'] = $query->result();
		echo json_encode($res);
	}

    public function stock_info_get(){
        $st_ID = $this->input->post('st_ID');
	    $query=$this->db->query("SELECT db_stock.id , db_items.item_name , db_stock.sku , db_stock.stock_qty , db_stock.cost_price , db_stock.unit_sales_price_01 , db_stock.unit_sales_price_02 , db_stock.unit_sales_price_03 , db_category.category_name , db_color.color , db_size.size FROM db_stock INNER JOIN db_items ON (db_stock.item_id = db_items.id) INNER JOIN db_category ON (db_stock.category_id = db_category.id) INNER JOIN db_color ON (db_color.id = db_stock.color_id) INNER JOIN db_size ON (db_size.id = db_stock.size_id) WHERE db_stock.id='$st_ID';");
		$res['st_id_info'] = $query->result();
		echo json_encode($res);
	}

    public function history_details_get(){
	    $query=$this->db->query("SELECT stock_edit.id , stock_edit.stock_id , db_stock.item_id , db_stock.sku , db_items.item_name , stock_edit.stock_qty_old , stock_edit.stock_qty_new , stock_edit.cost_price_old , stock_edit.cost_price_new , stock_edit.sale_price_1_old , stock_edit.sale_price_1_new , stock_edit.sale_price_2_old , stock_edit.sale_price_2_new , stock_edit.sale_price_3_old , stock_edit.sale_price_3_new , stock_edit.changeDate FROM stock_edit INNER JOIN db_stock ON (stock_edit.stock_id = db_stock.id) INNER JOIN db_items ON (db_stock.item_id = db_items.id);");
		$res['st_info'] = $query->result();
		echo json_encode($res);
	}

    public function stock_edit(){
        $e_st_id = $this->input->post('e_st_id');
        $e_stockQty = $this->input->post('e_stockQty');
        $e_costPrice = $this->input->post('e_costPrice');
        $e_salePrice_1 = $this->input->post('e_salePrice_1');
        $e_salePrice_2 = $this->input->post('e_salePrice_2');
        $e_salePrice_3 = $this->input->post('e_salePrice_3');

		$result=$this->stock->stock_edit($e_st_id,$e_stockQty,$e_costPrice,$e_salePrice_1,$e_salePrice_2,$e_salePrice_3);
		if($result=="success"){
            $res = 'success';
        }else if($result=="failed"){
            $res = 'failed';
        }
        echo json_encode($res);
	}

	public function get_section_qty(){
		$item_id = $this->input->post('item_id');

		// Get section 1 qty
		$query1 = $this->db->query("SELECT SUM(stock_qty) as total_qty FROM db_stock WHERE section='1' AND item_id='$item_id' ORDER BY id DESC LIMIT 1");
		$total_qty = 0;
		if($query1->num_rows() > 0){
			$result1 = $query1->row();
			$total_qty = $result1->total_qty ? $result1->total_qty : 0;
		}

		// Get section 2 qty as ware_total
		$query2 = $this->db->query("SELECT SUM(stock_qty) as ware_total FROM db_stock WHERE section='2' AND item_id='$item_id' ORDER BY id DESC LIMIT 1");
		$ware_total = 0;
		if($query2->num_rows() > 0){
			$result2 = $query2->row();
			$ware_total = $result2->ware_total ? $result2->ware_total : 0;
		}

		echo json_encode(array('total_qty' => $total_qty, 'ware_total' => $ware_total));
	}

	public function stock_transfer(){
		$transfer_item = $this->input->post('transfer_item');
		$from_section = $this->input->post('from_section');
		$to_section = $this->input->post('to_section');
		$transfer_qty = $this->input->post('transfer_qty');
		$added_by = isset($this->session) ? $this->session->userdata('inv_userid') : null;
		$added_date = date('Y-m-d H:i:s');

		$data = array(
			'item_id' => $transfer_item,
			'from_section' => $from_section,
			'to_section' => $to_section,
			'stock_qty' => $transfer_qty,
			'added_by' => $added_by,
			'added_date' => $added_date
		);

		$this->db->insert('db_stock_transfer', $data);

		if($this->db->affected_rows() > 0){
			// Update stock in from_section (only the latest record)
			$this->db->select('id');
			$this->db->from('db_stock');
			$this->db->where('item_id', $transfer_item);
			$this->db->where('section', $from_section);
			$this->db->order_by('id', 'DESC');
			$this->db->limit(1);
			$from_stock = $this->db->get()->row();

			if ($from_stock) {
				$this->db->set('stock_qty', 'stock_qty - '.$transfer_qty, FALSE);
				$this->db->where('id', $from_stock->id);
				$this->db->update('db_stock');
			}

			// Update stock in to_section (only the latest record)
			$this->db->select('id');
			$this->db->from('db_stock');
			$this->db->where('item_id', $transfer_item);
			$this->db->where('section', $to_section);
			$this->db->order_by('id', 'DESC');
			$this->db->limit(1);
			$to_stock = $this->db->get()->row();

			if ($to_stock) {
				$this->db->set('stock_qty', 'stock_qty + '.$transfer_qty, FALSE);
				$this->db->where('id', $to_stock->id);
				$this->db->update('db_stock');
			}

			echo json_encode(array('status' => 'success', 'message' => 'Stock transferred successfully.'));
		} else {
			echo json_encode(array('status' => 'error', 'message' => 'Failed to transfer stock.'));
		}

	}

	public function transfer(){
		$this->permission_check('brand_view');
		$data=$this->data;
		$data['page_title']='Stock Transfer History';
		$this->load->view('transfer-view', $data);
	}

	public function trans_history_info_get()
	{
		$formDate=$this->input->post('from_date');
		$toDate=$this->input->post('to_date');
		$fromSection=$this->input->post('from_section');
		$toSection=$this->input->post('to_section');

			$c_query = $this->db->query("SELECT COUNT(db_stock_transfer.id) AS d_count FROM db_stock_transfer WHERE (DATE(db_stock_transfer.added_date) BETWEEN '$formDate' AND '$toDate') AND db_stock_transfer.from_section='$fromSection' AND db_stock_transfer.to_section='$toSection'");
			$res['data_count_info'] = $c_query->result();
			$query = $this->db->query("SELECT db_stock_transfer.*, db_users.username, f_sec.section_name as from_section_n, to_sec.section_name as to_section_n, db_items.item_name FROM db_stock_transfer INNER JOIN db_users ON db_stock_transfer.added_by = db_users.id INNER JOIN db_items ON db_stock_transfer.item_id = db_items.id INNER JOIN db_section as f_sec ON db_stock_transfer.from_section = f_sec.section_id INNER JOIN db_section as to_sec ON db_stock_transfer.to_section = to_sec.section_id WHERE (DATE(db_stock_transfer.added_date) BETWEEN '$formDate' AND '$toDate') AND db_stock_transfer.from_section = '$fromSection' AND db_stock_transfer.to_section = '$toSection' ORDER BY db_stock_transfer.id DESC");
			$res['stock_info'] = $query->result();
				
		echo json_encode($res);
				
	}

}

