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

class Purchases extends CI_Controller {
	
    var $main_menu_name = "purchases";
	var $sub_menu_name = "categories";

      function __construct() 
      {
        parent::__construct();
        ini_set('display_errors', '1');
        ini_set('display_startup_errors', '1');
        error_reporting(E_ALL);
        date_default_timezone_set("Asia/Colombo");
        $this->load->model('purchases_model');
        $this->load->model('common_model');
		$this->load->model('Sequerty_Model');
        $this->load->library('form_validation');
		$this->load->model('User_Model');
		$this->load->model('Batch_Process_Model');
		$this->load->model('Stock_Counter_Model');
		$this->load->model('Product_Discount_Model');
		$this->load->model('Supplier_Payment_Process_Model');
      }
    public function index($e=0)
    {
      $data['error'] = $e;
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "list_purchases";
      $this->load->view('purchases_list',$data);
    }
    public function get_list_purchases($value='')
    {
           	$requestData= $_REQUEST;	
        	$start=$this->input->get('start');
        	$length=$this->input->get('length');
	        $search=$this->input->get('search');	
            $totalData =$this->purchases_model->get_all_grn("","",$search);
	        $values = $this->purchases_model->get_all_grn($start,$length,$search);
	        $totalFiltered=$totalData;
            $data = array();
            $pay_st;
            if (!empty($values)) {
                foreach ($values as $purchases) {
                    $paid_total=$this->Supplier_Payment_Process_Model->get_grn_total_payment($purchases->id);
                    $return_total=$this->Supplier_Payment_Process_Model->get_grn_return_total_payment($purchases->id);
                    $total_amount=$paid_total+$return_total;
                if ($paid_total==0) {
                  $pay_st = '<span class="label label-warning">Pending</span>';
                }else{
                  if ($purchases->total <= $total_amount) {
                    $pay_st = '<span class="label label-success">Paid</span>';
                  }else{
                    $pay_st = '<span class="label label-info">Partial</span>';
                  }
                }
                $row = array();
                    $row[] = $purchases->date;
                    $row[] = $purchases->reference_no;
                    $row[] = $purchases->supp_company_name;
					$row[] = $purchases->supp_invocie_no;
                    $row[] = number_format($purchases->grand_total,2,'.',',');
                    $row[] = number_format($paid_total,2,'.',',');
                    $row[] = number_format($purchases->grand_total - $total_amount,2,'.',',');
                    $row[] = $pay_st;
                    $row[] = '<div class="text-center"><div class="btn-group text-left">
                    <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                    <ul role="menu" class="dropdown-menu pull-right">
                        <li><a href="'.base_url('purchases_return/add_purchase_return?grn_no='.$purchases->id).'"><i class="fa fa-undo"></i> GRN Return</a></li>
                        <li><a href="'.base_url('purchases/view/'.$purchases->id).'"><i class="fa fa-file-text-o"></i> GRN Details</a></li>
                        <li><a href="#" onClick="delete_grn('.$purchases->id.')"><i class="fa fa-trash text-danger"></i> Delete</a></li> 
                    </ul></div>
                    </div>';
                    $data[] = $row;
                }
                $output = array('data' =>$data,	"recordsTotal"    => intval( $totalData ), 	"recordsFiltered" => intval( $totalFiltered ),);
                echo json_encode($output);
            }else{
                $output = array('data' =>'');
                echo json_encode($output);
            }
       }
    public function add_purchases()
    {
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = 'add_purchases';
      $data['warehouse'] = $this->purchases_model->get_warehouse();
      $data['supplier'] = $this->purchases_model->get_supplier();
      $isst=1;
      if (isset($_POST['submit'])) {
              $this->form_validation->set_rules('supplier', 'supplier', 'required');
              if ($this->form_validation->run() == FALSE)
              {
                $this->load->view('purchases',$data);
              }
              else
              {
                $podate       = $this->input->post('podate');
                $reference_no = $this->input->post('reference_no');
                $supplier     = $this->input->post('supplier');
                $discount     = $this->input->post('discount');
                $powarehouse  = $this->input->post('powarehouse'); 
                $note         = $this->input->post('note');
                $grand_total  = $this->input->post('hgtotal');
                $total        = $this->input->post('total');
                $order_cal_des= $this->input->post('order_cal_des');
				$supp_invocie_no           = $this->input->post('supp_invocie_no');
                $grn_header_id = $this->purchases_model->add_grn_header($podate,$reference_no,$supplier,$discount, $powarehouse,$note , $grand_total,$total,$order_cal_des,$supp_invocie_no);
                if ($grn_header_id) {
                    $product_id_array       = $this->input->post('product_id');
                    $product_array          = $this->input->post('product');
                    $product_name_array     = $this->input->post('product_name');
                    $unit_cost_array        = $this->input->post('unit_cost');
                    $quantity_array         = $this->input->post('quantity');
                    $product_discount_array = $this->input->post('product_discount');
                    $gross_total            = $this->input->post('gross_total');
                    $sub_total              = $this->input->post('subtotal');
                    $discount_cal           = $this->input->post('discount_cal');
                    $retail_price_array     = $this->input->post('retail_price');
                  for ($i=0; $i <count($product_array); $i++) { 
                    $this->purchases_model->add_grn_list_item($product_id_array[$i], $grn_header_id,$product_array[$i], $product_name_array[$i], $unit_cost_array[$i], $quantity_array[$i], $product_discount_array[$i],$gross_total,$sub_total[$i],$discount_cal[$i], $retail_price_array[$i]);
                    //$this->common_model->add_fi_table("grn",$grn_header_id,$product_id_array[$i],$quantity_array[$i],$unit_cost_array[$i]);
                  }
                  //$this->Batch_Process_Model->auto_create_grn_batch($grn_header_id);
                $this->index(1);
                }
              }
        }else{
            $this->load->view('purchases',$data);
        }
    }
    public function get_product_by_code()
    {        
        $emp_array=array();
        $product_code = $this->input->get('term');
		$s_tmp_id = strtotime("now"); 
        $get_product_all_by_id  = $this->purchases_model->get_product_by_code($product_code);
          if (!empty($get_product_all_by_id)) {
            $empar=array();			
            foreach ($get_product_all_by_id as $key => $value) {
            $discount=$this->Product_Discount_Model-> get_relevent_discount_for_pos($get_product_all_by_id[$key]->product_mat_id,1,0);
            $discount_text=" Discount : ".$discount;
            if($discount==0){
                $discount_text="";
            }
              //$r      = $get_product_all_by_id[$key];
              $r=array();
              $r['product_id']=$get_product_all_by_id[$key]->product_mat_id;
              $r['product_name']=$get_product_all_by_id[$key]->product_mat_name;
              $r['product_code']=$get_product_all_by_id[$key]->product_mat_code;
              $r['retail_cash']=$get_product_all_by_id[$key]->product_mat_price;
              $r['product_cost']=$get_product_all_by_id[$key]->product_mat_cost;
              $lb = $get_product_all_by_id[$key]->product_mat_name;	
              $currant_stock=$this->Stock_Counter_Model->get_stock_balance('',$get_product_all_by_id[$key]->product_mat_id);
              $label  = array("id"=>$s_tmp_id,"item_id"=>$get_product_all_by_id[$key]->product_mat_id,"stock_balance"=>$currant_stock,"label"=>$get_product_all_by_id[$key]->product_mat_code.' '.$get_product_all_by_id[$key]->product_mat_name.' / COST Rs.'.$get_product_all_by_id[$key]->product_mat_cost.' / SALE Rs'.$get_product_all_by_id[$key]->product_mat_price.' / Stock : '.$currant_stock." ".$discount_text,"qty"=>1,'row' =>$r,'value'=>$get_product_all_by_id[$key]->product_mat_name,'discount_text'=>$discount_text);
              array_push($empar,$label);		
            }
              echo json_encode($empar);
          } else {
            echo '[{"id":0,"label":"No matching result found! Product might be out of stock in the selected warehouse.","value":"hg"}]';
          }    
    }
    public function purchases_details($purchas_id='')
    {
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "view_purchases";
      $data['po_header'] = $this->purchases_model->getpurchases_by_id($purchas_id);
	  $data['po_middle'] = $this->purchases_model->get_purchese_data_by_id($purchas_id);
      $data['po_payment']= $this->purchases_model->get_payment_by_id($purchas_id);
      $data['po_paid_total'] = $this->purchases_model->grn_pay_total($purchas_id);
      $data['purchas_id'] = $purchas_id;
      $this->load->view('purchases_details',$data);
    }
	function print_purchase($purchas_id='')
    {
      $this->load->model('Warehouse_Model');
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "view_purchases";
      $data['po_header'] = $this->purchases_model->getpurchases_by_id_print($purchas_id);
	  $warehouse_details          = $this->Warehouse_Model->get_warehouse_info($data['po_header'][0]->warehouse_id);
      $data['warehouse_details']  = $warehouse_details;
      $data['po_middle'] = $this->purchases_model->get_purchese_data_by_id($purchas_id);
      $data['po_payment']= $this->purchases_model->get_payment_by_id($purchas_id);
      $data['po_paid_total'] = $this->purchases_model->grn_pay_total($purchas_id);
      $data['purchas_id'] = $purchas_id;
      $this->load->view('models/purchases_print',$data);
    }
    function manual_stock_batch(){
	    //$this->Batch_Process_Model->auto_create_grn_batch(819);
	    //$this->Batch_Process_Model->auto_create_grn_batch(1318);
	}
	
