<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Sales_estimation 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('Stock_model', 'Stock');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Subcontracts_model', 'Subcontracts');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->library('Stock_management','stock_management');
    $this->load->model('Sales_estimation_model','Sales_estimation');
    $this->load->model('Customers_model','Customer');
    $this->load->model('Account_model','Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Branches_model', 'Branches');
    $this->load->library('Accounts_management', 'accounts_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","sales_manager","auditor",'sales_staff','accounts_manager');
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    //        File Directory
    $this->page_data['directory'] = "sales_estimation";
    $this->page_data['tax_state_codes'] = $this->Settings->select_tax_state_codes("*")->result();
    $this->page_data['branches'] = $this->Branches->select_branches("*")->result();
  }
  public function index()
  {
    $this->view();
  }

  public function view()
  {
    $this->page_data['list_type'] = '';
    $this->page_data['material_list'] = $this->Material->select_material()->result();
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['customers'] = $this->Customer->select_customer()->result();
    $data_stock['sl.location_type'] = 'ware_house';
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations($columns="*",$data_stock)->result();
    $this->page_data['page_name'] = 'sales_estimation_view';
    $this->load->view('Index', $this->page_data);
  }
  public function profile($id="")
  {
    if($id!=''){
      $this->page_data['estimation_data'] = $this->Sales_estimation->select_sale_estimation("se.*,ba.*,u.user_alias,c.customer_id,c.customer_name,c.customer_location,tsc.state_name,tsc.state_code,se.branch_id as estimation_branch_id,b.branch_name,b.branch_address,b.workorder_logo", array("se.estimation_id" =>$id ));
      if($this->page_data['estimation_data']->num_rows()==1){
        $this->page_data['estimation_data'] = $this->page_data['estimation_data']->row();
        $this->page_data['estimation_data']->receivable_amount_in_words = $this->accounts_management->amount_in_words($this->page_data['estimation_data']->receivable_amount);
        $this->page_data['page_name'] = 'sales_estimation_profile';

        if($this->page_data['estimation_data']->estimation_branch_id==0){
          $default_branch_data = $this->config->item('default_branch_data');
          $this->page_data['estimation_data']->workorder_logo = $default_branch_data['sales_estimation_logo'];
        }

        $this->page_data['estimation_items'] = $this->Sales_estimation->select_estimation_sale_item("material_name,unit_name,sei.quantity,sei.unit_sale_price,sei.discount_amount,sei.taxable_amount,sei.total_amount,tt.*,sei.description,m.item_code",array("se.estimation_id"=>$id))->result();
        $this->page_data['sales_receipts'] = $this->Account->select_account_transaction("ats.*,ah1.acc_head_name as debit_account,u1.user_alias as created_user", array("ats.reference_id" => $id, "ats.reference_type" => 'sales_estimation'),'sales_estimation')->result();

        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }

  }
  public function add()
  {

    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['terms_and_condition_templates'] = $this->Settings->select_terms_and_condition_templates('',array("terms_type"=>'Sales Estimation'))->result();

    $data_stock['sl.location_type'] = 'ware_house';
    $data_stock['sl.location_branch_id'] = $this->session->userdata('branch_id');
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations($columns="*",$data_stock)->result();

    if($this->session->userdata('user_role')=='supervisor') {

    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['materials'] = $this->Material->select_material()->result();
    $this->page_data['bank_accounts'] = $this->Settings->select_bank_account_details()->result();

    $this->page_data['page_name'] = 'sales_estimation_add';
    $this->load->view('Index', $this->page_data);
  }

  public function create_estimation()
  {
    $data['branch_id'] = $this->session->userdata('branch_id');

    $item_qty_error = 0;
    // Check Items & qty with Stock Register
    $row_count = $this->security->xss_clean($this->input->post('current_row_count'));

    // Cart Items
    $item_data=$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;
      }
    }
    $item_key = 0;
    foreach ($newArrayItems as $row) {

      $item_data[$item_key]['material_id'] = $row['material_id'];
      $item_data[$item_key]['unit_id'] = $row['unit_id'];
      $item_data[$item_key]['unit_stock_price'] = $row['unit_id'];
      $item_data[$item_key]['unit_sale_price'] = $row['unit_price'];
      $item_data[$item_key]['quantity'] = $row['quantity'];
      $item_data[$item_key]['discount_amount'] = $row['disc_amount'];
      $item_data[$item_key]['taxable_amount'] = $row['taxable_amount'];
      $item_data[$item_key]['tax_percent'] = $row['tax_percent'];
      $item_data[$item_key]['tax_amount'] = $row['tax_amount'];
      $item_data[$item_key]['total_amount'] = $row['total_amount'];
      $item_key ++;
    }

    $data['buyer_customer_id'] = $this->security->xss_clean($this->input->post('customer_id'));
    $data['buyer_branch_id'] = $this->security->xss_clean($this->input->post('branch_id'));
    $data['estimation_to'] = $this->security->xss_clean($this->input->post('estimation_to'));
    $data['estimation_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('estimation_date'))));

    $data['buyer_name'] = $this->security->xss_clean($this->input->post('buyer_name'));
    $data['buyer_address'] = $this->security->xss_clean($this->input->post('buyer_address'));
    $data['buyer_phone'] = $this->security->xss_clean($this->input->post('buyer_phone'));
    $data['buyer_taxno'] = $this->security->xss_clean($this->input->post('buyer_taxno'));
    $data['buyer_state_id'] = $this->security->xss_clean($this->input->post('buyer_state_id'));

    // Generate Estimation No
    $estimation_where['se.branch_id'] = $data['branch_id'];
    $estimation_last_data = $this->Sales_estimation->select_sale_estimation("max(se.estimation_no) as max_estimation_no",$estimation_where);
    if($estimation_last_data->num_rows()==1){
      $data['estimation_no'] = ($estimation_last_data->row()->max_estimation_no)+1;
    }else{
      $data['estimation_no'] = 1;
    }

    $data['net_total'] = $this->security->xss_clean($this->input->post('bill_net_total_amount'));
    $data['tax_amount'] = $this->security->xss_clean($this->input->post('bill_tax_amount'));
    $data['round_amount'] = $this->security->xss_clean($this->input->post('bill_round_amount'));
    $data['receivable_amount'] = $this->security->xss_clean($this->input->post('bill_receivable_amount'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');

    //terms and conditions
    $terms_array=$newArrayterms=array();
    if($this->input->post('terms')){
      $terms_array = $this->input->post('terms');
    }
    $terms_array_length = sizeof($terms_array);
    foreach (array_keys($terms_array) as $fieldKey) {
      foreach ($terms_array[$fieldKey] as $key=>$value) {
        $newArrayterms[$key][$fieldKey] = $value;
      }
    }

    $i = 0;
    foreach ($newArrayterms as $row) {
      $terms_new[$i]['description'] = $row['description'];
      $i++;
    }
    if(sizeof($newArrayterms)){
      $data['terms_and_conditions'] = serialize($terms_new);
    }

    $result = $this->Sales_estimation->create_sale_estimation($data);
    $flash_data['status'] = $result['status'];
    if($flash_data['status']==1){
      // Insert Items
      foreach ($item_data as $key => $value) {
        $item_insert_data = array();
        $item_insert_data = $value;
        $item_insert_data['created_date'] = date('Y-m-d H:i:s');
        $item_insert_data['created_by'] = $this->session->userdata('user_id');
        $item_insert_data['estimation_id'] =  $result['insert_id'];
        $result2 = $this->Sales_estimation->create_estimation_items($item_insert_data);
      }

      $flash_data['estimation_id'] = $result['insert_id'];
      $flash_data['flashdata_msg'] = $this->config->item('Quotation_sales_estimation_title').' Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else {
      $flash_data['status'] = 2;
      $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);
  }
  public function select_estimations($list_type=''){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount=0;
    $total_amount1=0;
    $total_amount2=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(se.estimation_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(se.estimation_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['buyer']) && $_POST['buyer']!='' && $_POST['buyer']!='all'){
      $buyer = explode('_',$_POST['buyer']);
      if($buyer[0]=='branch'){
        $data['se.buyer_branch_id'] = $buyer[1];
      }else{
        $data['se.buyer_customer_id'] = $buyer[1];
      }
    }
    if(isset($_POST['branch']) && $_POST['branch']!='' && $_POST['branch']!='all'){
      $data['se.branch_id'] = $_POST['branch'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['se.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(isset($_POST['payment_status']) && $_POST['payment_status']!='' && $_POST['payment_status']!='all'){
      $data['se.payment_status'] = $_POST['payment_status'];
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['se.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Sales_estimation->select_sale_estimation("se.*,b.branch_name,u.user_alias,c.customer_id,c.customer_name,b2.branch_name as buyer_branch_name",$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):
      $bill_id_column=9;
      $btn_edit = $btn_delete = $btn_add_payment='';
      $btn_view='<a style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'sales_estimation/profile/'.$row->estimation_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>';
      if(($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')==$row->created_by) && ($this->session->userdata('user_role')!='auditor') ) {
        // $btn_edit = '<a style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'sales_estimation/edit/' . $row->estimation_id . '" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
        // <i class="la la-edit"></i>
        // </a>';
        // $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="sales_delete_btn" href="#sales_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        // <i class="la la-trash"></i>
        // </a>';
      }
      if($row->balance_amount<=0){
        $payment_status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Received</span>";
      }else{
        if($row->total_received>0){
          $payment_status="<span class='m-badge m-badge--info m-badge--wide'><i class='fa fa-times-circle'></i> Partially Received</span>";
        }else{
          $payment_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Not Received</span>";
        }
        // if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='supervisor' && $this->session->userdata('user_id')==$row->created_by)) {

        // if($this->session->userdata('user_role')!='auditor'){
        //   $btn_add_payment = '<a data-bill-type="sales_estimation" data-bill-id-column="'.$bill_id_column.'" style="margin-left: 5px;margin-right: 5px" id="btn_receive_payment_add" data-toggle="modal"  href="#receive_payment_add_modal" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
        //   <i class="la la-plus-circle"></i>
        //   </a>';
        // }
        // }
      }
      $sl_no++;
      $array[$j][]=$sl_no;
      $array[$j][]='<a href="' . base_url() . 'sales_estimation/profile/' . $row->estimation_id . '">#' .$row->estimation_no . '</a>';
      $array[$j][]=$row->branch_name;
      $array[$j][]=date('d-m-Y',strtotime($row->estimation_date));
      $array[$j][]=$row->buyer_name;
      $array[$j][]=$row->receivable_amount;
      $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Remarks : '.$row->bill_remarks."</li>";
      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',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_view.$btn_edit.$btn_delete;
      $array[$j][]=$row->estimation_id;

      $total_amount=$total_amount+$row->receivable_amount;
      $total_amount1=$total_amount1+$row->total_received;
      $total_amount2=$total_amount2+$row->balance_amount;
      $j++;
    endforeach;

    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$total_amount."</strong>";
      $array[$j][]="<strong>".$total_amount1."</strong>";
      $array[$j][]="<strong>".$total_amount2."</strong>";
      $array[$j][]="";
      $array[$j][]="";


    }

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function get_estimation_details()
  {
    $data = array();
    $json_data['count'] = 0;
    $data['se.estimation_id'] = $_POST['estimation_id'];
    $bill_data = $this->Sales_estimation->select_sale_estimation("se.*,b.branch_name,u.user_alias,c.customer_id,c.customer_name,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data);
    if($bill_data->num_rows()==1){
      $bill_data = $bill_data->row();
      $json_data['count'] = 1;
      $json_data['bill_id'] = "#".$bill_data->estimation_id;
      $json_data['bill_no'] = '#' . $bill_data->estimation_no_prefix.$bill_data->estimation_no;
      $json_data['bill_date'] = date('d-m-Y',strtotime($bill_data->estimation_date));
      $json_data['bill_total_amount'] = number_format($bill_data->receivable_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $json_data['bill_total_paid'] = number_format($bill_data->total_received,$this->config->item('Currency_amount_decimals_2'),'.','');
      $json_data['bill_balance_amount'] = number_format($bill_data->balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $json_data['customer'] = $bill_data->customer_name;
    }

    echo json_encode($json_data);
  }
}
?>
