<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Purchase_request extends CI_Controller
{
  public $page_data = array();

  function __construct()
  {
    parent::__construct();
    $this->initial();
  }

  public function initial()
  {
    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");

    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Purchase_request_model', 'Purchase_request');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->library('Stock_management','stock_management');
    $this->load->library('Bills_management','bills_management');
    $this->load->library('Projects_management','projects_management');
    $this->load->library('Push_notification','push_notification');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","purchase_manager","auditor","qs","qs_manager","procurement_engineer","project_manager","accounts_manager","operation_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    $company_details = $this->Settings->select_settings('*',array("settings_category"=>"Company Details"))->result();
    foreach ($company_details as $key => $value) {
      $this->page_data[$value->settings_name] = $value->value;
    }
    //        File Directory
    $this->page_data['directory'] = "purchases_request";

  }
  public function index()
  {
    $this->view();
  }

  public function view($param='')
  {
    // Check Module is Enabled or Not
    if($this->config->item('app_module_purchase_request')==0){
      redirect(base_url().'dashboard', 'refresh');
    }

    $this->page_data['material_list'] = $this->Material->select_material()->result();

    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->page_data['list_type'] = $param;
    $this->page_data['page_name'] = 'purchase_request_view';
    $this->load->view('Index',$this->page_data);
  }
  public function view_items($param='')
  {
    // Check Module is Enabled or Not
    if($this->config->item('app_module_purchase_request')==0){
      redirect(base_url().'dashboard', 'refresh');
    }

    $this->page_data['material_list'] = $this->Material->select_material()->result();

    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->page_data['list_type'] = $param;
    $this->page_data['page_name'] = 'requested_materials';
    $this->load->view('Index',$this->page_data);
  }
  public function add($work_id="")
  {
    // Check Module is Enabled or Not
    if($this->config->item('app_module_purchase_request')==0){
      redirect(base_url().'dashboard', 'refresh');
    }

    $this->page_data['page_name'] = 'purchase_request_add';

    if($work_id!=0){
      $this->page_data['location_data'] = $this->Stock->select_stock_locations("*", array("sl.work_id" =>$work_id));
    }
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();
    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->page_data['material_list'] = $this->Material->select_material()->result();
    $this->page_data['measure_units'] = $this->Material->select_unit()->result();
    $this->page_data['purchase_data'] = $this->Purchases->select_purchase()->result();
    $this->load->view('Index',$this->page_data);

  }
  public function profile($id="")
  {
    // Check Module is Enabled or Not
    if($this->config->item('app_module_purchase_request')==0){
      redirect(base_url().'dashboard', 'refresh');
    }

    if($id!=''){
      $this->page_data['request_data'] = $this->Purchase_request->select_purchase_request("*,pr.created_by as request_created_by,u2.user_alias as approved_user,u.user_alias as created_user,u1.user_alias as approved_1_user,u2.user_alias as approved_2_user", array("pr.request_id" =>$id ));
      if($this->page_data['request_data']->num_rows()==1){
        $this->page_data['request_data'] = $this->page_data['request_data']->row();

        $this->page_data['page_name'] = 'purchase_request_profile';
        if($this->session->userdata('user_role')=='supervisor') {
          //          Select Assigned Works Only
          $supervisor_id = $this->session->userdata('user_id');
          $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
        }
        $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

        $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
        $this->page_data['material_list'] = $this->Material->select_material()->result();
        $this->page_data['measure_units'] = $this->Material->select_unit()->result();

        $this->page_data['request_items'] = $this->Purchase_request->select_purchase_request_items("", array("pri.request_id" =>$id ))->result();
        foreach ($this->page_data['request_items'] as $key => $value) {
          // Get Total Received Quantity
          $value->ordered_qty = $this->Purchase_order->select_purchase_order_items("COALESCE(SUM(poi.quantity),0) as total", array("po.request_id" =>$id,"poi.material_id" =>$value->material_id))->row()->total;
          $value->received_qty = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total", array("po.request_id" =>$id,"pi.material_id"=>$value->material_id),'','','',1,'purchase_order')->row()->total;
        }
        $this->page_data['order_created'] = $this->Purchase_order->select_purchase_order("po.order_id",array("po.request_id"=>$id))->result();
        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function edit($id="")
  {
    // Check Module is Enabled or Not
    if($this->config->item('app_module_purchase_request')==0){
      redirect(base_url().'dashboard', 'refresh');
    }

    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();
    if($id!=''){
      $this->page_data['request_data'] = $this->Purchase_request->select_purchase_request("*,pr.created_by as request_created_by,u2.user_alias as approved_user,u.user_alias as created_user", array("pr.request_id" =>$id ));
      if($this->page_data['request_data']->num_rows()==1 && ($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='qs' || $this->session->userdata('user_role')=='qs_manager' || $this->session->userdata('user_role')=='procurement_engineer' || $this->session->userdata('user_role')=='purchase_manager' || $this->session->userdata('user_role')=='accounts_manager')){
        $this->page_data['request_data'] = $this->page_data['request_data']->row();

        $this->page_data['page_name'] = 'purchase_request_edit';
        if($this->session->userdata('user_role')=='supervisor') {
          //          Select Assigned Works Only
          $supervisor_id = $this->session->userdata('user_id');
          $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
        }
        $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

        $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
        $this->page_data['material_list'] = $this->Material->select_material()->result();
        $this->page_data['measure_units'] = $this->Material->select_unit()->result();

        $this->page_data['request_items'] = $this->Purchase_request->select_purchase_request_items("", array("pri.request_id" =>$id ))->result();
        $this->page_data['order_created'] = $this->Purchase_order->select_purchase_order("po.order_id",array("po.request_id"=>$id))->result();
        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function select_purchase_request($list_type=''){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount_paid=0;

    $data=array();
    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      if(isset($_POST['date_type']) && $_POST['date_type']=='approved_date_1'){
        $data["STR_TO_DATE(pr.approved_date_1,'%Y-%m-%d %H:%i:%s') <="] = $end_date." 23:59:59";
        $data["STR_TO_DATE(pr.approved_date_1,'%Y-%m-%d %H:%i:%s') >="] = $start_date." 00:00:00";
      }elseif(isset($_POST['date_type']) && $_POST['date_type']=='approved_date_2'){
        $data["STR_TO_DATE(pr.approved_date_2,'%Y-%m-%d %H:%i:%s') <="] = $end_date." 23:59:59";
        $data["STR_TO_DATE(pr.approved_date_2,'%Y-%m-%d %H:%i:%s') >="] = $start_date." 00:00:00";
      }else{
        $data["STR_TO_DATE(pr.request_date,'%Y-%m-%d') <="]= $end_date;
        $data["STR_TO_DATE(pr.request_date,'%Y-%m-%d') >="]= $start_date;
      }
    }
    if(isset($_POST['date_type']) && $_POST['date_type']=='approved_date_1'){
      $data['pr.approval_status_1'] = 1;
      if(isset($_POST['start_date']) && $_POST['start_date']!=''){
        $data["STR_TO_DATE(pr.approved_date_1,'%Y-%m-%d %H:%i:%s') >="]= date('Y-m-d', strtotime($_POST['start_date']))." 00:00:00";
      }
      if(isset($_POST['end_date']) && $_POST['end_date']!=''){
        $data["STR_TO_DATE(pr.approved_date_1,'%Y-%m-%d %H:%i:%s') <="]= date('Y-m-d', strtotime($_POST['end_date']))." 23:59:59";
      }
    }elseif(isset($_POST['date_type']) && $_POST['date_type']=='approved_date_2'){
      $data['pr.approval_status_2'] = 1;
      if(isset($_POST['start_date']) && $_POST['start_date']!=''){
        $data["STR_TO_DATE(pr.approved_date_2,'%Y-%m-%d %H:%i:%s') >="]= date('Y-m-d', strtotime($_POST['start_date']))." 00:00:00";
      }
      if(isset($_POST['end_date']) && $_POST['end_date']!=''){
        $data["STR_TO_DATE(pr.approved_date_2,'%Y-%m-%d %H:%i:%s') <="]= date('Y-m-d', strtotime($_POST['end_date']))." 23:59:59";
      }
    }else{
      if(isset($_POST['start_date']) && $_POST['start_date']!=''){
        $data["pr.request_date >="]= date('Y-m-d', strtotime($_POST['start_date']));
      }
      if(isset($_POST['end_date']) && $_POST['end_date']!=''){
        $data["pr.request_date <="]= date('Y-m-d', strtotime($_POST['end_date']));
      }
    }
    if(isset($_POST['location']) && $_POST['location']!='' && $_POST['location']!='all'){
      $data['pr.location_id'] = $_POST['location'];
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['pr.project_stage_id'] = $_POST['stage_id'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['sl.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('sl.work_id',explode(',',$_POST['work_ids']));
    }
    $status = '';
    if(isset($_POST['status']) && $_POST['status']!='' && $_POST['status']!='all'){
      if($_POST['status']==30){
        $status = 'approved_not_created_order';
      }elseif($_POST['status']==0 || $_POST['status']==10 || $_POST['status']==20){
        if($this->config->item('Purchase_purchase_request_second_approval')==1){
          if($_POST['status']==10){
            $data['pr.approval_status_1'] = 0;
          }else{
            $data['pr.approval_status_2'] = 0;
          }
        }else{
          $data['pr.approval_status_1'] = 0;
        }
      }elseif($_POST['status']==2){
        $this->db->where('(pr.approval_status_1=2 or pr.approval_status_2=2)');
      }elseif($_POST['status']==1){
        if($this->config->item('Purchase_purchase_request_second_approval')==1){
          $data['pr.approval_status_1'] = 1;
          $data['pr.approval_status_2'] = 1;
        }else{
          $data['pr.approval_status_1'] = 1;
        }
      }
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['pr.created_by'] = $_POST['user_id'];
    }
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['pr.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Purchase_request->select_purchase_request("pr.*,pr.created_by as created_by,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u1.user_alias as approved_1_user,u2.user_alias as approved_2_user",$data);
    $result_array=$result->result();
    $array=array();

    foreach($result_array as $row):
      $bill_id_column= 10;//Column Where Bill ID Exist
      $btn_view='<a style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'purchase_request/profile/'.$row->request_id.'" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
      <i class="la la-eye"></i>
      </a>';
      $btn_edit = $btn_delete = '';
      $btn_add_payment='';
      $btn_request='';

      $order_created = $this->Purchase_order->select_purchase_order("po.order_id",array("po.request_id"=>$row->request_id));
      if($order_created->num_rows()>0){
        $order_creation_status="<span style='margin-left: 5px;margin-right: 5px' class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check-circle'></i> ".$order_created->num_rows()." Order Created</span>";
      }else{
        $order_creation_status="<span style='margin-left: 5px;margin-right: 5px' class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Order Not Created</span>";
      }
      if($row->closed_status==1){
        $order_creation_status.="<br/><span style='margin-left: 5px;margin-right: 5px;margin-top: 5px' class='m-badge m-badge--info m-badge--wide'><i class='fa fa-check-circle'></i> Request Closed</span>";
      }else{
        $order_creation_status.="<br/><span style='margin-left: 5px;margin-right: 5px;margin-top: 5px' class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Request Open</span>";
      }
      $show = 0;
      if($this->config->item('Purchase_purchase_request_second_approval')==1){
        if($status=='approved_not_created_order' && $row->approval_status_1==1 && $row->approval_status_2==1 && $order_created->num_rows()==0){
          $show = 1;
        }
      }else{
        if($status=='approved_not_created_order' && $row->approval_status_1==1 && $order_created->num_rows()==0){
          $show = 1;
        }
      }
      if($status!='approved_not_created_order'){
        $show = 1;
      }

      if($show==1){
        if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='purchase_manager' || $this->session->userdata('user_role')=='qs' || $this->session->userdata('user_role')=='qs_manager' || $this->session->userdata('user_role')=='project_manager'){
          // $btn_request='<button id="purchase_request_approve_btn" data-toggle="modal" data-target="#purchase_request_approve_modal" style="margin-left: 5px;margin-right: 5px" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
          // <i class="la la-check"></i>
          // </button>';
          $btn_edit='<a style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'purchase_request/edit/' . $row->request_id . '" class="btn btn-focus m-btn m-btn--icon m-btn--icon-only  m-btn--pill m-btn--air">
          <i class="la la-edit"></i>
          </a>';
        }
        if(($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='supervisor') && $row->approval_status_1==1){
          if($this->config->item('Purchase_purchase_request_second_approval')==0 || ($this->config->item('Purchase_purchase_request_second_approval')==1 && $row->approval_status_2==1)){
            $order_creation_status.='<br/><a style="margin-top: 5px;margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'purchase_order/add?request_id=' . $row->request_id . '" class="btn btn-info btn-sm m-btn m-btn--icon   m-btn--pill m-btn--air">
            <i class="la la-plus-circle"></i> Add Purchase Order
            </a>';
          }
        }

        $location_name = $row->location_name;
        if($row->location_type=='work_site'){
          $location_name = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
        }elseif($row->location_type=='ware_house'){
          $location_name = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
        }

        $request_approval_status = $first_level_name = '';
        if($this->config->item('Purchase_purchase_request_second_approval')==1){
          $first_level_name = '1st Level';
        }
        if($row->approval_status_1==1){
          $request_approval_status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> ".$first_level_name." Approved<br/>By ".$row->approved_1_user."<br/>On ".date('d-m-Y',strtotime($row->approved_date_1))."</span>";
          if($this->config->item('Purchase_purchase_request_second_approval')==1){
            if($row->approval_status_2==1){
              $request_approval_status.="<br/><span style='margin-top:5px' class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> 2nd Level Approved<br/>By ".$row->approved_2_user."<br/>On ".date('d-m-Y',strtotime($row->approved_date_2))."</span>";
            }elseif($row->approval_status_2==2){
              $request_approval_status.="<br/><span style='margin-top:5px' class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> 2nd Level Rejected<br/>By ".$row->approved_2_user."<br/>On ".date('d-m-Y',strtotime($row->approved_date_2))."</span>";
            }else{
              $request_approval_status.="<br/><span style='margin-top:5px' class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> 2nd Level Pending</span>";
            }
          }
        }elseif($row->approval_status_1==2){
          $request_approval_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> ".$first_level_name." Rejected<br/>By ".$row->approved_1_user."<br/>On ".date('d-m-Y',strtotime($row->approved_date_1))."</span>";
        }else{
          $request_approval_status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> ".$first_level_name." Pending</span>";
        }


        $sl_no++;
        $remarks = $row->remarks;
        if($this->config->item('Purchase_request_payment_released_status')==1){
          if($row->payment_released_status==1){
            $remarks .= "<br/><span style='margin-top:5px' class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Payment Released <br/>On ".date('d-m-Y H:i:A',strtotime($row->payment_released_date))."</span>";
          }elseif($row->payment_released_status==2){
            $remarks .= "<br/><span style='margin-top:5px' class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Payment Release Cancelled <br/>On ".date('d-m-Y H:i:A',strtotime($row->payment_released_date))."</span>";
          }else{
            $remarks .= "<br/><span style='margin-top:5px' class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Payment Release Pending</span>";
          }
        }

        $array[$j][]=$sl_no;
        $array[$j][]='<a href="' . base_url() . 'purchase_request/profile/' . $row->request_id . '">#' . $row->request_id . '</a>';
        $array[$j][]=date('d-m-Y',strtotime($row->request_date));
        $array[$j][] =$location_name;
        $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->total_est_amount,$this->config->item('Currency_currency_shortname'));
        $array[$j][] =$request_approval_status;
        $array[$j][]=$order_creation_status;
        $array[$j][]=$remarks;
        if ($this->config->item('UI_hide_created_date_field')==0){
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y h:i A',strtotime($row->created_date))."</li><li>Created By : ".$row->user_alias."</li>";
        }else{
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
        }
        $array[$j][]=$btn_request.$btn_add_payment.$btn_view.$btn_edit.$btn_delete;
        $array[$j][]=$row->request_id;
        $array[$j][]=$row->approval_status_1;


        $j++;
      }
    endforeach;


    $json_data['data']=$array;
    $json_data['draw']=5;
    $json_data['recordsTotal']=sizeof($array);
    $json_data['recordsFiltered']=sizeof($array);


    echo json_encode($json_data);  // send data as json format
  }
  public function select_requested_items_list(){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount=$total_qty=$total_without_tax=$total_tax_amount=$total_tax1_amount=$total_tax2_amount=$total_tax3_amount=0;
    $data=array();
    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(pr.request_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(pr.request_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['material']) && $_POST['material']!='' && $_POST['material']!='all'){
      $data['m.material_id'] = $_POST['material'];
    }
    if(isset($_POST['material_category']) && $_POST['material_category']!='' && $_POST['material_category']!='all'){
      $data['m.category'] = $_POST['material_category'];
    }
    if(isset($_POST['unit_id']) && $_POST['unit_id']!='' && $_POST['unit_id']!='all'){
      $data['pri.unit_id'] = $_POST['unit_id'];
    }
    if(isset($_POST['unit_price']) && $_POST['unit_price']!='' && $_POST['unit_price']!='all'){
      $data['pri.unit_price like'] = $_POST['unit_price'];
    }
    if(isset($_POST['location_id']) && $_POST['location_id']!='' && $_POST['location_id']!='all'){
      $data['pr.location_id'] = $_POST['location_id'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['sl.work_id'] = $_POST['work'];
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['pr.project_stage_id'] = $_POST['stage_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['pr.created_by'] = $_POST['user_id'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['pr.request_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['pr.request_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['pr.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Purchase_request->select_purchase_request_items("pri.*,pr.request_date,m.material_name,mu.unit_name,m.item_code,u.user_alias,pr.created_date,pr.location_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data);
    $result_array=$result->result();

    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();

    foreach($result_array as $row):

      $location_name = $row->location_name;
      if($row->location_type=='work_site'){
        $location_name = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
      }elseif($row->location_type=='ware_house'){
        $location_name = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
      }

      $btn_view='<a style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'purchase_request/profile/'.$row->request_id.'" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
      <i class="la la-eye"></i>
      </a>';
      $sl_no++;
      $array[$j][]=$sl_no;
      $array[$j][]='<a href="' . base_url() . 'purchase_request/profile/' . $row->request_id . '">#' . $row->request_id . '</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->request_date));
      $array[$j][] = $location_name;
      $array[$j][]=$row->material_name;
      $array[$j][]=$row->unit_name;
      $array[$j][]=$row->item_code;
      $array[$j][]=$row->quantity;

      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->unit_price,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$row->user_alias;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]=date('d-m-Y',strtotime($row->created_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_view;


      $j++;
    endforeach;


    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function create(){

    $user_details = $this->User->select_user("",array("user_id"=>$this->session->userdata('user_id')));
    if($user_details->row()->branch_id!=0){
      $material_select = 'm.material_unit_price_branch as material_unit_price';
    }else{
      $material_select = 'm.material_unit_price';
    }

    $data['location_id'] = $this->security->xss_clean($this->input->post('location'));
    $data['request_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('request_date'))));
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');

    $location_data=$this->Stock->select_stock_locations("sl.work_id",array("sl.location_id"=>$data['location_id']));
    if($location_data->num_rows()==1){
      $data['project_stage_id'] = $this->projects_management->get_project_stage_id($location_data->row()->work_id);
    }


    $result = $this->Purchase_request->insert_purchase_request($data);
    $flash_data['status'] = $result['status'];
    if($result['status']==1){
      $item_data['request_id'] = $request_data['request_id'] = $result['insert_id'];
      // Insert Cart Items
      $items_array=$newArrayitems=array();
      if($this->input->post('item')){
        $items_array = $this->input->post('item');
      }
      $items_array_length = sizeof($items_array);
      // Convert to New Formatted Array
      foreach (array_keys($items_array) as $fieldKey) {
        foreach ($items_array[$fieldKey] as $key=>$value) {
          $newArrayitems[$key][$fieldKey] = $value;
        }
      }
      $total_est_amount = $grand_total_tax_amount = 0;
      foreach ($newArrayitems as $row) {
        $material_data = $this->Material->select_material("unit,".$material_select,array('material_id'=>$row['material_id']))->row();
        $item_data['material_id'] = $row['material_id'];
        $item_data['quantity'] = $row['quantity'];
        $item_data['unit_id'] = $row['unit_id'];
        $item_data['unit_price']  = $material_data->material_unit_price;
        $item_data['total_amount']  = ($material_data->material_unit_price)*$item_data['quantity'];
        $total_est_amount += $item_data['total_amount'];
        if(isset($row['description'])){
          $item_data['description'] = $row['description'];
        }
        // $item_data['unit_price'] = $item_data['total_amount']/$item_data['quantity'];
        $item_result = $this->Purchase_request->create_purchase_request_item($item_data);
      }

      $request_update_data['request_id'] = $result['insert_id'];
      $request_update_data['total_est_amount'] = $total_est_amount;
      $result3 = $this->Purchase_request->update_purchase_request($request_update_data);

      $flash_data['flashdata_msg'] = 'Purchase Request Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['request_id'] = $request_data['request_id'];

      $request_data_2 = $this->Purchase_request->select_purchase_request("sl.work_id,sl.location_type",array("pr.request_id"=>$request_data['request_id']))->row();
      $flash_data['location_type']=$request_data_2->location_type;
      $flash_data['work_id']=$request_data_2->work_id;
    }else{
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }

    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);  // send data as json format
  }
  public function update(){
    $user_details = $this->User->select_user("",array("user_id"=>$this->session->userdata('user_id')));
    if($user_details->row()->branch_id!=0){
      $material_select = 'm.material_unit_price_branch as material_unit_price';
    }else{
      $material_select = 'm.material_unit_price';
    }

    $data['request_id'] = $this->security->xss_clean($this->input->post('request_id'));
    $request_details = $this->Purchase_request->select_purchase_request("pr.*,pr.created_by as created_by,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u1.user_alias as approved_1_user,u2.user_alias as approved_2_user",array("request_id"=>$data['request_id']))->row();
    $data['location_id'] = $this->security->xss_clean($this->input->post('location'));
    $data['request_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('request_date'))));
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    if($this->config->item('Purchase_request_payment_released_status')==1){
      $data['payment_released_status'] = $this->security->xss_clean($this->input->post('payment_status'));
      if($data['payment_released_status'] !=0 && $request_details->payment_released_status!=$data['payment_released_status']){
        $data['payment_released_date'] = date('Y-m-d H:i:s');
        $data['payment_released_by'] = $this->session->userdata('user_id');
      }
    }
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['updated_by'] = $this->session->userdata('user_id');

    $result = $this->Purchase_request->update_purchase_request($data);
    $flash_data['status'] = $result;
    if($flash_data['status']==1){
      $item_data['request_id'] = $request_data['request_id'] = $data['request_id'];
      // Insert Cart Items
      $items_array=$newArrayitems=array();
      if($this->input->post('item')){
        $items_array = $this->input->post('item');
      }
      $items_array_length = sizeof($items_array);
      // Convert to New Formatted Array
      foreach (array_keys($items_array) as $fieldKey) {
        foreach ($items_array[$fieldKey] as $key=>$value) {
          $newArrayitems[$key][$fieldKey] = $value;
        }
      }
      $total_est_amount = $grand_total_tax_amount = 0;
      foreach ($newArrayitems as $row) {
        $material_data = $this->Material->select_material("unit,".$material_select,array('material_id'=>$row['material_id']))->row();
        $item_data['material_id'] = $row['material_id'];
        $item_data['quantity'] = $row['quantity'];
        $item_data['unit_id'] = $row['unit_id'];
        $item_data['unit_price']  = $row['unit_price'];
        $item_data['total_amount']  = ($row['unit_price'])*$item_data['quantity'];
        $total_est_amount += $item_data['total_amount'];
        if(isset($row['description'])){
          $item_data['description'] = $row['description'];
        }
        if(isset($row['item_id']) && $row['item_id']!=''){
          // Update Existing Data
          $item_data['item_id'] = $row['item_id'];
          $item_result =  $this->Purchase_request->update_purchase_request_item($item_data);
        }else{
          // Create New Data
          unset($item_data['item_id']);
          $item_result = $this->Purchase_request->create_purchase_request_item($item_data);
        }
      }

      // Check Items Deleted
      $deleted_items = $this->security->xss_clean($this->input->post('deleted_items'));
      if($deleted_items!=''){
        $items = explode(',',$deleted_items);
        foreach ($items as $key => $value) {
          $item_data=array();
          $item_data['delete_status'] = 1;
          $item_data['item_id'] = $value;
          $this->Purchase_request->update_purchase_request_item($item_data);
        }
      }

      $request_update_data['request_id'] = $data['request_id'];
      $request_update_data['total_est_amount'] = $total_est_amount;
      $result3 = $this->Purchase_request->update_purchase_request($request_update_data);

      $flash_data['flashdata_msg'] = 'Purchase Request Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['request_id'] = $request_data['request_id'];

      $request_data_2 = $this->Purchase_request->select_purchase_request("sl.work_id,sl.location_type",array("pr.request_id"=>$request_data['request_id']))->row();
      $flash_data['location_type']=$request_data_2->location_type;
      $flash_data['work_id']=$request_data_2->work_id;

      $this->bills_management->update_purchase_request_closed_status($request_data['request_id']);
    }else{
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }

    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);  // send data as json format
  }
  public function approve_request()
  {
    $data['request_id'] = $this->security->xss_clean($this->input->post('request_id'));
    $request_data = $this->Purchase_request->select_purchase_request("pr.*",array("pr.request_id"=>$data['request_id']),'all')->row();
    if($this->input->post('approval_level')==1 && $request_data->approval_status_2==0){
      $data['approval_status_1'] = $this->security->xss_clean($this->input->post('approve_status'));
      $data['approved_by_1'] = $data['updated_by'] = $this->session->userdata('user_id');
      $data['approved_date_1'] = $data['updated_date'] = date('Y-m-d H:i:s');
      $result = $this->Purchase_request->update_purchase_request($data);

      if($this->config->item('Purchase_purchase_request_second_approval')==0){
        // Send Mobile App Notification
        $message = "Purchase Request #".$request_data->request_id." -Date-".date('d-m-Y',strtotime($request_data->request_date))." is ";
        if($data['approval_status_1']==1){
          $message .= 'Approved';
        }else{
          $message .= 'Rejected';
        }
        $this->push_notification->send_notification($request_data->created_by,$message,"Purchase Request Approval",$request_data->request_id);
      }
    }elseif($this->input->post('approval_level')==2 && $request_data->approval_status_1==1){
      $data['approval_status_2'] = $this->security->xss_clean($this->input->post('approve_status'));
      $data['approved_by_2'] = $data['updated_by'] = $this->session->userdata('user_id');
      $data['approved_date_2'] = $data['updated_date'] = date('Y-m-d H:i:s');
      $result = $this->Purchase_request->update_purchase_request($data);

      // Send Mobile App Notification
      $message = "Purchase Request #".$request_data->request_id." -Date-".date('d-m-Y',strtotime($request_data->request_date))." is ";
      if($data['approval_status_2']==1){
        $message .= 'Approved';
      }else{
        $message .= 'Rejected';
      }
      $this->push_notification->send_notification($request_data->created_by,$message,"Purchase Request Approval",$request_data->request_id);
    }
    if(isset($result)){
      $flash_data['status'] = $result;
      if($result==1){
        $flash_data['status'] = 1;
        $flash_data['flashdata_msg'] = 'Purchase request approval status updated Successfully!';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !!';
      }else{
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo(json_encode($flash_data));
  }

}
?>
