<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Boq 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('Subcontracts_model', 'Subcontracts');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Labour_wages_model', 'Labour_wages');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Boq_model', 'Boq');
    $this->load->model('Material_model','Material');
    $this->load->model('Sales_invoice_model','Sales_invoice');
    $this->load->library('Projects_management','projects_management');
    $this->load->library('Stock_management', 'stock_management');
    $this->load->library('Boq_management', 'boq_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","purchase_manager","boq_manager","auditor","qs","qs_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'] = "boq";

  }

  public function profile($id="")
  {
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $id));
    if($id!="" && $boq_data->num_rows()==1) {
      $this->page_data['boq_data'] = $boq_data->row();
      $this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $this->page_data['boq_data']->project_id))->row();
      $this->page_data['stock_materials'] = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$this->page_data['boq_data']->project_id),'sr.material_id')->result();
      $this->page_data['work_types'] = $this->Work->select_work_types()->result();
      $this->page_data['project_work_types'] = $this->Boq->select_project_work_type("",array("pwt.boq_id"=>$id,"pwt.project_id"=>$this->page_data['boq_data']->project_id))->result();
      $this->page_data['measure_units'] = $this->Material->select_unit()->result();
      $this->page_data['materials'] = $this->Material->select_material()->result();

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

    }else{
      show_404();
    }
  }
  public function daily_progress($id="")
  {
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $id));
    if($id!="" && $boq_data->num_rows()==1) {
      $this->page_data['boq_data'] = $boq_data->row();
      $this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $this->page_data['boq_data']->project_id))->row();
      $this->page_data['page_name'] = 'boq_daily_progress_add';
      $this->page_data['work_types'] = $this->Work->select_work_types()->result();
      $this->page_data['project_work_types'] = $this->Boq->select_project_work_type("",array("pwt.boq_id"=>$id,"pwt.project_id"=>$this->page_data['boq_data']->project_id))->result();

      $this->page_data['measure_units'] = $this->Material->select_unit()->result();
      $this->page_data['materials'] = $this->Material->select_material()->result();

      $this->load->view('Index', $this->page_data);

    }else{
      show_404();
    }
  }
  public function dpr_add()
  {
    if ($this->input->post('boq_id') && $this->input->post('date')) {
      $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $this->input->post('boq_id')));
      if($boq_data->num_rows()==1) {
        $this->page_data['work_date'] = $this->input->post('date');
        $this->page_data['boq_data'] = $boq_data->row();
        $this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $this->page_data['boq_data']->project_id))->row();

        $dpr_where['bdp.boq_id'] = $this->input->post('boq_id');
        $dpr_where['bdp.project_id'] = $this->page_data['boq_data']->project_id;
        $dpr_where['bdp.work_date'] = date('Y-m-d',strtotime($this->input->post('date')));
        $dpr_count = $this->Boq->select_boq_dpr('bdp.dpr_id',$dpr_where);
        if($dpr_count->num_rows()==0){
          $this->page_data['work_types'] = $this->Work->select_work_types()->result();
          $this->page_data['project_work_types'] = $this->Boq->select_project_work_type("",array("pwt.boq_id"=>$this->page_data['boq_data']->boq_id,"pwt.project_id"=>$this->page_data['boq_data']->project_id))->result();
          $this->page_data['stock_materials'] = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$this->page_data['boq_data']->project_id),'sr.material_id')->result();
          foreach ($this->page_data['stock_materials'] as $key => $value) {
            $opening_stock_where["sr.stock_date <"] = $purchase_where["p.purchase_date <"] = $transfer_in_where["st.transfer_date <"] = $transfer_out_where["st.transfer_date <"] = $consumed_where["sc.consumption_date <"] = $purchase_return_where["pr.return_date <"] = $sales_invoice_where["si.invoice_date <"] = $material_issue_where["smb.bill_date <"] = $material_issue_return_where["smr.returned_date <"] = $dpr_where['bdp.work_date'];
            $opening_stock_where["sr.material_id"] = $purchase_where["pi.material_id"] = $transfer_in_where["sr2.material_id"] = $purchase_where_today["pi.material_id"] = $transfer_in_where_today["sr2.material_id"] = $transfer_out_where["sr1.material_id"] = $consumed_where["sr.material_id"] = $purchase_return_where["m.material_id"] = $sales_invoice_where["m.material_id"] = $material_issue_where["sr.material_id"] = $material_issue_return_where["sr.material_id"] = $value->material_id;
            $opening_stock_where["sl.work_id"] = $purchase_where["sl.work_id"] = $transfer_in_where["sl2.work_id"] = $purchase_where_today["sl.work_id"] = $transfer_in_where_today["sl2.work_id"] = $transfer_out_where["sl1.work_id"] = $consumed_where["sl.work_id"] = $purchase_return_where["sl.work_id"] = $sales_invoice_where["sl.work_id"] = $material_issue_where["sc.work_id"] = $material_issue_return_where["sc.work_id"] = $this->page_data['boq_data']->project_id;
            $purchase_where_today["p.purchase_date"] = $transfer_in_where_today["st.transfer_date"] = $dpr_where['bdp.work_date'];

            $total_opening_qty = $this->Stock->select_stock_register("COALESCE(SUM(sr.total_opening_qty),0) as total", $opening_stock_where)->row()->total;
            $total_purchased_qty = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total",$purchase_where)->row()->total;
            $total_transferred_in_qty = $this->Stock->select_stock_transfers("COALESCE(SUM(st.transferred_qty),0) as total", $transfer_in_where)->row()->total;
            $total_transferred_out_qty = $this->Stock->select_stock_transfers("COALESCE(SUM(st.transferred_qty),0) as total", $transfer_out_where)->row()->total;
            $total_consumption_qty = $this->Stock->select_stock_consumption("COALESCE(SUM(sc.consumption_qty),0) as total", $consumed_where)->row()->total;
            $total_consumption_qty += $this->Subcontracts->select_material_issue_items("COALESCE(SUM(smi.quantity),0) as total", $material_issue_where)->row()->total;
            $total_consumption_qty -= $this->Subcontracts->select_material_return("COALESCE(SUM(smr.returned_qty),0) as total", $material_issue_return_where)->row()->total;
            $total_purchase_return_qty = $this->Purchases->select_purchase_return("COALESCE(SUM(pr.returned_qty),0) as total", $purchase_return_where)->row()->total;
            $total_sold_qty = $this->Sales_invoice->select_invoice_sale_item("COALESCE(SUM(sii.quantity),0) as total", $sales_invoice_where)->row()->total;
            $value->opening_stock_today = $total_opening_qty+$total_purchased_qty+$total_transferred_in_qty-$total_transferred_out_qty-$total_consumption_qty-$total_sold_qty-$total_purchase_return_qty;

            $total_purchased_qty_today = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total",$purchase_where_today)->row()->total;
            $total_transferred_in_qty_today = $this->Stock->select_stock_transfers("COALESCE(SUM(st.transferred_qty),0) as total", $transfer_in_where_today)->row()->total;
            $value->received_qty_today = $total_purchased_qty_today+$total_transferred_in_qty_today;
          }

          $this->page_data['measure_units'] = $this->Material->select_unit()->result();
          $this->page_data['materials'] = $this->Material->select_material()->result();

          $this->page_data['page_name'] = 'boq_dpr_add';
          $this->load->view('Index', $this->page_data);
        }else{
          $flash_data['status'] = 0;
          $flash_data['flashdata_msg'] = 'Sorry.. DPR of Selected Date & Project is already Submitted!';
          $flash_data['flashdata_type'] = 'warning';
          $flash_data['alert_type'] = 'warning';
          $flash_data['flashdata_title'] = 'Already Submitted !!';
          $this->session->set_flashdata($flash_data);
          redirect($this->input->post('redirect_url'),'refresh');
        }
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function dpr_edit($boq_id,$dpr_id)
  {
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $boq_id));
    if($boq_id!="" && $boq_data->num_rows()==1) {
      $this->page_data['boq_data'] = $boq_data->row();
      $this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $boq_data->row()->project_id))->row();
      $this->page_data['stock_materials'] = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$boq_data->row()->project_id),'sr.material_id')->result();
      foreach ($this->page_data['stock_materials'] as $key88 => $value88) {
        ${'material_total_qty_'.$value88->material_id}=0;
      }
      $task_daily_progress = '';
      $dpr_where1['bdp.dpr_id'] = $dpr_where2['bd.dpr_id'] = $dpr_id;
      $boq_dpr = $this->Boq->select_boq_dpr('bdp.*,u1.user_alias as supervisor_name',$dpr_where1);
      if($boq_dpr->num_rows()==1){
        $this->page_data['dpr'] = $boq_dpr->row();
        $this->page_data['dpr']->dpr_items = $this->Boq->select_boq_dpr_items('bdi.*,bd.*,m.material_name',$dpr_where2)->result();
        foreach ($this->page_data['dpr']->dpr_items as $key55 => $value55) {
          $this->page_data['dpr']->dpr_items[$key55]->item_materials = $this->Boq->select_boq_dpr_item_materials('bdim.*',array("bdim.item_id"=>$value55->item_id))->result();
        }
        $this->page_data['dpr']->material_consumptions = $this->Boq->select_boq_dpr_material_consumption('bdmc.*,m.material_name,mu.unit_name',array("bdmc.dpr_id"=>$boq_dpr->row()->dpr_id))->result();

        foreach ($this->page_data['stock_materials'] as $key => $value) {
          $opening_stock_where["sr.stock_date <"] = $purchase_where["p.purchase_date <"] = $transfer_in_where["st.transfer_date <"] = $transfer_out_where["st.transfer_date <"] = $consumed_where["sc.consumption_date <"] = $purchase_return_where["pr.return_date <"] = $sales_invoice_where["si.invoice_date <"] = $material_issue_where["smb.bill_date <"] = $material_issue_return_where["smr.returned_date <"] = $boq_dpr->row()->work_date;
          $opening_stock_where["sr.material_id"] = $purchase_where["pi.material_id"] = $transfer_in_where["sr2.material_id"] = $purchase_where_today["pi.material_id"] = $transfer_in_where_today["sr2.material_id"] = $transfer_out_where["sr1.material_id"] = $consumed_where["sr.material_id"] = $purchase_return_where["m.material_id"] = $sales_invoice_where["m.material_id"] = $material_issue_where["sr.material_id"] = $material_issue_return_where["sr.material_id"] = $value->material_id;
          $opening_stock_where["sl.work_id"] = $purchase_where["sl.work_id"] = $transfer_in_where["sl2.work_id"] = $purchase_where_today["sl.work_id"] = $transfer_in_where_today["sl2.work_id"] = $transfer_out_where["sl1.work_id"] = $consumed_where["sl.work_id"] = $purchase_return_where["sl.work_id"] = $sales_invoice_where["sl.work_id"] = $material_issue_where["sc.work_id"] = $material_issue_return_where["sc.work_id"] = $this->page_data['boq_data']->project_id;
          $purchase_where_today["p.purchase_date"] = $transfer_in_where_today["st.transfer_date"] = $boq_dpr->row()->work_date;

          $total_opening_qty = $this->Stock->select_stock_register("COALESCE(SUM(sr.total_opening_qty),0) as total", $opening_stock_where)->row()->total;
          $total_purchased_qty = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total",$purchase_where)->row()->total;
          $total_transferred_in_qty = $this->Stock->select_stock_transfers("COALESCE(SUM(st.transferred_qty),0) as total", $transfer_in_where)->row()->total;
          $total_transferred_out_qty = $this->Stock->select_stock_transfers("COALESCE(SUM(st.transferred_qty),0) as total", $transfer_out_where)->row()->total;
          $total_consumption_qty = $this->Stock->select_stock_consumption("COALESCE(SUM(sc.consumption_qty),0) as total", $consumed_where)->row()->total;
          $total_consumption_qty += $this->Subcontracts->select_material_issue_items("COALESCE(SUM(smi.quantity),0) as total", $material_issue_where)->row()->total;
          $total_consumption_qty -= $this->Subcontracts->select_material_return("COALESCE(SUM(smr.returned_qty),0) as total", $material_issue_return_where)->row()->total;
          $total_purchase_return_qty = $this->Purchases->select_purchase_return("COALESCE(SUM(pr.returned_qty),0) as total", $purchase_return_where)->row()->total;
          $total_sold_qty = $this->Sales_invoice->select_invoice_sale_item("COALESCE(SUM(sii.quantity),0) as total", $sales_invoice_where)->row()->total;
          $value->opening_stock_today = $total_opening_qty+$total_purchased_qty+$total_transferred_in_qty-$total_transferred_out_qty-$total_consumption_qty-$total_sold_qty-$total_purchase_return_qty;

          $total_purchased_qty_today = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total",$purchase_where_today)->row()->total;
          $total_transferred_in_qty_today = $this->Stock->select_stock_transfers("COALESCE(SUM(st.transferred_qty),0) as total", $transfer_in_where_today)->row()->total;
          $value->received_qty_today = $total_purchased_qty_today+$total_transferred_in_qty_today;
        }

        $this->page_data['measure_units'] = $this->Material->select_unit()->result();
        $this->page_data['materials'] = $this->Material->select_material()->result();

        $this->page_data['page_name'] = 'boq_dpr_edit';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function details_edit($id="")
  {
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $id));
    if($id!="" && $boq_data->num_rows()==1) {
      $this->page_data['boq_data'] = $boq_data->row();
      $this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $this->page_data['boq_data']->project_id))->row();
      $this->page_data['page_name'] = 'boq_details_edit';
      $this->page_data['work_types'] = $this->Work->select_work_types()->result();
      $this->page_data['project_work_types'] = $this->Boq->select_project_work_type("",array("pwt.boq_id"=>$id,"pwt.project_id"=>$this->page_data['boq_data']->project_id))->result();

      $this->page_data['measure_units'] = $this->Material->select_unit()->result();
      $this->page_data['materials'] = $this->Material->select_material()->result();

      $this->load->view('Index', $this->page_data);

    }else{
      show_404();
    }
  }
  public function print($id="",$print_type='')
  {
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $id));
    if($id!="" && $boq_data->num_rows()==1) {
      $this->page_data['boq_data'] = $boq_data->row();$this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $boq_data->row()->project_id))->row();
      $this->page_data['page_name'] = 'boq_print';
      $this->page_data['print_type'] = $print_type;
      $this->page_data['work_types'] = $this->Work->select_work_types()->result();
      $this->page_data['project_work_types'] = $this->Boq->select_project_work_type("",array("pwt.boq_id"=>$id,"pwt.project_id"=>$this->page_data['boq_data']->project_id))->result();
      $this->page_data['total_boq_amt'] =$this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount",array("bt.boq_id"=>$id))->row()->total_amount;
      foreach($this->page_data['project_work_types'] as $row){
        $work_type_id=$row->id;
        $type_id=$row->type_id;
        $type_name=$row->type_name;

        $data2['bt.project_work_type_id']=$work_type_id;
        $data2['bt.boq_id']=$id;
        $boq_task_sum = $this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount",$data2);
        if($boq_task_sum->num_rows()==1){
          $row->boq_task_sum=number_format((float)$boq_task_sum->row()->total_amount, 3, '.', '');
        }else{
          $row->boq_task_sum=0;
        }
        $row->boq_tasks=$this->Boq->select_task("",$data2)->result();

        foreach ($row->boq_tasks as $row2){
          $task_id = $row2->task_id;
          $project_work_type_id = $row2->project_work_type_id;
          $data3['bt.boq_id']=$id;
          $data3['bt.project_work_type_id']=$project_work_type_id;
          $data3['bti.boq_task_id']=$task_id;
          $data3['bti.delete_status']=0;
          $column = "bt.project_work_type_id,mu.unit_name,bt.task_id,bt.boq_id,bt.description,bt.project_work_type_id,bt.item_sl_no,bt.qty,bt.unit as psuedo_unit, bt.unit_price,bt.total_price,bt.created_date,bt.created_by,bt.updated_by,bt.updated_date,bti.*,m.material_id,m.material_name,m.unit as psuedo_unit2,b.*";
          $row2->task_items = $this->Boq->select_task_items($column,$data3)->result();
        }
      }

      $this->load->view('Index', $this->page_data);
    }else{
      show_404();
    }
  }
  public function print_dpr($id="",$date='')
  {
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $id));
    if($id!="" && $boq_data->num_rows()==1) {
      $this->page_data['boq_data'] = $boq_data->row();
      $this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $boq_data->row()->project_id))->row();
      $this->page_data['stock_materials'] = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$boq_data->row()->project_id),'sr.material_id')->result();
      foreach ($this->page_data['stock_materials'] as $key88 => $value88) {
        ${'material_total_qty_'.$value88->material_id}=0;
      }
      $task_daily_progress = '';
      $dpr_where1['bdp.project_id'] = $dpr_where2['bd.project_id'] = $boq_data->row()->project_id;
      $dpr_where1['bdp.boq_id'] = $dpr_where2['bd.boq_id'] = $id;
      $dpr_where1['bdp.work_date'] = $dpr_where2['bd.work_date'] = date('Y-m-d',strtotime($date));
      $boq_dpr = $this->Boq->select_boq_dpr('bdp.*,u1.user_alias as supervisor_name,sc.sub_work_name,c.contractor_name',$dpr_where1);
      if($boq_dpr->num_rows()==1){
        $this->page_data['dpr'] = $boq_dpr->row();
        $this->page_data['dpr']->dpr_items = $this->Boq->select_boq_dpr_items('bdi.*,bd.*,m.material_name',$dpr_where2)->result();
        foreach ($this->page_data['dpr']->dpr_items as $key55 => $value55) {
          $this->page_data['dpr']->dpr_items[$key55]->item_materials = $this->Boq->select_boq_dpr_item_materials('bdim.*',array("bdim.item_id"=>$value55->item_id))->result();
        }
        $this->page_data['dpr']->material_consumptions = $this->Boq->select_boq_dpr_material_consumption('bdmc.*,m.material_name,mu.unit_name',array("bdmc.dpr_id"=>$boq_dpr->row()->dpr_id))->result();
      }else{
        show_404();
      }

      $this->page_data['page_name'] = 'boq_dpr_print';
      $this->load->view('Index', $this->page_data);
    }else{
      show_404();
    }
  }
  public function print_dpr_summary($id="",$date='')
  {
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $id));
    if($id!="" && $boq_data->num_rows()==1) {
      $this->page_data['boq_data'] = $boq_data->row();
      $this->page_data['project_data'] = $this->Work->select_work("*", array("work_id" => $boq_data->row()->project_id))->row();
      $this->page_data['stock_materials'] = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$boq_data->row()->project_id),'sr.material_id')->result();
      foreach ($this->page_data['stock_materials'] as $key88 => $value88) {
        ${'material_total_qty_'.$value88->material_id}=0;
        $value88->consumable_type='item_wise';

        $data3['bt.boq_id']=$id;
        $data3['bti.item_type']='material';
        $data3['bti.material_id']=$value88->material_id;
        $boq_task_item_details=$this->Boq->select_task_items('bti.*',$data3)->result();
        foreach ($boq_task_item_details as $key99 => $value99) {
          if($value99->consumable_type=='common'){
            $value88->consumable_type='common';
          }
        }

      }
      $task_daily_progress = '';
      $dpr_where1['bdp.project_id'] = $dpr_where2['bd.project_id'] = $boq_data->row()->project_id;
      $dpr_where1['bdp.boq_id'] = $dpr_where2['bd.boq_id'] = $id;
      // $dpr_where1['bdp.work_date'] = $dpr_where2['bd.work_date'] = date('Y-m-d',strtotime($date));
      $this->page_data['dpr'] = $this->Boq->select_boq_dpr('bdp.*,u1.user_alias as supervisor_name',$dpr_where1,'',array("bdp.work_date",'asc'))->result();
      foreach ($this->page_data['dpr'] as $key => $value) {
        $dpr_where2['bdi.dpr_id'] = $value->dpr_id;
        $value->dpr_items = $this->Boq->select_boq_dpr_items('bdi.*,bd.*,m.material_name',$dpr_where2)->result();
        foreach ($value->dpr_items as $key55 => $value55) {
          $value55->item_materials = $this->Boq->select_boq_dpr_item_materials('bdim.*',array("bdim.item_id"=>$value55->item_id))->result();
        }
        $value->material_consumptions = $this->Boq->select_boq_dpr_material_consumption('bdmc.*,m.material_name,mu.unit_name',array("bdmc.dpr_id"=>$value->dpr_id))->result();
      }
      $this->page_data['page_name'] = 'boq_dpr_summary_print';
      $this->load->view('Index', $this->page_data);
    }else{
      show_404();
    }
  }
  public function create_boq(){

    if($this->session->userdata('user_role')=='admin'){
      $boq_approval_status = 1;
    }else{
      $boq_approval_status = 0;
    }

    $data['project_id'] = $this->input->post('work_id');
    $data['work_order_no'] = $this->input->post('work_order_no');
    $data['file_attachment'] = $this->input->post('file_link');
    $data['boq_name'] = $this->input->post('name');
    $data['created_by'] = $this->session->userdata('user_id');
    $data['created_date'] =  date('Y-m-d H:i:s');
    $data['boq_approval_status'] = $boq_approval_status;
    $data['project_stage_id'] = $this->projects_management->get_project_stage_id($data['project_id']);

    $result = $this->Boq->insert_boq($data);
    $flash_data['status'] = $result['status'];
    if($result['status'] == 1){
      $flash_data['boq_id'] = $result['insert_id'];
      $flash_data['flashdata_msg'] = 'BOQ: '. $data['boq_name'] .' added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }
    else{
      $flash_data['flashdata_msg'] = 'BOQ adding failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }

    echo(json_encode($flash_data));

  }
  public function update_boq(){
    $data['boq_id'] = $this->input->post('boq_id');
    $data['project_id'] = $this->input->post('work_id');
    $data['work_order_no'] = $this->input->post('work_order_no');
    $data['file_attachment'] = $this->input->post('file_link');
    $data['boq_name'] = $this->input->post('name');
    $data['updated_by'] = $this->session->userdata('user_id');
    $data['updated_date'] =  date('Y-m-d H:i:s');

    $result = $this->Boq->update_boq($data,$data['boq_id']);
    $flash_data['status'] = $result;
    if($result == 1){
      $flash_data['flashdata_msg'] = 'BOQ Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }
    else{
      $flash_data['flashdata_msg'] = 'BOQ Updating failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }

    echo(json_encode($flash_data));

  }
  public function update_boq_details(){

    $boq_id = $this->input->post('boq_id');
    $data['reference_no'] = $this->input->post('reference_no');
    $data['boq_date'] = date('Y-m-d',strtotime($this->input->post('date')));
    $data['boq_description'] = $this->input->post('boq_description');

    //material description
    $material_description_array=$newArraymaterial_description=array();
    if($this->input->post('material_description')){
      $material_description_array = $this->input->post('material_description');
      $material_description_array_length = sizeof($material_description_array);
      foreach (array_keys($material_description_array) as $fieldKey) {
        foreach ($material_description_array[$fieldKey] as $key=>$value) {
          $newArraymaterial_description[$key][$fieldKey] = $value;
        }
      }
      $i = 0;
      foreach ($newArraymaterial_description as $row) {
        $material_description_new[$i]['title'] = $row['title'];
        $material_description_new[$i]['description'] = $row['description'];
        $i++;
      }
      $data['materials_description'] = serialize($material_description_new);
    }else{
      $data['materials_description'] = '';
    }

    //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]['title'] = $row['title'];
        $terms_new[$i]['description'] = $row['description'];
        $i++;
      }
      $data['terms_and_conditions'] = serialize($terms_new);
    }else{
      $data['terms_and_conditions'] = '';
    }

    $result = $this->Boq->update_boq($data,$boq_id);
    $flash_data['status'] = $result;
    if($result == 1){
      $flash_data['flashdata_msg'] = 'BOQ Details Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }
    else{
      $flash_data['flashdata_msg'] = 'BOQ Updating failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }

    echo(json_encode($flash_data));
  }
  public function delete_boq()
  {
    $project_id = $this->input->post('work_id');
    $boq_id = $this->input->post('boq_delete_id');
    $data = array('delete_status' => '1', );
    $result = $this->Boq->update_boq($data,$boq_id);
    $flash_data['status'] = $result;
    if($result == 1){

      $flash_data['flashdata_msg'] = 'BOQ deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }
    else{

      $flash_data['flashdata_msg'] = 'BOQ Deleting failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }

    echo(json_encode($flash_data));
  }
  public function select_boq() {

    $json_data=array();
    $data=array();
    if(isset($_POST['work_id']) && $_POST['work_id']!='' && $_POST['work_id']!='all'){
      $data['b.project_id'] = $_POST['work_id'];
    }
    // if($this->config->item('user_data_access_view_all')!=1){
    //   $data['b.created_by'] = $this->session->userdata('user_id');
    // }
    $result	= $this->Boq->select_boq("b.*", $data);
    $result_array=$result->result();

    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    $sl_no=$j=0;
    foreach($result_array as $row){
      $sl_no++;
      $btn_edit = $btn_delete= $btn_status ='';
      $btn_view = '<a style="margin-left: 5px;margin-right: 5px" href="'.base_url().'boq/profile/'.$row->boq_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) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="boq_edit_btn" class="btn btn-success m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air" data-toggle="modal" data-target="#boq_edit_modal"><i class="la la-edit "></i>';
        $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="boq_delete_btn" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air" data-toggle="modal" data-target="#boq_delete_modal"><i class="la la-trash "></i>';
      }
      if($this->session->userdata('user_role')=='admin'){
        $btn_status = '<a style="margin-left: 5px;margin-right: 5px" id="boq_status_btn" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air" data-toggle="modal" data-target="#boq_status_modal"><i class="la la-forward"></i>';
      }
      if($this->session->userdata('user_role')=='general_manager' ){
        $data2['u.user_id'] = $row->created_by;
        $user = $this->User->select_user("ur.role_name",$data2)->result();
        foreach($user as $u){
          if($u->role_name=='admin'){
            $btn_edit = $btn_delete= '';
          }
        }
      }

      if($row->boq_approval_status==1){
        $status = "<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check-circle'></i> Approved</span>";
      }else{
        $status = "<span class='m-badge m-badge--warning m-badge--wide'><i class='fas fa-exclamation-circle'></i> Pending</span>";
      }

      $file_attachment='';
      if($row->file_attachment!=''){
        $file_attachment = "<a target='_blank' href='".$row->file_attachment."'> ".$row->file_attachment."</span>";
      }

      $array[$j][]=$sl_no;
      $array[$j][]=$row->boq_id;
      $array[$j][]=$row->boq_name;
      $array[$j][]=$row->work_order_no;
      $array[$j][]=$this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount",array('bt.boq_id'=>$row->boq_id))->row()->total_amount;
      $array[$j][]=$status;
      $array[$j][]=$file_attachment;
      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.$btn_status.$btn_edit.$btn_delete;
      $array[$j][]=$row->boq_approval_status;
      $array[$j][]=$row->file_attachment;


      $j++;
    }
    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }

  public function update_approval_status()
  {
    $boq_id = $this->input->post('boq_id');
    $data['boq_approval_status'] = $this->input->post('status');

    $result = $this->Boq->update_boq($data,$boq_id);
    $flash_data['status'] = $result;
    if($result == 1){

      $flash_data['flashdata_msg'] = 'BOQ Status updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }
    else{

      $flash_data['flashdata_msg'] = 'BOQ status updating failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }

    echo(json_encode($flash_data));
  }

  public function create_project_work_type()
  {
    $boq_id = $this->input->post('boq_id');
    $project_id = $this->input->post('project_id');

    $works_cat = $this->input->post('works_cat');
    $created_by = $this->session->userdata('user_id');
    $created_date = date('Y-m-d H:i:s');
    $data2['pwt.project_id'] = $project_id;
    $data2['pwt.work_type_id'] = $works_cat;
    $data2['pwt.boq_id'] = $boq_id;
    $res=$this->Boq->select_project_work_type("",$data2);
    $res = $res->result();
    if(empty($res)){
      $data = array('project_id' => $project_id , 'boq_id' => $boq_id,'work_type_id' => $works_cat, 'created_by' => $created_by, 'created_date' => $created_date);
      $result = $this->Boq->insert_project_work_type($data);
      $flash_data['status'] = $result['status'];
      if($result['status'] == 1){
        $flash_data['flashdata_msg'] = 'Project Work Category Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }
      else{
        $flash_data['flashdata_msg'] = 'Project Work Category Adding failed !.';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Failed !';
      }
    }
    else{
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Project Work Category already Exist !.';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Already Added  !';
    }
    // echo(json_encode($flash_data));
    $this->session->set_flashdata($flash_data);
    redirect($this->input->post('redirect_url'),'refresh');
  }
  public function delete_project_work_type()
  {
    $project_work_type_id = $this->security->xss_clean($this->input->post('project_work_type_id'));
    $boq_id = $this->security->xss_clean($this->input->post('boq_id'));

    $where['id'] = $project_work_type_id;
    $data['delete_status'] = '1';

    $result=$this->Boq->update_project_work_type($data,$where);
    if($result == '1')
    {
      $flash_data['flashdata_msg'] = 'Work Type Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else{
      $flash_data['flashdata_msg'] = 'Work Type Deleting failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }
    $this->session->set_flashdata($flash_data);
    redirect(base_url(). 'boq/profile/'.$boq_id,'refresh');
  }

  public function create_boq_tasks($id='')
  {
    if($id!="") {
      $boq_items_have = $this->input->post('boq_items_have_add');
      $items_count = $this->input->post('current_row_count');
      $project_id = $this->input->post('project_id');
      $data['boq_id'] = $boq_id = $this->input->post('boq_id');
      $data['project_work_type_id'] = $this->input->post('work_type_id');
      $data['description'] = $this->input->post('description');
      $data['qty'] = $this->input->post('quantity');
      $data['unit'] = $this->input->post('unit');
      $data['total_price'] = $this->input->post('total_price');
      if($boq_items_have == 0 && $this->input->post('task_unit_price') && $this->input->post('task_unit_price')!=''){
        $data['unit_price'] = $this->input->post('task_unit_price');
      }else{
        if($data['total_price']!=0 && $data['qty']!=0){
          $data['unit_price'] = round($data['total_price']/$data['qty'],$this->config->item('Currency_amount_decimals_2'));
        }else{
          $data['unit_price'] = 0;
        }
      }
      $data['client_unit_price'] = $this->input->post('client_unit_price');
      $data['client_tax_percent'] = $this->input->post('client_tax_percent');
      $data['client_tax_amount'] = $this->input->post('client_tax_amount');
      $data['client_total_price'] = $this->input->post('client_total_price');
      $data['created_by'] = $this->session->userdata('user_id');
      $data['created_date'] = date('Y-m-d H:i:s');
      $result = $this->Boq->insert_boq_tasks($data);

      if($boq_items_have == 1 && $items_count > 0){
        for ($i=0; $i < $items_count ; $i++)
        {
          $items = array();
          $items['boq_task_id'] = $result['insert_id'];
          $items['item_type'] = $this->input->post('item[type]['.$i.']');
          if($items['item_type']=='material'){
            $items['material_id'] = $this->input->post('item[material]['.$i.']');
          }else{
            $items['item_name'] = $this->input->post('item[name]['.$i.']');
          }
          $items['grade'] = $this->input->post('item[grade]['.$i.']');
          $items['spec'] = $this->input->post('item[spec]['.$i.']');
          $items['unit'] = $this->input->post('item[unit]['.$i.']');
          $items['qnty'] = $this->input->post('item[quantity]['.$i.']');
          $items['unit_rate'] = $this->input->post('item[unit_price]['.$i.']');
          $items['total_amount'] = $this->input->post('item[total_price]['.$i.']');
          if($this->config->item('BOQ_dpr_template')==2){
            $items['consumable_type'] = $this->input->post('item[consumable_type]['.$i.']');
          }
          $items['created_by'] = $this->session->userdata('user_id');
          $items['created_date'] = date('Y-m-d H:i:s');
          $result_items = $this->Boq->insert_boq_task_items($items);
        }
      }

      if($result['status'] == 1){
        $flash_data['flashdata_msg'] = 'BOQ Task added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }else{
        $flash_data['flashdata_msg'] = 'BOQ Task adding failed !.';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Failed !';
      }
      $this->session->set_flashdata($flash_data);
      redirect(base_url(). 'boq/profile/'.$boq_id,'refresh');
    }else{
      show_404();
    }
  }
  public function update_boq_tasks()
  {
    $boq_items_have = $this->input->post('boq_items_have_edit');
    $items_count = $this->input->post('current_row_count_edit');
    $project_id = $this->input->post('project_id');
    $data['boq_id'] = $boq_id = $this->input->post('boq_id');
    $data_where['task_id'] = $this->input->post('boq_task_id_edit');
    $data['project_work_type_id'] = $this->input->post('work_type_id');
    $data['description'] = $this->input->post('description_edit');
    $data['qty'] = $this->input->post('quantity_edit');
    $data['unit'] = $this->input->post('unit_edit');
    $data['total_price'] = $this->input->post('total_price_edit');
    if($boq_items_have == 0 && $this->input->post('task_unit_price') && $this->input->post('task_unit_price')!=''){
      $data['unit_price'] = $this->input->post('task_unit_price');
    }else{
      if($data['total_price']!=0 && $data['qty']!=0){
        $data['unit_price'] = round($data['total_price']/$data['qty'],$this->config->item('Currency_amount_decimals_2'));
      }else{
        $data['unit_price'] = 0;
      }
    }
    $data['client_unit_price'] = $this->input->post('client_unit_price');
    $data['client_tax_percent'] = $this->input->post('client_tax_percent');
    $data['client_tax_amount'] = $this->input->post('client_tax_amount');
    $data['client_total_price'] = $this->input->post('client_total_price');
    $data['updated_by'] = $this->session->userdata('user_id');
    $data['updated_date'] = date('Y-m-d H:i:s');
    $result = $this->Boq->update_boq_task($data,$data_where);


    // $items_deleted = array();
    $items_deleted = $this->input->post('items_deleted');
    $items_deleted = explode(',', $items_deleted);
    foreach ($items_deleted as $deleted) {
      $delete_data['delete_status'] = '1';
      $delete_where['item_id'] =  $deleted;
      $delete_result = $this->Boq->update_boq_task_items($delete_data,$delete_where);
    }

    if($boq_items_have == 1 && $items_count > 0){
      for ($i=0; $i < $items_count ; $i++)
      {
        $items = array();
        $item_id = $this->input->post('item[item_id]['.$i.']');
        $items['item_type'] = $this->input->post('item[type_edit]['.$i.']');
        if($items['item_type']!=''){
          if($items['item_type']=='material'){
            $items['material_id'] = $this->input->post('item[material]['.$i.']');
            $items['item_name'] = '';
          }else{
            $items['material_id'] = 0;
            $items['item_name'] = $this->input->post('item[name]['.$i.']');
          }
          $items['grade'] = $this->input->post('item[grade]['.$i.']');
          $items['spec'] = $this->input->post('item[spec]['.$i.']');
          $items['unit'] = $this->input->post('item[unit]['.$i.']');
          $items['qnty'] = $this->input->post('item[quantity]['.$i.']');
          $items['unit_rate'] = $this->input->post('item[unit_price]['.$i.']');
          $items['total_amount'] = $this->input->post('item[total_price]['.$i.']');
          if($this->config->item('BOQ_dpr_template')==2){
            $items['consumable_type'] = $this->input->post('item[consumable_type]['.$i.']');
          }
          // $result_items = $this->Boq->insert_boq_task_items($items);
          if($item_id!=''){
            $items['updated_by'] = $this->session->userdata('user_id');
            $items['updated_date'] = date('Y-m-d H:i:s');
            $update_where['item_id'] =  $item_id;
            $result_items = $this->Boq->update_boq_task_items($items,$update_where);
          }else{
            $items['boq_task_id'] = $this->input->post('boq_task_id_edit');
            $items['created_by'] = $this->session->userdata('user_id');
            $items['created_date'] = date('Y-m-d H:i:s');
            $result_items = $this->Boq->insert_boq_task_items($items);
          }
        }
      }
    }

    if($result == 1){
      $flash_data['flashdata_msg'] = 'Project Task Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else{
      $flash_data['flashdata_msg'] = 'Project Task Updating failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }
    $this->session->set_flashdata($flash_data);
    redirect(base_url(). 'boq/profile/'.$boq_id,'refresh');

  }
  public function delete_boq_task()
  {
    $task_id = $this->security->xss_clean($this->input->post('boq_task_id_delete'));
    $boq_id = $this->security->xss_clean($this->input->post('boq_id_delete2'));

    $where['task_id'] = $where2['boq_task_id'] = $task_id;
    $data['delete_status'] = '1';

    $result=$this->Boq->update_boq_task($data,$where);
    if($result == '1')
    {
      $flash_data['flashdata_msg'] = 'Task Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else{
      $flash_data['flashdata_msg'] = 'Task Deleting failed !.';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Failed !';
    }
    $this->session->set_flashdata($flash_data);
    redirect(base_url(). 'boq/profile/'.$boq_id,'refresh');

  }
  public function select_boq_task_list() {

    $data=array();
    $project_id = $this->security->xss_clean($this->input->post('project_id'));
    $project_data = $this->Work->select_work("*", array("work_id" =>$project_id))->row();
    $boq_id = $this->security->xss_clean($this->input->post('boq_id'));
    $data['pwt.project_id'] = $project_id;
    $data['pwt.boq_id'] = $boq_id;
    //      Select Work Category
    $res=$this->Boq->select_project_work_type("",$data);
    $tasks_table_body='';
    $tasks_table_summary='';
    $total_acheived_amount=$total_boq_client_amt=0;
    $total_boq_amt=$this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount",array("bt.boq_id"=>$boq_id))->row()->total_amount;
    $works_count=$res->num_rows();
    if($works_count>0){
      $tasks_table_summary.='<tr>'.
      '<td></td>'.
      '<td style="display: none"></td>'.
      '<td colspan="10" style="text-align: center"><strong>SUMMARY</strong></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td></td>'.
      '<td></td>'.
      '<td></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none" class="delete_column"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '</tr>';

      $priority=1;

      foreach($res->result() as $row):

        $work_type_id=$row->id;
        $type_id=$row->type_id;
        $type_name=$row->type_name;

        $data2['bt.project_work_type_id']=$work_type_id;
        $data2['bt.boq_id']=$boq_id;
        $res2=$this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount,COALESCE(SUM(bt.client_total_price),0) as client_total_amount",$data2);

        if($res2->num_rows()==1){
          $total_amt_sum=number_format((float)$res2->row()->total_amount, 3, '.', '');
          $total_client_sum=number_format((float)$res2->row()->client_total_amount, 3, '.', '');
        }else{
          $total_amt_sum=$total_client_sum=0;
        }


        $tasks_table_body.='<tr>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td><strong>'.$priority.'</strong></td>'.
        '<td colspan="9"><strong>'.$type_name.'</strong></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td style="display: none"></td>';
        if($row->created_by == $this->session->userdata('user_id')){
          $tasks_table_body.= '<td  class="delete_column"><a style="margin-left: 5px;margin-right: 5px" id="btn_boq_work_type_delete" onclick="$(\'#boq_work_type_delete\').val(\'' . $work_type_id . '\');$(\'#boq_id_work_type_delete\').val(\'' . $boq_id . '\')" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_work_type_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a></td>';
        }else{
          $tasks_table_body.= '<td  class="delete_column"></td>';
        }
        $tasks_table_body.='<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '</tr>';

        $daily_progress_work_type_sum_where['type'] = 'boq_task';
        $daily_progress_work_type_sum_where['bdp.project_work_type_id'] = $work_type_id;
        $daily_progress_work_type_sum_where['bdp.boq_id'] = $boq_id;
        $daily_progress_work_type_sum = round($this->Boq->select_boq_daily_progress('COALESCE(SUM(bdp.quantity*bdp.unit_rate),0) as total',$daily_progress_work_type_sum_where,'','','',true)->row()->total,$this->config->item('Currency_amount_decimals_2'));
        $total_acheived_amount += $daily_progress_work_type_sum;

        $tasks_table_summary.='<tr>'.
        '<td></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td colspan="4"><strong>'.$type_name.'</strong></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td ><strong>'.number_format($total_amt_sum,$this->config->item('Currency_amount_decimals_2'),'.','').'</strong></td>'.
        '<td ></td>'.
        '<td ></td>'.
        '<td ></td>'.
        '<td ><strong>'.number_format($total_client_sum,$this->config->item('Currency_amount_decimals_2'),'.','').'</strong></td>'.
        '<td></td>'.
        '<td ><strong>'.number_format($daily_progress_work_type_sum,$this->config->item('Currency_amount_decimals_2'),'.','').'</strong></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none" class="delete_column"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '</tr>';
        //              Select Tasks

        $res2=$this->Boq->select_task("",$data2);
        $task_count=$res2->num_rows();

        $sub_total=0;
        if($task_count>0) {
          $priority2 = 1;
          $j=1;
          foreach ($res2->result() as $row2):
            $unit_name = $row2->unit_name;
            $priority3 = $priority.'.'.$priority2;
            $task_id = $row2->task_id;
            $project_work_type_id = $row2->project_work_type_id;
            $description = $row2->description;
            $qnty = $row2->qty;
            $unit = $row2->unit;
            $unit_price = $row2->unit_price;
            $total_price = $row2->total_price;
            $unit_price_client = $row2->client_unit_price;
            $client_tax_percent = $row2->tax_percentage;
            $client_tax_amount = $row2->client_tax_amount;
            $total_price_client = $row2->client_total_price;
            $total_boq_client_amt += $row2->client_total_price;
            $data3['bt.boq_id']=$boq_id;
            $data3['bt.project_work_type_id']=$project_work_type_id;
            $data3['bti.boq_task_id']=$task_id;
            $data3['bti.delete_status']=0;
            $column = "bt.project_work_type_id,mu.unit_name,bt.task_id,bt.boq_id,bt.description,bt.project_work_type_id,bt.item_sl_no,bt.qty,bt.unit as psuedo_unit, bt.unit_price,bt.total_price,bt.created_date,bt.created_by,bt.updated_by,bt.updated_date,bti.*,m.material_id,m.material_name,m.unit as psuedo_unit2,b.*";
            $res3=$this->Boq->select_task_items($column,$data3);
            $task_item_count=$res3->num_rows();
            $boq_id = $row2->boq_id;
            $work_type_id = $row2->project_work_type_id;
            if($qnty!=0 && $total_price!=0){
              $task_unit_price = round($total_price/$qnty,$this->config->item('Currency_amount_decimals_2'));
            }else{
              $task_unit_price = 0;
            }

            if($this->config->item('BOQ_dpr_template')==2){
              if($project_data->project_section=='Road Studs' || $project_data->project_section=='Sign Boards' || $project_data->project_section=='Crash Barrier'){
                $total_task_acheived = $this->Boq->select_boq_dpr_item_materials('COALESCE(SUM(bdim.quantity),0) as total_qty',array("bd.boq_id"=>$boq_id))->row();
                $total_task_acheived->total_amount = 0;
              }
            }else{
              $daily_progress_data_where['type'] = 'boq_task';
              $daily_progress_data_where['reference_id'] = $task_id;
              $daily_progress_data_where['bdp.boq_id'] = $boq_id;
              $total_task_acheived = $this->Boq->select_boq_daily_progress('COALESCE(SUM(bdp.quantity),0) as total_qty,COALESCE(SUM(bdp.quantity*bdp.unit_rate),0) as total_amount',$daily_progress_data_where)->row();
            }
            $tasks_table_body.=
            '<tr>'.
            '<td style="display: none">'.$task_id.'</td>'.
            '<td style="display: none"></td>'.
            '<td><strong>'.$priority3.'</strong></td>'.
            '<td >'.$description.'</td>'.
            '<td>'.number_format($qnty,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
            '<td>'.$unit_name.'</td>'.
            '<td>'.number_format($task_unit_price,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
            '<td>'.number_format($total_price,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td>'.number_format($unit_price_client,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
            '<td>'.$client_tax_percent.'</td>'.
            '<td>'.number_format($client_tax_amount,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
            '<td>'.number_format($total_price_client,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>';
            if(isset($total_task_acheived)){
              $tasks_table_body.='<td>'.number_format($total_task_acheived->total_qty,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
              '<td>'.number_format(($total_task_acheived->total_amount),$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
              '<td>'.number_format(($qnty-$total_task_acheived->total_qty),$this->config->item('Currency_amount_decimals_2'),'.','').'</td>';
            }else{
              $tasks_table_body.='<td></td>'.
              '<td></td>'.
              '<td></td>';
            }
            if($row->created_by == $this->session->userdata('user_id') || $this->session->userdata('user_role')=='admin'){
              $tasks_table_body.='<td class="edit_column">
              <a style="margin-left: 5px;margin-right: 5px" id="btn_boq_task_edit" data-boq-id="'.$boq_id.'" data-item-count="'.$task_item_count.'" class="btn btn-success m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_task_edit_modal" data-toggle="modal"><i class="la la-edit"></i></a>
              <a style="margin-left: 5px;margin-right: 5px" id="btn_boq_task_delete" onclick="$(\'#boq_task_id_delete\').val(\'' . $task_id . '\');$(\'#boq_id_delete2\').val(\'' . $boq_id . '\');" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_task_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a>
              </td>';
            }else{
              $tasks_table_body.='<td class="edit_column"></td>';
            }
            $tasks_table_body.='<td style="display: none"></td>'.
            '<td style="display: none">'.$row2->unit.'</td>'.
            '<td style="display: none">'.$row2->project_work_type_id.'</td>'.
            '<td style="display: none">'.$description.'</td>'.
            '<td style="display: none">'.$row2->client_tax_percent.'</td>'.
            '</tr>';
            $sub_total=$sub_total+$total_price;
            $priority2++;
            if($task_item_count>0){
              $tasks_table_body.= '<tr>'.
              '<td ></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td colspan="11" class="right" style=" font-weight: 500;font-style: italic;  ">Item Requirements </td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td style="display:none"></td>'.
              '<td ></td>'.
              '<td ></td>'.
              '<td style="display:none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '</tr>';
              $priority4=1;
              foreach ($res3->result() as $row3):
                if(($row3->item_type)=="other" && $row3->item_name !='0') {
                  $material_name = $row3->item_name;
                }else{
                  $material_name = $row3->material_name;
                }
                if($row3->consumable_type=='common'){
                  $material_name .= ' [Common Consumable]';
                }
                $unit_name = $row3->unit_name;

                if($this->config->item('BOQ_dpr_template')==2){
                  $total_item_acheived = $this->Boq->select_boq_dpr_item_materials('COALESCE(SUM(bdim.quantity),0) as total_qty',array("bd.boq_id"=>$boq_id,"bdim.material_id"=>$row3->material_id))->row();
                  $total_item_acheived->total_amount = 0;
                }else{
                  $daily_progress_data_where['type'] = 'boq_task_item';
                  $daily_progress_data_where['reference_id'] = $row3->item_id;
                  $daily_progress_data_where['bdp.boq_id'] = $boq_id;
                  $total_item_acheived = $this->Boq->select_boq_daily_progress('COALESCE(SUM(bdp.quantity),0) as total_qty,COALESCE(SUM(bdp.quantity*bdp.unit_rate),0) as total_amount',$daily_progress_data_where)->row();
                }

                $tasks_table_body.=
                '<tr>'.
                '<td style="display: none"></td>'.
                '<td style="display: none">'.$task_id.'</td>'.
                '<td>'.$priority3.'.'.$priority4.'</td>'.
                '<td>'.$material_name.'</td>'.
                '<td>'.number_format($row3->qnty,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
                '<td>'.$unit_name.'</td>'.
                '<td>'.number_format($row3->unit_rate,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
                '<td>'.number_format($row3->total_amount,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
                '<td ></td>'.
                '<td ></td>'.
                '<td ></td>'.
                '<td ></td>'.
                '<td >'.number_format($total_item_acheived->total_qty,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
                '<td >'.number_format($total_item_acheived->total_amount,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
                '<td >'.number_format(($row3->qnty-$total_item_acheived->total_qty),$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
                '<td ></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '</tr>';
                $priority4++;
              endforeach;
              $tasks_table_body.='<tr>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td colspan="7" class="right"></td>'.
              '<td></td>'.
              '<td></td>'.
              '<td></td>'.
              '<td></td>'.
              '<td></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td></td>'.
              '<td></td>'.
              '<td style="display: none" class="delete_column"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '<td style="display: none"></td>'.
              '</tr>';
            }

          endforeach;
        }
        $tasks_table_body.='<tr>'.
        '<td></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td colspan="4" class="right">Sub Total : to be carried to summary</td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td>'.number_format($sub_total,$this->config->item('Currency_amount_decimals_2'),'.','').'</td>'.
        '<td></td>'.
        '<td style="display: none"></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td></td>'.
        '<td style="display: none" class="delete_column"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '<td style="display: none"></td>'.
        '</tr>';
        $priority++;
      endforeach;
      $tasks_table_summary.='<tr>'.
      '<td></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td colspan="4"><strong>Total Amount</strong></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td ><strong>'.$this->config->item("Currency_currency_format").' ' .number_format($total_boq_amt,$this->config->item('Currency_amount_decimals_2'),'.','').' </strong></td>'.
      '<td></td>'.
      '<td></td>'.
      '<td></td>'.
      '<td><strong>'.$this->config->item("Currency_currency_format").' ' .number_format($total_boq_client_amt,$this->config->item('Currency_amount_decimals_2'),'.','').' </strong></td>'.
      '<td></td>'.
      '<td ><strong>'.$this->config->item("Currency_currency_format").' ' .number_format($total_acheived_amount,$this->config->item('Currency_amount_decimals_2'),'.','').' </strong></td>'.
      '<td></td>'.
      '<td></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none" class="delete_column"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '<td style="display: none"></td>'.
      '</tr>';
      $table_content=$tasks_table_body.$tasks_table_summary;
      echo json_encode(array("work_count"=>$works_count,"content"=>$table_content));
    }else{
      echo json_encode(array("work_count"=>$works_count));
    }
  }

  public function select_boq_task_list_consumption() {

    $data=array();
    $project_id = $this->security->xss_clean($this->input->post('project_id'));
    $boq_id = $this->security->xss_clean($this->input->post('boq_id'));
    $data['pwt.project_id'] = $project_id;
    $data['pwt.boq_id'] = $boq_id;
    //      Select Work Category
    $res=$this->Boq->select_project_work_type("",$data);
    $tasks_table_body='';
    $tasks_table_summary='';
    $total_boq_amt=$this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount",array("bt.boq_id"=>$boq_id))->row()->total_amount;
    $works_count=$res->num_rows();
    if($works_count>0){

      $priority=1;

      foreach($res->result() as $row):

        $work_type_id=$row->id;
        $type_id=$row->type_id;
        $type_name=$row->type_name;

        $data2['bt.project_work_type_id']=$work_type_id;
        $data2['bt.boq_id']=$boq_id;
        $res2=$this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount",$data2);

        if($res2->num_rows()==1){
          $total_amt_sum=number_format((float)$res2->row()->total_amount, 3, '.', '');
        }else{
          $total_amt_sum=0;
        }


        $tasks_table_body.='<tr>'.
        '<td style="padding: 5px !important;">'.
        '<div class="m-form__group form-group" style="margin-bottom: 2rem;">
        <div class="m-checkbox-list">
        <label class="m-checkbox m-checkbox--bold m-checkbox--state-success">
        <input type="checkbox" data-id="'.$row->id.'" data-child="checkbox_work_type_'.$row->id.'" data-checkbox-type="work_type" class="checkbox_display">
        <span></span>
        </label>
        </div>
        </div>'.
        '</td>'.
        '<td></td>'.
        '<td></td>'.
        '<td><strong>'.$priority.'</strong></td>'.
        '<td colspan="8"><strong>'.$type_name.'</strong></td>'.
        '<td style="display:none"></td>'.
        '<td style="display:none"></td>'.
        '<td style="display:none"></td>'.
        '<td style="display:none"></td>'.
        '<td style="display:none"></td>'.
        '<td style="display:none"></td>'.
        '<td style="display:none"></td>'.
        '</tr>';

        //              Select Tasks

        $res2=$this->Boq->select_task("",$data2);
        $task_count=$res2->num_rows();

        $sub_total=0;
        if($task_count>0) {
          $priority2 = 1;
          $j=1;
          foreach ($res2->result() as $row2):
            $unit_name = $row2->unit_name;
            $priority3 = $priority.'.'.$priority2;
            $task_id = $row2->task_id;
            $project_work_type_id = $row2->project_work_type_id;
            $description = $row2->description;
            $qnty = $row2->qty;
            $unit = $row2->unit;
            $unit_price = $row2->unit_price;
            $total_price = $row2->total_price;
            $data3['bt.boq_id']=$boq_id;
            $data3['bt.project_work_type_id']=$project_work_type_id;
            $data3['bti.boq_task_id']=$task_id;
            $data3['bti.delete_status']=0;
            $column = "bt.project_work_type_id,mu.unit_name,bt.task_id,bt.boq_id,bt.description,bt.project_work_type_id,bt.item_sl_no,bt.qty,bt.unit as psuedo_unit, bt.unit_price,bt.total_price,bt.created_date,bt.created_by,bt.updated_by,bt.updated_date,bti.*,m.material_id,m.material_name,m.unit as psuedo_unit2,b.*";
            $res3=$this->Boq->select_task_items($column,$data3);
            $task_item_count=$res3->num_rows();
            $boq_id = $row2->boq_id;
            $work_type_id = $row2->project_work_type_id;
            if($qnty!=0 && $total_price!=0){
              $task_unit_price = round($total_price/$qnty,$this->config->item('Currency_amount_decimals_2'));
            }else{
              $task_unit_price = 0;
            }

            $tasks_table_body.=
            '<tr class="div_work_type_'.$row->id.'" style="display:none">'.
            '<td style="padding: 5px !important;">'.
            '<div class="m-form__group form-group" style="margin-bottom: 2rem;margin-left: 1rem;"><div class="m-checkbox-list">
            <label class="m-checkbox m-checkbox--bold m-checkbox--state-brand"><input type="checkbox" data-child="checkbox_task_'.$task_id.'" data-id="'.$task_id.'" data-checkbox-type="task" class="task_check_box checkbox_display checkbox_work_type_'.$row->id.'"><span></span></label></div></div>'.
            '</td>'.
            '<td></td>'.
            '<td>'.$task_id.'</td>'.
            '<td><strong>'.$priority3.'</strong></td>'.
            '<td>'.$description.'</td>'.
            '<td>'.$qnty.'</td>'.
            '<td>'.$unit_name.'</td>'.
            '<td>'.$task_unit_price.'</td>'.
            '<td>'.$total_price.'</td>'.
            '<td style="min-width: 150px">
            <div class="form-group m-form__group input_task_'.$task_id.'" style="display:none;margin-bottom: 5px;margin-top: 5px;">
            <div class="input-group m-input-group m-input-group--pill  m-input-group--air">
            <input  style="display:none;" type="text" data-type="task" data-id="'.$task_id.'" name="task_qty_'.$task_id.'" id="task_qty_'.$task_id.'" class="numeric_fields input_fields input_task_'.$task_id.' form-control m-input m-input--air m-input--pill"   placeholder="Qty">
            <div class="input-group-append"><span class="input-group-text" id="basic-addon1">'.$unit_name.'</span></div>
            </div>
            </div>
            </td>'.
            '<td style="min-width: 150px">
            <div class="form-group m-form__group input_task_'.$task_id.'" style="display:none;margin-bottom: 5px;margin-top: 5px;">
            <div class="input-group m-input-group m-input-group--pill  m-input-group--air">
            <input  style="display:none;" value="'.$task_unit_price.'" type="text" name="task_rate_'.$task_id.'" id="task_rate_'.$task_id.'" class="numeric_fields input_task_'.$task_id.' form-control m-input m-input--air m-input--pill"   placeholder="Unit Rate">
            <div class="input-group-append"><span class="input-group-text" id="basic-addon1">/'.$unit_name.'</span></div>
            </div>
            </div>
            </td>'.
            '<td></td>'.
            '</tr>';
            $sub_total=$sub_total+$total_price;
            $priority2++;
            $tasks_table_body.= '<tr class="div_task_'.$task_id.'" style="display:none">'.
            '<td ></td>'.
            '<td ></td>'.
            '<td ></td>'.
            '<td ></td>'.
            '<td colspan="8" class="right" style=" font-weight: 500;font-style: italic;  ">Item Requirements </td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '</tr>';
            $priority4=1;
            foreach ($res3->result() as $row3):
              if(($row3->item_type)=="other" && $row3->item_name !='0') {
                $material_name = $row3->item_name;
              }
              else{
                $material_name = $row3->material_name;
              }
              $unit_name = $row3->unit_name;
              $tasks_table_body.=
              '<tr class="div_task_'.$task_id.'" style="display:none">'.
              '<td style="padding: 5px !important;">'.
              '<div class="m-form__group form-group" style="margin-bottom: 2rem;margin-left: 2rem;"><div class="m-checkbox-list">
              <label class="m-checkbox m-checkbox--bold m-checkbox--state-info"><input type="checkbox" data-child="" data-parent="'.$task_id.'" data-id="'.$row3->item_id.'" data-checkbox-type="item" class="checkbox_display checkbox_task_'.$task_id.'"><span></span></label></div></div>'.
              '</td>'.
              '<td></td>'.
              '<td>'.$task_id.'</td>'.
              '<td>'.$priority3.'.'.$priority4.'</td>'.
              '<td>'.$material_name.'</td>'.
              '<td>'.$row3->qnty.'</td>'.
              '<td>'.$unit_name.'</td>'.
              '<td>'.$row3->unit_rate.'</td>'.
              '<td>'.$row3->total_amount.'</td>'.
              '<td style="min-width: 150px;">
              <div class="form-group m-form__group input_item_'.$row3->item_id.'" style="display:none;margin-bottom: 5px;margin-top: 5px;">
              <div class="input-group m-input-group m-input-group--pill  m-input-group--air">
              <input  style="display:none;" data-type="item" data-parent="'.$task_id.'" data-id="'.$row3->item_id.'" name="item_qty_'.$row3->item_id.'" id="item_qty_'.$row3->item_id.'" type="text" class="numeric_fields input_fields input_item_'.$row3->item_id.' form-control m-input m-input--air m-input--pill"   placeholder="Qty">
              <div class="input-group-append"><span class="input-group-text" id="basic-addon1">'.$unit_name.'</span></div>
              </div>
              <span class="m-form__help"></span>
              </div>
              </td>'.
              '<td style="min-width: 150px;">
              <div class="form-group m-form__group input_item_'.$row3->item_id.'" style="display:none;margin-bottom: 5px;margin-top: 5px;">
              <div class="input-group m-input-group m-input-group--pill  m-input-group--air">
              <input  style="display:none;" data-type="item" data-parent="'.$task_id.'" data-id="'.$row3->item_id.'" value="'.$row3->unit_rate.'" name="item_rate_'.$row3->item_id.'" id="item_rate_'.$row3->item_id.'" type="text" class="numeric_fields input_fields input_item_'.$row3->item_id.' form-control m-input m-input--air m-input--pill"   placeholder="Qty">
              <div class="input-group-append"><span class="input-group-text" id="basic-addon1">'.$unit_name.'</span></div>
              </div>
              <span class="m-form__help"></span>
              </div>
              </td>'.
              '<td style="min-width: 150px;">
              <div class="form-group m-form__group input_item_'.$row3->item_id.'" style="display:none;margin-bottom: 5px;margin-top: 5px;">
              <div class="m-radio-list">
              <label class="m-radio m-radio--solid m-radio--success">
              <input style="display:none;" data-type="item" data-parent="'.$task_id.'" data-id="'.$row3->item_id.'" type="radio" class="input_fields input_item_'.$row3->item_id.'" name="consumption_type_'.$row3->item_id.'" value="purchased_material"> Purchased Material
              <span></span>
              </label>
              <label class="m-radio m-radio--solid m-radio--brand">
              <input style="display:none;" data-type="item" data-parent="'.$task_id.'" data-id="'.$row3->item_id.'" type="radio" class="input_fields input_item_'.$row3->item_id.'" name="consumption_type_'.$row3->item_id.'" value="provided_by_client"> Provided By Client
              <span></span>
              </label>
              <label class="m-radio m-radio--solid m-radio--focus">
              <input style="display:none;" data-type="item" data-parent="'.$task_id.'" data-id="'.$row3->item_id.'" type="radio" class="input_fields input_item_'.$row3->item_id.'" name="consumption_type_'.$row3->item_id.'" value="reusable_material"> Reusable Material
              <span></span>
              </label>
              </div>
              <span class="m-form__help"></span>
              </div>
              </div>
              </td>'.
              '</tr>';
              $priority4++;
            endforeach;
            $tasks_table_body.='<tr class="div_task_'.$task_id.'" style="display:none">'.
            '<td colspan="12"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '<td style="display:none"></td>'.
            '</tr>';
          endforeach;
        }

        $priority++;
      endforeach;

      $table_content=$tasks_table_body.$tasks_table_summary;
      echo json_encode(array("work_count"=>$works_count,"content"=>$table_content));
    }else{
      echo json_encode(array("work_count"=>$works_count));
    }
  }

  public function select_boq_daily_progress() {

    $data=array();
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && isset($_POST['end_date']) && $_POST['end_date']!=''){
      $start_date=date('Y-m-d', strtotime($_POST['start_date']));
      $end_date=date('Y-m-d', strtotime($_POST['end_date']));
      // of period 1 day
      $interval = new DateInterval('P1D');
      $realEnd = new DateTime($end_date);
      $realEnd->add($interval);
      $date_period = new DatePeriod(new DateTime($start_date), $interval, $realEnd);

      $project_id = $this->security->xss_clean($this->input->post('project_id'));
      $boq_id = $this->security->xss_clean($this->input->post('boq_id'));
      $project_data = $this->Work->select_work("*", array("work_id" =>$project_id))->row();
      $stock_materials = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$project_id),'sr.material_id')->result();


      $data['pwt.project_id'] = $project_id;
      $data['pwt.boq_id'] = $boq_id;
      //      Select Work Category
      $res=$this->Boq->select_project_work_type("",$data);
      $tasks_table_body='';
      $tasks_table_summary='';
      $priority=1;
      $grand_total_achieved_amount = $grand_total_expense_amount = $grand_total_profit = $grand_total_qty = 0;

      if($res->num_rows()>0){
        foreach ($date_period as $key11 => $value11) {
          $daily_total_achieved_amount = $daily_total_expense_amount = $daily_total_profit = 0;
          if($this->config->item('BOQ_dpr_template')==1){
            $tasks_table_body.='<tr>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td colspan="11" style="text-align: left"><strong>DATE: '.$value11->format('d-m-Y').'</strong></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none" class="delete_column"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '</tr>';
          }elseif($this->config->item('BOQ_dpr_template')==2){
            if($project_data->project_section=='Sign Boards'){
              $colspan3=10+sizeof($stock_materials);
              $colspan33=5;
            }elseif($project_data->project_section=='Road Marking'){
              $colspan3=10+1;
              $colspan33=6;
            }elseif($project_data->project_section=='Road Studs'){
              $colspan3=9+sizeof($stock_materials);
              $colspan33=5;
            }elseif($project_data->project_section=='Crash Barriers'){
              $colspan3=9+sizeof($stock_materials);
              $colspan33=9;
            }else{
              $colspan3=9;
              $colspan33=9;
            }
            $tasks_table_body.='<tr>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td colspan="'.$colspan3.'" style="text-align: left"><strong><a target="_blank" id="btn_print_dpr" href="javascript:;" data-boq-id="'.$boq_id.'" data-date="'.$value11->format('d-m-Y').'">DATE: '.$value11->format('d-m-Y').'</a></strong></td>';
            for($ii=0;$ii<$colspan3-1;$ii++) {
              $tasks_table_body.='<td style="display: none"></td>';
            }
            $tasks_table_body.='</tr>';
          }
          foreach($res->result() as $row):

            if($this->config->item('BOQ_dpr_template')==1){
              $work_type_id=$row->id;
              $type_id=$row->type_id;
              $type_name=$row->type_name;

              $data2['bt.project_work_type_id']=$work_type_id;
              $data2['bt.boq_id']=$boq_id;
              $res2=$this->Boq->select_task("COALESCE(SUM(bt.total_price),0) as total_amount",$data2);

              if($res2->num_rows()==1){
                $total_amt_sum=number_format((float)$res2->row()->total_amount, 3, '.', '');
              }else{
                $total_amt_sum=0;
              }

              //              Select Tasks

              $res2=$this->Boq->select_task("",$data2);
              $task_count=$res2->num_rows();

              $sub_total=$task_daily_progress_count = 0;
              $task_daily_progress = '';
              if($task_count>0) {
                $priority2 = 0;
                $j=1;
                foreach ($res2->result() as $row2):
                  $priority2++;
                  $unit_name = $row2->unit_name;
                  $priority3 = $priority.'.'.$priority2;
                  $task_id = $row2->task_id;
                  $project_work_type_id = $row2->project_work_type_id;
                  $description = $row2->description;
                  $qnty = $row2->qty;
                  $unit = $row2->unit;
                  $unit_price = $row2->unit_price;
                  $total_price = $row2->total_price;
                  $data3['bt.boq_id']=$boq_id;
                  $data3['bt.project_work_type_id']=$project_work_type_id;
                  $data3['bti.boq_task_id']=$task_id;
                  $data3['bti.delete_status']=0;
                  $column = "bt.project_work_type_id,mu.unit_name,bt.task_id,bt.boq_id,bt.description,bt.project_work_type_id,bt.item_sl_no,bt.qty,bt.unit as psuedo_unit, bt.unit_price,bt.total_price,bt.created_date,bt.created_by,bt.updated_by,bt.updated_date,bti.*,m.material_id,m.material_name,m.unit as psuedo_unit2,b.*";
                  $res3=$this->Boq->select_task_items($column,$data3);
                  $task_item_count=$res3->num_rows();
                  $boq_id = $row2->boq_id;
                  $work_type_id = $row2->project_work_type_id;
                  if($qnty!=0 && $total_price!=0){
                    $task_unit_price = round($total_price/$qnty,$this->config->item('Currency_amount_decimals_2'));
                  }else{
                    $task_unit_price = 0;
                  }

                  $daily_progress_data_where['type'] = 'boq_task';
                  $daily_progress_data_where['reference_id'] = $task_id;
                  $daily_progress_data_where['bdp.boq_id'] = $boq_id;
                  $daily_progress_data_where['bdp.date'] = $value11->format('Y-m-d');
                  $total_task_acheived = $this->Boq->select_boq_daily_progress('',$daily_progress_data_where);
                  if($total_task_acheived->num_rows()==1){
                    $task_daily_progress_count++;
                    $unit_rate =  $total_task_acheived->row()->unit_rate;
                    $unit_rate_client = $row2->client_unit_price;
                    $total_task_acheived_qty = $total_task_acheived->row()->quantity;
                    $total_acheived_amount = $total_task_acheived_qty*$unit_rate_client;
                    $total_expense_amount = $total_task_acheived_qty*$unit_rate;
                    $task_daily_progress.=
                    '<tr>'.
                    '<td style="display: none">'.$task_id.'</td>'.
                    '<td style="display: none"></td>'.
                    '<td><strong>'.$priority3.'</strong></td>'.
                    '<td >'.$description.'</td>'.
                    '<td style="display: none">'.$qnty.'</td>'.
                    '<td>'.$unit_name.'</td>'.
                    '<td>'.$unit_rate.'</td>'.
                    '<td style="display: none">'.$total_price.'</td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td>'.$total_task_acheived_qty.'</td>'.
                    '<td>'.round($total_acheived_amount,$this->config->item('Currency_amount_decimals_2')).'</td>'.
                    '<td>'.$total_task_acheived_qty.'</td>'.
                    '<td>'.round($total_expense_amount,$this->config->item('Currency_amount_decimals_2')).'</td>'.
                    '<td></td>'.
                    '<td>'.round($total_acheived_amount-$total_expense_amount,$this->config->item('Currency_amount_decimals_2')).'</td>';
                    if($row->created_by == $this->session->userdata('user_id')  || $this->session->userdata('user_role')=='admin'){
                      // $task_daily_progress.='<td class="edit_column">
                      // <a style="margin-left: 5px;margin-right: 5px" id="btn_boq_daily_progress_edit" data-boq-id="'.$boq_id.'" data-type="boq_task" data-reference-id="'.$task_id.'" class="btn btn-success m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_daily_progress_edit_modal" data-toggle="modal"><i class="la la-edit"></i></a>
                      // <a style="margin-left: 5px;margin-right: 5px" id="btn_boq_daily_progress_delete" data-boq-id="'.$boq_id.'" data-type="boq_task" data-reference-id="'.$task_id.'" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_daily_progress_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a>
                      // </td>';
                      $task_daily_progress.='<td class="edit_column">
                      <a style="margin-left: 5px;margin-right: 5px" id="btn_boq_daily_progress_delete" data-date="'.$value11->format('Y-m-d').'" data-boq-id="'.$boq_id.'" data-type="boq_task" data-reference-id="'.$task_id.'" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_daily_progress_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a>
                      </td>';
                    }else{
                      $task_daily_progress.='<td class="edit_column"></td>';
                    }
                    $task_daily_progress.='<td style="display: none">'.$row2->unit.'</td>'.
                    '<td style="display: none">'.$row2->project_work_type_id.'</td>'.
                    '</tr>';
                    $daily_total_achieved_amount += $total_acheived_amount;
                    $grand_total_achieved_amount += $total_acheived_amount;
                    $daily_total_expense_amount += $total_expense_amount;
                    $grand_total_expense_amount += $total_expense_amount;
                    $daily_total_profit += $total_acheived_amount-$total_expense_amount;
                    $grand_total_profit += $total_acheived_amount-$total_expense_amount;

                    $task_daily_progress.= '<tr>'.
                    '<td ></td>'.
                    '<td colspan="11" class="right" style=" font-weight: 500;font-style: italic;  ">Items </td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '<td style="display:none"></td>'.
                    '</tr>';
                    $priority4=1;
                    foreach ($res3->result() as $row3):
                      if(($row3->item_type)=="other" && $row3->item_name !='0') {
                        $material_name = $row3->item_name;
                      }
                      else{
                        $material_name = $row3->material_name;
                      }
                      $unit_name = $row3->unit_name;

                      $daily_progress_data_where['type'] = 'boq_task_item';
                      $daily_progress_data_where['reference_id'] = $row3->item_id;
                      $daily_progress_data_where['bdp.boq_id'] = $boq_id;
                      $daily_progress_data_where['bdp.date'] = $value11->format('Y-m-d');
                      $total_item_acheived = $this->Boq->select_boq_daily_progress('',$daily_progress_data_where);
                      if($total_item_acheived->num_rows()==1){
                        $total_item_acheived_qty = $total_item_acheived->row()->quantity;
                        $unit_rate = $total_item_acheived->row()->unit_rate;
                        $task_daily_progress.=
                        '<tr>'.
                        '<td style="display: none">'.$task_id.'</td>'.
                        '<td style="display: none"></td>'.
                        '<td>'.$priority3.'.'.$priority4.'</td>'.
                        '<td>'.$material_name.'</td>'.
                        '<td style="display: none">'.$row3->qnty.'</td>'.
                        '<td>'.$unit_name.'</td>'.
                        '<td>'.$unit_rate.'</td>'.
                        '<td style="display: none">'.$row3->total_amount.'</td>'.
                        '<td style="display: none"></td>'.
                        '<td style="display: none"></td>'.
                        '<td >'.$total_item_acheived_qty.'</td>'.
                        '<td ></td>'.
                        '<td>'.$total_item_acheived_qty.'</td>'.
                        '<td>'.round($total_item_acheived_qty*$unit_rate,$this->config->item('Currency_amount_decimals_2')).'</td>'.
                        '<td>'.ucwords(str_replace('_',' ',$total_item_acheived->row()->consumption_type)).'</td>'.
                        '<td></td>';
                        if($row->created_by == $this->session->userdata('user_id')){
                          // $task_daily_progress.='<td class="edit_column">
                          // <a style="margin-left: 5px;margin-right: 5px" id="btn_boq_daily_progress_edit" data-boq-id="'.$boq_id.'" data-type="boq_task_item" data-reference-id="'.$row3->item_id.'" class="btn btn-success m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_daily_progress_edit_modal" data-toggle="modal"><i class="la la-edit"></i></a>
                          // <a style="margin-left: 5px;margin-right: 5px" id="btn_boq_daily_progress_delete" data-boq-id="'.$boq_id.'" data-type="boq_task_item" data-reference-id="'.$row3->item_id.'" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#boq_daily_progress_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a>
                          // </td>';
                          $task_daily_progress.='<td class="edit_column"></td>';
                        }else{
                          $task_daily_progress.='<td class="edit_column"></td>';
                        }
                        $task_daily_progress.='<td style="display: none"></td>'.
                        '<td style="display: none"></td>'.
                        '<td style="display: none"></td>'.
                        '</tr>';
                      }
                      $priority4++;
                    endforeach;


                    $task_daily_progress.='<tr>'.
                    '<td colspan="5" style=" font-weight: 500;font-style: italic;text-align: center;">Day Total : </td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td><strong>'.round($daily_total_achieved_amount,$this->config->item('Currency_amount_decimals_2')).'</strong></td>'.
                    '<td></td>'.
                    '<td><strong>'.round($daily_total_expense_amount,$this->config->item('Currency_amount_decimals_2')).'</strong></td>'.
                    '<td></td>'.
                    '<td><strong>'.round($daily_total_profit,$this->config->item('Currency_amount_decimals_2')).'</strong></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '</tr>';

                    $task_daily_progress.='<tr>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td colspan="9" class="right"></td>'.
                    '<td></td>'.
                    '<td></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none" class="delete_column"></td>'.
                    '<td style="display: none"></td>'.
                    '<td style="display: none"></td>'.
                    '</tr>';
                  }
                endforeach;
              }
              if($task_daily_progress_count>0){
                $tasks_table_body.='<tr>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td><strong>'.$priority.'</strong></td>'.
                '<td colspan="9"><strong>'.$type_name.'</strong></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td class="delete_column"></td>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '</tr>';
                $tasks_table_body.=$task_daily_progress;
              }

              $priority++;
            }elseif($this->config->item('BOQ_dpr_template')==2){
              foreach ($stock_materials as $key88 => $value88) {
                ${'material_total_qty_'.$value88->material_id}=0;
              }
              $task_daily_progress = '';
              $dpr_where['bd.project_id'] = $project_id;
              $dpr_where['bd.boq_id'] = $boq_id;
              $dpr_where['bd.work_date'] = $value11->format('Y-m-d');
              $dpr_items = $this->Boq->select_boq_dpr_items('bdi.*,bd.*,m.material_name,bdi.remarks as item_remarks',$dpr_where)->result();
              if(sizeof($dpr_items)>0){
                $task_daily_progress.=
                '<tr>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td></td>'.
                '<td colspan="'.($colspan3-4).'"><a target="_blank" id="btn_print_dpr" href="javascript:;" data-boq-id="'.$boq_id.'" data-date="'.$value11->format('d-m-Y').'">DPR #'.$dpr_items[0]->dpr_id.'</a></td>';
                for($ii=0;$ii<$colspan3-5;$ii++) {
                  $task_daily_progress.='<td style="display: none"></td>';
                }
                $task_daily_progress.='<td><a href="'.base_url().'boq/dpr_edit/'.$boq_id.'/'.$dpr_items[0]->dpr_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></td>'.
                '<td></td>'.
                '<td></td>'.
                '</tr>';
              }
              foreach ($dpr_items as $key55 => $value55) {
                $task_daily_progress.=
                '<tr>'.
                '<td style="display: none"></td>'.
                '<td style="display: none"></td>'.
                '<td></td>'.
                '<td>'.$value55->chainage_from.'</td>';
                if($project_data->project_section!='Road Marking' && $project_data->project_section!='Sign Boards'){
                  $task_daily_progress.='<td>'.$value55->chainage_to.'</td>';
                }
                if($project_data->project_section=='Sign Boards'){
                  $task_daily_progress.='<td>'.$value55->material_name.'</td>';
                }
                $task_daily_progress.='<td>'.$value55->side.'</td>';
                if($project_data->project_section=='Road Marking' || $project_data->project_section=='Sign Boards'){
                  $task_daily_progress.='<td>'.number_format($value55->quantity,$this->config->item('Currency_amount_decimals_2'), '.', '').'</td>';
                }
                if($project_data->project_section=='Road Studs'){
                  $task_daily_progress.='<td>'.$value55->spacing.'</td>';
                }
                if($project_data->project_section=='Crash Barriers' || $project_data->project_section=='Road Marking'){
                  $task_daily_progress.='<td>'.number_format($value55->chainage_length,$this->config->item('Currency_amount_decimals_2'), '.', '').'</td>';
                }
                if($project_data->project_section=='Road Marking'){
                  $task_daily_progress.='<td>'.number_format($value55->chainage_width,$this->config->item('Currency_amount_decimals_2'), '.', '').'</td>';
                }
                if($project_data->project_section=='Road Marking'){
                  $task_daily_progress.='<td>'.number_format($value55->chainage_total,$this->config->item('Currency_amount_decimals_2'), '.', '').'</td>';
                }
                if($project_data->project_section!='Road Marking'){
                  foreach ($stock_materials as $key88 => $value88) {
                    $item_materials = $this->Boq->select_boq_dpr_item_materials('bdim.quantity',array("bdim.item_id"=>$value55->item_id,"bdim.material_id"=>$value88->material_id));
                    if($item_materials->num_rows()==1){
                      $task_daily_progress.='<td>'.$item_materials->row()->quantity.'</td>';
                      ${'material_total_qty_'.$value88->material_id}+=$item_materials->row()->quantity;
                    }else{
                      $task_daily_progress.='<td></td>';
                    }
                  }
                }
                if($project_data->project_section=='Sign Boards'){
                  $task_daily_progress.='<td>'.$value55->reference_no.'</td>';
                }
                $task_daily_progress.='<td>'.$value55->item_remarks.'</td>'.
                '<td></td>'.
                '<td></td>'.
                '<td></td>'.
                '</tr>';
                $grand_total_qty+=$value55->chainage_total;
              }
              $tasks_table_body.=$task_daily_progress;
            }
          endforeach;
          if($this->config->item('BOQ_dpr_template')==1){
            $tasks_table_body.='<tr>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>';
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td colspan="9" class="right"></td>'.
            '<td></td>'.
            '<td></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none" class="delete_column"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>'.
            '</tr>';
          }elseif($this->config->item('BOQ_dpr_template')==2){
            $tasks_table_body.='<tr>'.
            '<td colspan="'.($colspan3+2).'" class="right"></td>'.
            '<td style="display: none"></td>'.
            '<td style="display: none"></td>';
            for($ii=0;$ii<$colspan3-1;$ii++) {
              $tasks_table_body.='<td style="display: none"></td>';
            }
            $tasks_table_body.='</tr>';
          }
        }
        if($this->config->item('BOQ_dpr_template')==1){
          $tasks_table_body.='<tr>'.
          '<td colspan="5" style=" font-weight: 500;font-style: italic;text-align: center;">Grand Total : </td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td><strong>'.round($grand_total_achieved_amount,$this->config->item('Currency_amount_decimals_2')).'</strong></td>'.
          '<td></td>'.
          '<td><strong>'.round($grand_total_expense_amount,$this->config->item('Currency_amount_decimals_2')).'</strong></td>'.
          '<td></td>'.
          '<td><strong>'.round($grand_total_profit,$this->config->item('Currency_amount_decimals_2')).'</strong></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '</tr>';
        }elseif($this->config->item('BOQ_dpr_template')==2){
          $tasks_table_body.='<tr>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td colspan="'.($colspan33).'" style=" font-weight: 500;font-style: italic;text-align: center;">Grand Total : </td>';
          for($ii=0;$ii<$colspan33-1;$ii++) {
            $tasks_table_body.='<td style="display: none"></td>';
          }
          if($project_data->project_section!='Road Marking'){
            foreach ($stock_materials as $key88 => $value88) {
              $tasks_table_body.='<td><strong>'.${'material_total_qty_'.$value88->material_id}.'</strong></td>';
            }
          }else{
            $tasks_table_body.='<td></td>';
          }
          $tasks_table_body.='<td></td>'.
          '<td></td>'.
          '<td></td>'.
          '<td></td>';
          if($project_data->project_section=='Sign Boards'){
            $tasks_table_body.='<td></td>';
          }
          $tasks_table_body.='<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '</tr>';
        }

        $table_content=$tasks_table_body.$tasks_table_summary;
        echo json_encode(array("count"=>$res->num_rows(),"content"=>$table_content));
      }else{
        echo json_encode(array("count"=>$res->num_rows()));
      }
    }else{
      echo json_encode(array("count"=>$res->num_rows()));
    }
  }

  public function select_task_items()
  {
    $data3['bt.boq_id']=$this->security->xss_clean($this->input->post('boq_id'));
    $data3['bt.project_work_type_id']=$this->security->xss_clean($this->input->post('work_type_id'));
    $counter = $this->security->xss_clean($this->input->post('counter'));
    $data3['bti.boq_task_id'] = $this->security->xss_clean($this->input->post('task_id'));
    $data3['bti.delete_status']=0;

    $column = "bt.task_id,bt.boq_id,bt.description,bt.project_work_type_id,bt.item_sl_no,bt.qty,bt.unit as psuedo_unit, bt.unit_price,bt.total_price,bt.created_date,bt.created_by,bt.updated_by,bt.updated_date,bti.*,m.material_id,m.material_name,m.unit as psuedo_unit2,b.*";
    $res3=$this->Boq->select_task_items($column,$data3);
    $result = $res3->result();
    $array=array();
    $json_data='';
    $j=0;
    $materials = $this->Material->select_material()->result();
    $meausre_units = $this->Material->select_unit()->result();
    $current_mat = $current_unit =array();

    if($counter>0){
      foreach($result as $row):
        if($row->item_type=='material')
        {
          $checked_material = 'checked';
          $checked_other = $other_name = $dis_select =  $text_required = '';
          $dis_text = 'display: none;';
          $select_required = 'required';
        }
        else{
          $checked_other = 'checked';
          $checked_material =  $dis_text = $select_required = '';
          $dis_select = 'display: none;';
          $other_name = $row->item_name;
          $text_required = 'required';
        }
        if($row->consumable_type=='item_wise')
        {
          $checked_item_wise='checked';
          $checked_common='';
        }else{
          $checked_item_wise='';
          $checked_common='checked';
        }

        $json_data .= '<tr>';
        $json_data .= '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input style="padding: 10px; text-align:center;" readonly type="text" class="form-control m-input" name="labour[sl_no]'.'["'.$j.'"]_edit'.' value='.'"'.($j+1).'"/></div></div><input type="hidden" name="item[item_id]'.'['.$j.']_edit'.'" value="'.$row->item_id.'"></td>';
        $json_data .= '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class=""><label class="m-radio m-radio--solid m-radio--state-brand"><input data-sl-no='.'"'.($j+1).'" required type="radio" name="item[type_edit]'.'['.$j.']" id="item_type_'.($j+1).'_edit" class="form_labour_add_fields item_type_edit material_radio_'.($j+1).'" '.$checked_material.' value="material">Material<span></span></label><label class="m-radio m-radio--solid m-radio--state-success"><input type="radio" name="item[type_edit]'.'['.$j.']" id="item_type_'.($j+1).'_edit" '.$checked_other.' data-sl-no='.'"'.($j+1).'" class="form_labour_add_fields item_type_edit other_radio_'.($j+1).'" value="other">Other<span></span></label></div></div>';
        $json_data .='<div class="form-group m-form__group text_field_'.($j+1).'_edit" style="padding: 0px;margin: 0px;'.$dis_text.'" ><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input '.$text_required.' placeholder="Specify" value="'.$other_name.'" type="text"  class="form-control m-input" name="item[name]['.($j).']" id="item_name_spec_'.($j+1).'_edit"/></div></div><div class="form-group m-form__group select_field_'.($j+1).'_edit" style="padding: 0px;margin: 0px;'.$dis_select.'"><div class="m-select2 m-select2--air m-select2--pill"><select style="width: 100%" '.$select_required.' class="form-control material_edit_select" name="item[material]['.($j).']" id="item_material_'.($j+1).'_edit" aria-required="true" tabindex="-1"   aria-describedby=""><option selected disabled>Select Material</option>';
        foreach($materials as $r) {
          $json_data .= '<option value="'.$r->material_id.'">'.$r->material_name.'</option>';
        }
        $json_data .= '</select></div></div></td>';
        $json_data .= '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="m-select2 m-select2--air m-select2--pill"><select style="width: 100%" required="" class="form-control measure_unit_edit_select" name="item[unit]['.($j).']" id="material_unit_'.($j+1).'_edit" aria-required="true" tabindex="-1"   aria-describedby=""><option selected disabled>Select Unit</option>';
        foreach($meausre_units as $r) {
          $json_data .= '<option value="'.$r->unit_id.'">'.$r->unit_name .'</option>';
        }
        $json_data .= '</select></div></div></td>';
        $json_data .=  '<td><div class="form-group m-form__group " style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input   " value="'.$row->grade.'" data-sl-no="'.($j+1).'_edit" name="item[grade]['.($j).']" id="material_grade_'.($j+1).'_edit"/></div></div></td>';
        $json_data .= '<td><div class="form-group m-form__group " style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input   " value="'.$row->spec.'" data-sl-no="'.($j+1).'_edit" name="item[spec]['.($j).']" id="material_spec_'.($j+1).'_edit"/></div></div></td>';
        $json_data .= '<td><div class="form-group m-form__group " style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input   unit_quantity_edit" value="'.$row->qnty.'" data-sl-no="'.($j+1).'" name="item[quantity]['.($j).']" id="material_quantity_'.($j+1).'_edit"/></div></div></td>';
        $json_data .= '<td><div class="form-group m-form__group " style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input  unit_quantity_edit" value="'.$row->unit_rate.'" data-sl-no="'.($j+1).'" name="item[unit_price]['.($j).']" id="material_unit_price_'.($j+1).'_edit"/></div></div></td>';
        $json_data .= '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly  class="form-control m-input total_item_amount_edit" value="'.$row->total_amount.'" name="item[total_price]['.($j).']" id="material_total_price_'.($j+1).'_edit"/></div></div></td>';
        if($this->config->item('BOQ_dpr_template')==2){
          $json_data .= '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class=""> <label class="m-radio m-radio--solid m-radio--state-focus"><input data-sl-no="'.($j+1).'" required type="radio" name="item[consumable_type]['.($j).']" id="item_consumable_type_'.($j+1).'" class=" consumable_type" '.$checked_item_wise.' value="item_wise">Item Wise<span></span></label><label class="m-radio m-radio--solid m-radio--state-warning"><input type="radio" name="item[consumable_type]['.($j).']" id="item_consumable_type_'.($j+1).'" '.$checked_common.' data-sl-no="'.($j+1).'" class=" consumable_type" value="common">Common<span></span></label></div></div></td>';
        }
        $json_data .= '<td><a href="javascript:" data-item-id="'.$row->item_id.'" data-sl-no="'.($j+1).'" class="ibtnDel btn btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td>';
        $json_data .= '</tr>';
        $j++;
        $current_mat[] +=  $row->material_id;
        $current_unit[] +=  $row->unit;
      endforeach;
    }
    // $json_data['data']=$json_data;

    echo json_encode(array('data'=>$json_data,"count"=>$j,"current_mat"=>$current_mat, "current_unit"=>$current_unit));  // send data as json format
  }

  public function create_daily_progress($id='')
  {
    $boq_id = $this->input->post('boq_id');
    $daily_progress_data['boq_id'] = $daily_progress_data_where['bdp.boq_id'] = $boq_id;
    $daily_progress_data['date'] = $daily_progress_data_where['bdp.date'] = date('Y-m-d',strtotime($this->input->post('work_date')));
    $daily_progress_data['remarks'] = $this->input->post('remarks');
    $daily_progress_data['created_by'] = $daily_progress_data['updated_by'] = $this->session->userdata('user_id');
    $daily_progress_data['created_date'] = $daily_progress_data['updated_date'] = date('Y-m-d H:i:s');

    $task_where['bt.boq_id'] = $boq_id;
    $tasks = $this->Boq->select_task("",$task_where)->result();
    $success = $error = 0;
    foreach ($tasks as $row){
      // Check Input Comes
      $daily_progress_data['project_work_type_id'] = $row->project_work_type_id;
      if($this->input->post('task_qty_'.$row->task_id) && $this->input->post('task_qty_'.$row->task_id)!=''){
        $daily_progress_data['type'] = $daily_progress_data_where['type'] = 'boq_task';
        $daily_progress_data['reference_id'] = $daily_progress_data_where['reference_id'] = $row->task_id;
        $daily_progress_data['quantity'] = $this->input->post('task_qty_'.$row->task_id);
        $daily_progress_data['unit_rate'] = $this->input->post('task_rate_'.$row->task_id);
        $daily_progress_count = $this->Boq->select_boq_daily_progress('bdp.id',$daily_progress_data_where);
        if($daily_progress_count->num_rows()==0){
          unset($daily_progress_data['updated_by']);
          unset($daily_progress_data['updated_date']);
          $daily_progress_data['created_by'] = $this->session->userdata('user_id');
          $daily_progress_data['created_date'] = date('Y-m-d H:i:s');
          $result = $this->Boq->insert_boq_daily_progress($daily_progress_data);
          if($result['status']==1){
            $success++;
          }else{
            $error++;
          }
        }else{
          unset($daily_progress_data['created_by']);
          unset($daily_progress_data['created_date']);
          $daily_progress_data['updated_by'] = $this->session->userdata('user_id');
          $daily_progress_data['updated_date'] = date('Y-m-d H:i:s');
          $update_where['id'] = $daily_progress_count->row()->id;
          $result = $this->Boq->update_boq_daily_progress($update_where,$daily_progress_data);
          if($result==1){
            $success++;
          }else{
            $error++;
          }
        }

      }

      $item_where['boq_task_id'] = $row->task_id;
      $task_items=$this->Boq->select_task_items('bti.*',$item_where)->result();
      foreach ($task_items as $row2){
        // Check Input Comes
        if($this->input->post('item_qty_'.$row2->item_id) && $this->input->post('item_qty_'.$row2->item_id)!=''){
          $daily_progress_data['type'] = $daily_progress_data_where['type'] = 'boq_task_item';
          $daily_progress_data['reference_id'] = $daily_progress_data_where['reference_id'] = $row2->item_id;
          $daily_progress_data['quantity'] = $this->input->post('item_qty_'.$row2->item_id);
          $daily_progress_data['unit_rate'] = $this->input->post('item_rate_'.$row2->item_id);
          $daily_progress_data['consumption_type'] = $this->input->post('consumption_type_'.$row2->item_id);
          $daily_progress_count = $this->Boq->select_boq_daily_progress('bdp.id',$daily_progress_data_where);
          if($daily_progress_count->num_rows()==0){
            unset($daily_progress_data['updated_by']);
            unset($daily_progress_data['updated_date']);
            $daily_progress_data['created_by'] = $this->session->userdata('user_id');
            $daily_progress_data['created_date'] = date('Y-m-d H:i:s');
            $result = $this->Boq->insert_boq_daily_progress($daily_progress_data);
            if($result['status']==1){
              $success++;
            }else{
              $error++;
            }
          }else{
            unset($daily_progress_data['created_by']);
            unset($daily_progress_data['created_date']);
            $daily_progress_data['updated_by'] = $this->session->userdata('user_id');
            $daily_progress_data['updated_date'] = date('Y-m-d H:i:s');
            $update_where['id'] = $daily_progress_count->row()->id;
            $result = $this->Boq->update_boq_daily_progress($update_where,$daily_progress_data);
            if($result==1){
              $success++;
            }else{
              $error++;
            }
          }
        }
      }
    }
    if($success>0){
      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = 'BOQ Daily Progress Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }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);
  }
  public function delete_daily_progress()
  {
    $daily_progress_where_data['boq_id'] = $this->input->post('boq_id');
    $daily_progress_where_data['type'] = $this->input->post('type');
    $daily_progress_where_data['date'] = $this->input->post('date');
    $daily_progress_where_data['reference_id'] = $this->input->post('id');
    if($daily_progress_where_data['type']=='boq_task'){
      // Select Boq Task Items
      $task_items = $this->Boq->select_task_items('bti.*',array("bti.boq_task_id"=>$daily_progress_where_data['reference_id']))->result();
      foreach ($task_items as $key => $value) {
        $daily_progress_where_data_2['boq_id'] = $this->input->post('boq_id');
        $daily_progress_where_data_2['type'] = 'boq_task_item';
        $daily_progress_where_data_2['reference_id'] = $value->item_id;
        $daily_progress_where_data_2['date'] = $this->input->post('date');
        $daily_progress_data_2['delete_status'] = 1;
        $result2 = $this->Boq->update_boq_daily_progress($daily_progress_data_2,$daily_progress_where_data_2);
      }
      $daily_progress_data['delete_status'] = 1;
      $result = $this->Boq->update_boq_daily_progress($daily_progress_data,$daily_progress_where_data);
      if($result==1){
        $flash_data['status'] = 1;
        $flash_data['flashdata_msg'] = 'BOQ Daily Progress Deleted Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }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 !!';
      }
    }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);
  }

  public function create_dpr(){

    $dpr_data['boq_id'] = $dpr_where['bdp.boq_id'] = $this->input->post('boq_id');
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $dpr_data['boq_id']))->row();
    $dpr_data['project_id'] = $dpr_where['bdp.project_id'] = $this->input->post('project_id');
    $dpr_data['work_date'] = $dpr_where['bdp.work_date'] = date('Y-m-d',strtotime($this->input->post('work_date')));
    $dpr_data['vehicle_no'] = $this->input->post('vehicle_no');
    $dpr_data['applicator_name'] = $this->input->post('applicator_team_name');
    if($this->input->post('subcontract')){
      $dpr_data['subcontract_id'] = $this->input->post('subcontract');
    }
    $dpr_data['supervisor_id'] = $this->input->post('supervisor');
    $dpr_data['no_of_labours'] = $this->input->post('no_of_labours');
    if($this->input->post('start_time')!=''){
      $dpr_data['start_time'] = date('H:i:s',strtotime($this->input->post('start_time')));
    }
    if($this->input->post('end_time')!=''){
      $dpr_data['end_time'] = date('H:i:s',strtotime($this->input->post('end_time')));
    }
    $dpr_data['created_by'] = $this->session->userdata('user_id');
    $dpr_data['created_date'] = date('Y-m-d H:i:s');

    $dpr_count = $this->Boq->select_boq_dpr('bdp.dpr_id',$dpr_where);
    if($dpr_count->num_rows()==0){
      $result = $this->Boq->insert_boq_dpr($dpr_data);
      if($result['status']==1){
        //DPR measurements Items
        $measurements_array=$newArraymeasurements=array();
        if($this->input->post('measurements')){
          $measurements_array = $this->input->post('measurements');
        }
        $measurements_array_length = sizeof($measurements_array);
        foreach (array_keys($measurements_array) as $fieldKey) {
          foreach ($measurements_array[$fieldKey] as $key=>$value) {
            $newArraymeasurements[$key][$fieldKey] = $value;
          }
        }

        $i = 0;
        $item_data['dpr_id'] = $material_consumption['dpr_id'] = $result['insert_id'];
        foreach ($newArraymeasurements as $row) {
          $item_data['chainage_from'] = $row['chainage_from'];
          if(isset($row['chainage_to'])){
            $item_data['chainage_to'] = $row['chainage_to'];
          }
          if(isset($row['item'])){
            $item_data['item_material_id'] = $row['item'];
          }
          $item_data['side'] = $row['side'];
          if(isset($row['spacing'])){
            $item_data['spacing'] = $row['spacing'];
          }
          if(isset($row['qty_no'])){
            $item_data['quantity'] = $row['qty_no'];
          }
          if(isset($row['length'])){
            $item_data['chainage_length'] = $row['length'];
          }
          if(isset($row['width'])){
            $item_data['chainage_width'] = $row['width'];
          }
          if(isset($row['total_qty'])){
            $item_data['chainage_total'] = $row['total_qty'];
          }
          if(isset($row['ref_no'])){
            $item_data['reference_no'] = $row['ref_no'];
          }
          $item_data['remarks'] = $row['remarks'];
          $item_result = $this->Boq->insert_boq_dpr_items($item_data);
          if($item_result['status']==1){
            if(isset($row['material_qty'])){
              $material_qty = $row['material_qty'];
              foreach ($material_qty as $key => $value) {
                $material_data['item_id'] = $item_result['insert_id'];
                $material_data['material_id'] = $key;
                $material_data['quantity'] = $value;
                $material_result = $this->Boq->insert_boq_dpr_item_materials($material_data);
              }
            }
          }
        }

        // Material Consumption
        if($this->input->post('materials')){
          $materials_array=$newArraymaterials=array();
          $materials_array = $this->input->post('materials');
          $materials_array_length = sizeof($materials_array);
          foreach (array_keys($materials_array) as $fieldKey) {
            foreach ($materials_array[$fieldKey] as $key=>$value) {
              $newArraymaterials[$key][$fieldKey] = $value;
            }
          }
          $stock_materials = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$boq_data->project_id),'sr.material_id')->result();
          foreach ($stock_materials as $key => $value) {
            if(isset($newArraymaterials[$value->material_id])){
              $material_consumption['material_id'] = $value->material_id;
              $material_consumption['opening_stock'] = $newArraymaterials[$value->material_id]['opening_qty'];
              $material_consumption['received_qty'] = $newArraymaterials[$value->material_id]['received_qty'];
              $material_consumption['consumed_qty'] = $newArraymaterials[$value->material_id]['consumed_qty'];
              $material_consumption['balance_qty'] = $newArraymaterials[$value->material_id]['balance_qty'];
              $material_consumption['remarks'] = $newArraymaterials[$value->material_id]['remarks'];
              $material_consumption['created_by'] = $this->session->userdata('user_id');
              $material_consumption['created_date'] = date('Y-m-d H:i:s');
              $material_consumption_result = $this->Boq->insert_boq_dpr_material_consumption($material_consumption);
              if($material_consumption_result['status']==1 && $material_consumption['consumed_qty']>0){
                // Insert to Stock Consumption
                $stock_conusmption_data['work_id'] = $boq_data->project_id;
                $stock_conusmption_data['consumption_date'] = $dpr_data['work_date'];
                $stock_cons_data = $this->Stock->select_stock_consumption("MAX(cons_group_id) as last_group_id");
                if ($stock_cons_data->num_rows() == 1) {
                  $stock_conusmption_data['cons_group_id'] = ($stock_cons_data->row()->last_group_id) + 1;
                } else {
                  $stock_conusmption_data['cons_group_id'] = 1;
                }
                $stock_conusmption_data['project_stage_id'] = $this->projects_management->get_project_stage_id($boq_data->project_id);
                $stock_conusmption_data['created_date'] = date('Y-m-d H:i:s');
                $stock_conusmption_data['created_by'] = $this->session->userdata('user_id');
                $stock_conusmption_data['remarks'] = $material_consumption['remarks'];
                $stock_conusmption_data['dpr_cons_id'] = $material_consumption['dpr_id'];
                $remaining_qty = $material_consumption['consumed_qty'];
                $stock_register_where['sl.work_id'] = $boq_data->project_id;
                $stock_register_where['sr.material_id'] = $value->material_id;
                $stock_register_where['sr.total_balance_qty >'] = 0;
                $stock_register = $this->Stock->select_stock_register("stock_id,total_balance_qty", $stock_register_where)->result();
                foreach ($stock_register as $key22 => $value22) {
                  if ($remaining_qty > 0) {
                    $available_stock_item_qty = $value22->total_balance_qty;
                    if ($remaining_qty > $available_stock_item_qty) {
                      $stock_conusmption_data['consumption_qty']  = $available_stock_item_qty;
                    } else {
                      $stock_conusmption_data['consumption_qty']  = $remaining_qty;
                    }
                    $remaining_qty = $remaining_qty - $stock_conusmption_data['consumption_qty'];
                    $stock_conusmption_data['stock_id'] = $value22->stock_id;
                    // Update Stock Consumption
                    $stock_conusmption_result = $this->Stock->insert_stock_consumption($stock_conusmption_data);
                    //  Update Stock Register
                    $stock_conusmption_result2 = $this->stock_management->calculate_stock_balance($stock_conusmption_data['stock_id']);
                  }
                }
              }
            }
          }
        }


        $flash_data['status'] = 1;
        $flash_data['flashdata_msg'] = 'BOQ DPR Saved Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }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 !!';
      }
    }else{
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. DPR of Selected Date & Project is already Submitted!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Already Submitted !!';
    }
    echo json_encode($flash_data);
  }
  public function update_dpr(){

    $boq_where['boq_id'] = $this->input->post('boq_id');
    $boq_data = $this->Boq->select_boq("*,b.created_by as boq_created_by",array('boq_id' => $boq_where['boq_id']))->row();
    $dpr_where['dpr_id'] = $this->input->post('dpr_id');
    $dpr_data['vehicle_no'] = $this->input->post('vehicle_no');
    $dpr_data['applicator_name'] = $this->input->post('applicator_team_name');
    if($this->input->post('subcontract')){
      $dpr_data['subcontract_id'] = $this->input->post('subcontract');
    }
    $dpr_data['supervisor_id'] = $this->input->post('supervisor');
    $dpr_data['no_of_labours'] = $this->input->post('no_of_labours');
    if($this->input->post('start_time')!=''){
      $dpr_data['start_time'] = date('H:i:s',strtotime($this->input->post('start_time')));
    }
    if($this->input->post('end_time')!=''){
      $dpr_data['end_time'] = date('H:i:s',strtotime($this->input->post('end_time')));
    }
    $dpr_data['updated_by'] = $this->session->userdata('user_id');
    $dpr_data['updated_date'] = date('Y-m-d H:i:s');

    $dpr_count = $this->Boq->select_boq_dpr('bdp.dpr_id,bdp.work_date',$dpr_where);
    if($dpr_count->num_rows()==1){
      $result = $this->Boq->update_boq_dpr($dpr_data,$dpr_where);
      if($result==1){
        //DPR measurements Items
        $measurements_array=$newArraymeasurements=array();
        if($this->input->post('measurements')){
          $measurements_array = $this->input->post('measurements');
        }
        $measurements_array_length = sizeof($measurements_array);
        foreach (array_keys($measurements_array) as $fieldKey) {
          foreach ($measurements_array[$fieldKey] as $key=>$value) {
            $newArraymeasurements[$key][$fieldKey] = $value;
          }
        }

        $i = 0;
        $item_data['dpr_id'] = $dpr_where['dpr_id'];
        foreach ($newArraymeasurements as $row) {
          $item_where = array();
          $item_data['chainage_from'] = $row['chainage_from'];
          if(isset($row['chainage_to'])){
            $item_data['chainage_to'] = $row['chainage_to'];
          }
          if(isset($row['item'])){
            $item_data['item_material_id'] = $row['item'];
          }
          $item_data['side'] = $row['side'];
          if(isset($row['spacing'])){
            $item_data['spacing'] = $row['spacing'];
          }
          if(isset($row['qty_no'])){
            $item_data['quantity'] = $row['qty_no'];
          }
          if(isset($row['length'])){
            $item_data['chainage_length'] = $row['length'];
          }
          if(isset($row['width'])){
            $item_data['chainage_width'] = $row['width'];
          }
          if(isset($row['total_qty'])){
            $item_data['chainage_total'] = $row['total_qty'];
          }
          if(isset($row['ref_no'])){
            $item_data['reference_no'] = $row['ref_no'];
          }
          $item_data['remarks'] = $row['remarks'];
          if(isset($row['item_id'])){
            // update
            $item_where['item_id'] = $row['item_id'];
            $item_result = $this->Boq->update_boq_dpr_items($item_data,$item_where);
            $dpr_item_id = $row['item_id'];
          }else{
            // create
            $item_result1 = $this->Boq->insert_boq_dpr_items($item_data);
            $item_result = $item_result1['status'];
            $dpr_item_id = $item_result1['insert_id'];
          }
          if(isset($item_result) && $item_result==1){
            if(isset($row['material_qty'])){
              $material_qty = $row['material_qty'];
              foreach ($material_qty as $key => $value) {
                $material_data['item_id'] = $material_data_where['bdim.item_id'] = $dpr_item_id;
                $material_data['material_id'] = $material_data_where['bdim.material_id'] = $key;
                $material_data['quantity'] = $value;
                $material_details = $this->Boq->select_boq_dpr_item_materials('',$material_data_where);
                if($material_details->num_rows()==1){
                  $material_result = $this->Boq->update_boq_dpr_item_materials($material_data,$material_data_where);
                }else{
                  $material_result = $this->Boq->insert_boq_dpr_item_materials($material_data);
                }
              }
            }
          }
        }
      }

      // Material Consumption
      if($this->input->post('materials')){
        $materials_array=$newArraymaterials=array();
        $materials_array = $this->input->post('materials');
        $materials_array_length = sizeof($materials_array);
        foreach (array_keys($materials_array) as $fieldKey) {
          foreach ($materials_array[$fieldKey] as $key=>$value) {
            $newArraymaterials[$key][$fieldKey] = $value;
          }
        }
        $stock_materials = $this->Stock->select_stock_register("m.material_name,m.material_id,mu.unit_name",array("sl.work_id"=>$boq_data->project_id),'sr.material_id')->result();
        foreach ($stock_materials as $key => $value) {
          if(isset($newArraymaterials[$value->material_id])){
            $material_consumption = array();
            $material_consumption['dpr_id'] = $material_consumption_where['bdmc.dpr_id'] = $dpr_where['dpr_id'];
            $material_consumption['material_id'] = $material_consumption_where['bdmc.material_id'] = $value->material_id;
            $material_consumption['opening_stock'] = $newArraymaterials[$value->material_id]['opening_qty'];
            $material_consumption['received_qty'] = $newArraymaterials[$value->material_id]['received_qty'];
            $material_consumption['consumed_qty'] = $newArraymaterials[$value->material_id]['consumed_qty'];
            $material_consumption['balance_qty'] = $newArraymaterials[$value->material_id]['balance_qty'];
            $material_consumption['remarks'] = $newArraymaterials[$value->material_id]['remarks'];

            $material_consumption_details = $this->Boq->select_boq_dpr_material_consumption('',$material_consumption_where);
            if($material_consumption_details->num_rows()==1){
              $material_consumption['updated_by'] = $this->session->userdata('user_id');
              $material_consumption['updated_date'] = date('Y-m-d H:i:s');
              $material_consumption_result = $this->Boq->update_boq_dpr_material_consumption($material_consumption,$material_consumption_where);
            }else{
              $material_consumption['created_by'] = $this->session->userdata('user_id');
              $material_consumption['created_date'] = date('Y-m-d H:i:s');
              $material_consumption_result1 = $this->Boq->insert_boq_dpr_material_consumption($material_consumption);
              $material_consumption_result = $material_consumption_result1['status'];
            }
            if($material_consumption_result==1){
              if($material_consumption_details->num_rows()==1 && $material_consumption_details->row()->consumed_qty!=$material_consumption['consumed_qty']){
                // Update Stock Consumption
                // Delete old Consumption data
                $stock_cons_data = $this->Stock->select_stock_consumption("cons_id,sc.stock_id",array("dpr_cons_id"=>$material_consumption['dpr_id'],"m.material_id"=>$material_consumption['material_id']))->result();
                foreach ($stock_cons_data as $key77 => $value77) {
                  $cons_delete_data['cons_id'] = $value77->cons_id;
                  $cons_delete_data['delete_status'] = 1;
                  $cons_delete_result = $this->Stock->update_stock_consumption($cons_delete_data);
                  //  Update Stock Register
                  $stock_reg_update = $this->stock_management->calculate_stock_balance($value77->stock_id);
                }
              }

              if(($material_consumption_details->num_rows()==0) || ($material_consumption_details->num_rows()==1 && $material_consumption_details->row()->consumed_qty!=$material_consumption['consumed_qty'])){
                // Insert to Stock Consumption
                $stock_conusmption_data['work_id'] = $boq_data->project_id;
                $stock_conusmption_data['consumption_date'] = $dpr_count->row()->work_date;
                $stock_cons_data = $this->Stock->select_stock_consumption("MAX(cons_group_id) as last_group_id");
                if ($stock_cons_data->num_rows() == 1) {
                  $stock_conusmption_data['cons_group_id'] = ($stock_cons_data->row()->last_group_id) + 1;
                } else {
                  $stock_conusmption_data['cons_group_id'] = 1;
                }
                $stock_conusmption_data['project_stage_id'] = $this->projects_management->get_project_stage_id($boq_data->project_id);
                $stock_conusmption_data['created_date'] = date('Y-m-d H:i:s');
                $stock_conusmption_data['created_by'] = $this->session->userdata('user_id');
                $stock_conusmption_data['remarks'] = $material_consumption['remarks'];
                $stock_conusmption_data['dpr_cons_id'] = $material_consumption['dpr_id'];

                $remaining_qty = $material_consumption['consumed_qty'];
                $stock_register_where['sl.work_id'] = $boq_data->project_id;
                $stock_register_where['sr.material_id'] = $value->material_id;
                $stock_register_where['sr.total_balance_qty >'] = 0;
                $stock_register = $this->Stock->select_stock_register("stock_id,total_balance_qty", $stock_register_where)->result();
                foreach ($stock_register as $key22 => $value22) {
                  if ($remaining_qty > 0) {
                    $available_stock_item_qty = $value22->total_balance_qty;
                    if ($remaining_qty > $available_stock_item_qty) {
                      $stock_conusmption_data['consumption_qty']  = $available_stock_item_qty;
                    } else {
                      $stock_conusmption_data['consumption_qty']  = $remaining_qty;
                    }
                    $remaining_qty = $remaining_qty - $stock_conusmption_data['consumption_qty'];
                    $stock_conusmption_data['stock_id'] = $value22->stock_id;
                    // Update Stock Consumption
                    $stock_conusmption_result = $this->Stock->insert_stock_consumption($stock_conusmption_data);
                    //  Update Stock Register
                    $stock_conusmption_result2 = $this->stock_management->calculate_stock_balance($stock_conusmption_data['stock_id']);
                  }
                }
              }
            }
          }
        }
        $this->boq_management->auto_correct_material_consumption_balance($boq_data->project_id,$dpr_count->row()->work_date);
      }



      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = 'BOQ DPR Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }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);
  }
}