	 public function grn_approval($e=0)
    {
      $data['error'] = $e;
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "grn_approval";
      $this->load->view('grn_approval',$data);
    }
    public function delete_grn()
    {
        $id = $this->input->post('id');
        if (!$id) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid ID']);
            return;
        }
        $deleted = $this->delete_grn_by_id($id);
    
        if ($deleted) {
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Unable to delete. Might be referenced elsewhere.']);
        }
    }
    public function delete_grn_by_id($purchase_id)
    {
        if (!$purchase_id) return false;
        $this->db->trans_begin();
        try {
            // Delete from purchase_items
            $this->db->where('purchase_id', $purchase_id);
            $this->db->delete('purchase_items');
    
            // Delete payments where type = 'GRN' and id = this purchase ID
            $this->db->where('invoice_id', $purchase_id);
            $this->db->delete('payment_given_items');
    
            // Delete main purchase record
            $this->db->where('id', $purchase_id);
            $this->db->delete('purchases');
    
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                return false;
            } else {
                $this->db->trans_commit();
                return true;
            }
        } catch (Exception $e) {
            $this->db->trans_rollback();
            return false;
        }
    }

    public function get_list_purchases_pending_approval($value='')
    {
       $values = $this->purchases_model->get_pending_purchases();
      
        $data = array();
        $pay_st;
        if (!empty($values)) {
            foreach ($values as $purchases) {
                $paid_total=$this->Supplier_Payment_Process_Model->get_grn_total_payment($purchases->id);
                $return_total=$this->Supplier_Payment_Process_Model->get_grn_return_total_payment($purchases->id);
                $total_amount=$paid_total+$return_total;
            if ($paid_total==0) {
              $pay_st = '<span class="label label-warning">Pending</span>';
            }else{
              if ($purchases->total <= $total_amount) {
                $pay_st = '<span class="label label-success">Paid</span>';
              }else{
                $pay_st = '<span class="label label-info">Partial</span>';
              }
            }
            $row = array();
                $row[] = $purchases->date;
                $row[] = $purchases->reference_no;
                $row[] = $purchases->supp_company_name;
				$row[] = $purchases->supp_invocie_no;
                $row[] = number_format($purchases->grand_total,2,'.',',');
                $row[] = number_format($paid_total,2,'.',',');
                $row[] = number_format($purchases->grand_total - $total_amount,2,'.',',');
                $row[] = $pay_st;
                $row[] = 
                '<div class="text-center">
                    <div class="btn-group text-left">
                        <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                        <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="#" onClick="approval_grn('.$purchases->id.')"><i class="fa fa-file-text-o"></i> Approval</a></li>
                            <li><a href="'.base_url('purchases/view/'.$purchases->id).'"><i class="fa fa-file-text-o"></i> GRN Details</a></li>
                            <li><a href="#" onClick="delete_grn('.$purchases->id.')"><i class="fa fa-trash text-danger"></i> Delete</a></li>
                        </ul>
                    </div>
                </div>';
                $data[] = $row;
            }
            $output = array('data' =>$data);
            echo json_encode($output);
        }else{
            $output = array('data' =>'');
            echo json_encode($output);
        }
    }
       
       	function approval_grn()
	{		
		$grn_id=$this->input->get('id');
		$this->Batch_Process_Model->auto_create_grn_batch($grn_id);
		$data_array=array('approval_status'=>1,'approval_by'=>$this->session->userdata('ss_user_id'),'approval_date_time'=> date('Y-m-d H:i:s'));
		$response=$this->purchases_model->approval_grn($data_array,$grn_id);
		$message='Error!. Please try again';
		$status=0;
		if($response==1)
		{
		    $this->Batch_Process_Model->auto_enable_disable_zero_batch_qty($grn_id);
			$message='Sucssesfully Approved';
			$status=1;			
		}		
		$data=array('status'=>$status,'message'=>$message);
		echo json_encode($data);		
	}
}