<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Invoices 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_order_model','Work_order');
    $this->load->model('Documents_model', 'Documents');
    $this->load->model('Invoices_model', 'Invoices');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->library('Bills_management','bills_management');
    $this->load->library('Accounts_management', 'accounts_management');
    $this->load->library('Projects_management','projects_management');

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

  public function view($invoice_type='project_invoice')
  {
    $work_data = $user_data = $invoice_where = array();

    $this->page_data['invoice_type'] = $invoice_type;
    if($invoice_type=='other_income'){
      $this->page_data['invoice_title'] = 'Other Income Invoices';
      $invoice_where['invoice_type'] = 'other_income';
    }elseif($invoice_type=='proforma'){
      $this->page_data['invoice_title'] = 'Proforma Invoices';
      $invoice_where['invoice_type'] = 'proforma';
    }else{
      $this->page_data['invoice_title'] = 'Project Invoices';
      $invoice_where['invoice_type'] = 'project_invoice';
    }
    $this->page_data['invoices'] = $this->Invoices->select_invoices("*,u1.user_id as i_created_by,u1.user_alias as i_created,u2.user_alias as prepared_by_user",$invoice_where,'all')->result();

    $this->page_data['total_invoice_data'] = $this->Invoices->select_invoices("count(*) as invoice_count,COALESCE(SUM(i.invoice_total_amount),0) as total_invoice_amount,COALESCE(SUM(i.total_paid),0) as total_invoice_received,COALESCE(SUM(i.balance_amount),0) as total_invoice_balance",$invoice_where)->row();
    $invoice_where['project_status'] = 1;
    $this->page_data['balance_to_receive_on_completed'] = $this->Invoices->select_invoices("COALESCE(SUM(i.balance_amount),0) as total_invoice_balance",$invoice_where)->row()->total_invoice_balance;

    $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();
    $this->page_data['users'] = $this->User->select_user("",$user_data)->result();

    $this->page_data['page_name'] = 'invoices_view';
    $this->load->view('Index',$this->page_data);
  }
  public function payments()
  {

    $this->page_data['page_name'] = 'invoices_payments';
    $work_data = $user_data = $data =  array();

    $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();
    $this->page_data['invoices'] = $this->Invoices->select_invoices("*,u1.user_id as i_created_by,u1.user_alias as i_created",$data)->result();

    $this->page_data['users'] = $this->User->select_user("",$user_data)->result();
    $this->load->view('Index',$this->page_data);
  }
  public function receivable()
  {

    $this->page_data['page_name'] = 'invoices_receivable';
    $work_data = $user_data = array();

    $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();
    $this->page_data['users'] = $this->User->select_user("",$user_data)->result();
    $this->load->view('Index',$this->page_data);
  }
  public function profile($id='',$view='view',$print_transactions=false)
  {
    if(isset($id) && $id!=''){

      $data['i.invoice_id'] = $data2['ii.invoice_id'] = $id;
      // $payment_data['reference_type_2'] = 'invoice';
      $payment_data['ats.invoice_id'] = $id;

      $invoice_data = $this->Invoices->select_invoices("i.*,wc.enquiry_id,wc.lpo_no,wc.work_name,client_name,client_address,client_email,client_contact,c.tax_no,tt.tax_percentage,tt.tax1_percent,tt.tax2_percent,tt.tax3_percent,u1.user_id as i_created_by,u1.user_alias as i_created,v.vehicle_no,ba.*,u2.user_alias as prepared_by_user",$data,'all')->result();
      if(empty($invoice_data)){
        show_404();
      }else{
        $this->page_data['invoice'] = $invoice_data[0];
        if($this->page_data['invoice']->invoice_type!='proforma'){
          $this->page_data['invoice']->receivable_amount_in_words = $this->accounts_management->amount_in_words(number_format($this->page_data['invoice']->invoice_total_amount,$this->config->item('Currency_amount_decimals_2'),'.',''));
        }else{
          $this->page_data['invoice']->receivable_amount_in_words = $this->accounts_management->amount_in_words(number_format($this->page_data['invoice']->claiming_advance_amount,$this->config->item('Currency_amount_decimals_2'),'.',''));
        }
        $this->page_data['invoice']->tax_amount_in_words = $this->accounts_management->amount_in_words(number_format($this->page_data['invoice']->invoice_tax_amount,$this->config->item('Currency_amount_decimals_2'),'.',''));
        $this->page_data['invoice_items'] = $this->Invoices->select_invoice_items("*",$data2)->result();
        if ($this->config->item('Client_Invoice_work_order_connected') == 1){
          foreach ($this->page_data['invoice_items'] as $key => $value) {
            if($value->work_order_item_id!=0){
              $work_order_details = $this->Work_order->select_work_order_items("woi.*,mu.unit_name,wt.type_name",array("item_id"=>$value->work_order_item_id))->row();
              $value->type_name = $work_order_details->type_name;
            }
          }
        }
        $order_by[0]['column'] = 'tr_date';
        $order_by[0]['order'] = 'asc';
        if($this->page_data['invoice']->invoice_type=='other_income'){
          $this->page_data['invoice_payments'] = $this->Account->select_account_transaction("ats.*,u1.user_alias as created_user,u2.user_alias as updated_user,ah2.acc_head_name as credit_account",$payment_data,'income_receipts','','',$order_by)->result();
        }else{
          $this->page_data['invoice_payments'] = $this->Account->select_account_transaction("ats.*,c.client_email,c.client_id,c.client_name,wc.work_id,wc.work_name,u1.user_alias as created_user,u2.user_alias as updated_user,ah2.acc_head_name as credit_account",$payment_data,'client_payment','','',$order_by)->result();
        }
        $this->page_data['client_data'] = $this->Client->select_client("",array("client_id"=>$this->page_data['invoice']->client_id))->row();
        $work_data = $user_data = array();
        $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();
        $this->page_data['users'] = $this->User->select_user("",$user_data)->result();

        if($this->page_data['invoice']->enquiry_id!=0){
          $this->page_data['enquiry_data'] = $this->Enquiries->select_enquiries("*,u1.user_alias as assigned_user", array("enquiry_id"=>$this->page_data['invoice']->enquiry_id));
          if($this->page_data['enquiry_data']->num_rows()==1){
            $this->page_data['enquiry_data'] = $this->page_data['enquiry_data']->row();
          }
        }
        $this->page_data['print_transactions'] = $print_transactions;

        if($view=='print'){
          $this->load->view('modules/invoices/invoice_print_'.$this->config->item('Client_Payment_client_payment_invoice_template'),$this->page_data);
        }else{
          $this->page_data['page_name'] = 'invoice_profile';
          $this->load->view('Index',$this->page_data);
        }
      }
    }
    else
    {
      show_404();
    }
  }
  // public function print_invoice($id)
  // {
  //   $this->page_data['page_name'] = 'print_invoice';
  //   $payment_data['ats.invoice_id'] = $id;
  //   $data['i.invoice_id'] = $data2['ii.invoice_id'] = $id;
  //   $this->page_data['invoice'] = $this->Invoices->select_invoices("*,u1.user_id as i_created_by,u1.user_alias as i_created",$data)->result()[0];
  //   $this->page_data['invoice_items'] = $this->Invoices->select_invoice_items("*",$data2)->result();
  //   $this->page_data['invoice_payments'] = $this->Account->select_account_transaction("ats.*,c.client_email,c.client_id,c.client_name,wc.work_id,wc.work_name,u1.user_alias as created_user,u2.user_alias as updated_user,ah2.acc_head_name as credit_account",$payment_data,'client_payment')->result();
  //   $work_data = $user_data = array();
  //   $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();
  //   $this->page_data['users'] = $this->User->select_user("",$user_data)->result();
  //   $this->load->view('Index',$this->page_data);
  // }
  public function add($invoice_type='project_invoice',$id="")
  {

    $this->page_data['bank_accounts'] = $this->Settings->select_bank_account_details()->result();
    $this->page_data['invoice_type'] = $invoice_type;
    if($invoice_type=='other_income'){
      $this->page_data['invoice_title'] = 'Other Income Invoices';
    }elseif($invoice_type=='proforma'){
      $this->page_data['invoice_title'] = 'Proforma Invoices';
    }else{
      $this->page_data['invoice_title'] = 'Project Invoices';
    }

    $this->page_data['measure_units'] = $this->Material->select_unit()->result();
    $work_data = $user_data = array();
    if(isset($id) && $id!=''){
      $this->page_data['invoice_work_id'] = $id;
      $this->page_data['work_data'] = $this->Work->select_work("*",$work_data)->row();
    }
    $this->page_data['page_name'] = 'invoice_add';
    $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();
    $this->page_data['users'] = $this->User->select_user("",$user_data)->result();
    $this->load->view('Index',$this->page_data);
  }
  public function edit($id="")
  {
    $this->page_data['bank_accounts'] = $this->Settings->select_bank_account_details()->result();
    $this->page_data['measure_units'] = $this->Material->select_unit()->result();
    $work_data = $user_data = array();
    if(isset($id) && $id!=''){
      $this->page_data['page_name'] = 'invoice_edit';

      $data['i.invoice_id'] = $data2['ii.invoice_id'] = $id;
      $this->page_data['invoice'] = $this->Invoices->select_invoices("i.*,u1.user_id as i_created_by,u1.user_alias as i_created",$data,'all')->result()[0];

      $this->page_data['invoice_type'] = $this->page_data['invoice']->invoice_type;
      if($this->page_data['invoice_type']=='other_income'){
        $this->page_data['invoice_title'] = 'Other Income Invoices';
      }else{
        $this->page_data['invoice_title'] = 'Project Invoices';
      }
      // $work_data['w.work_id'] =  $this->page_data['invoice']->project_id;
      $this->page_data['work_contracts'] = $this->Work->select_work("*",$work_data)->result();

      $this->page_data['invoice_items'] = $this->Invoices->select_invoice_items("*",$data2)->result();
      $this->page_data['users'] = $this->User->select_user("",$user_data)->result();
      $this->load->view('Index',$this->page_data);
    }
    else{
      show_404();
    }
  }

  public function select_invoices($list_type="",$page_data_type=''){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $taxable_amount=$tax_amount=$tax1_amount=$tax2_amount=$tax3_amount=$total_amount=$total_received=$total_balance=0;
    $data=array();
    // if(isset($_POST['date']) && $_POST['date']!=''){
    //   $date=array();
    //   $date=explode('-',$_POST['date']);
    //   $start_date=date('Y-m-d', strtotime($date[0]));
    //   $end_date=date('Y-m-d', strtotime($date[1]));
    //   $data["STR_TO_DATE(i.created_date,'%Y-%m-%d') <="]= $end_date;
    //   $data["STR_TO_DATE(i.created_date,'%Y-%m-%d') >="]= $start_date;
    // }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $data["i.invoice_date >="]= date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $data["i.invoice_date <="]= date('Y-m-d', strtotime($_POST['end_date']));
    }
    if(isset($_POST['work_status']) && $_POST['work_status']!='' && $_POST['work_status']!='all'){
      $data['i.project_status'] = $_POST['work_status'];
    }
    if(isset($_POST['payment_status']) && $_POST['payment_status']!='' && $_POST['payment_status']!='all'){
      if($_POST['payment_status']==1){
        $data['i.balance_amount'] = 0;
      }else{
        $data['i.balance_amount >'] = 0;
      }
    }
    if(isset($_POST['invoice_id']) && $_POST['invoice_id']!='' && $_POST['invoice_id']!='all'){
      $data['i.invoice_id'] = $_POST['invoice_id'];
    }

    if(isset($_POST['invoice_type']) && $_POST['invoice_type']!='' && $_POST['invoice_type']!='all'){
      $data['i.invoice_type'] = $_POST['invoice_type'];
    }else{
      $data['i.invoice_type'] = 'project_invoice';
      // $this->db->where("(i.invoice_type = 'project_invoice' or i.invoice_type = 'proforma')");
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['i.project_stage_id'] = $_POST['stage_id'];
    }
    if(isset($_POST['project']) && $_POST['project']!='' && $_POST['project']!='all'){
      $data['i.project_id'] = $_POST['project'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('i.project_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['type']) && $_POST['type']!='' && $_POST['type']!='all'){
      $data['i.balance_amount >'] = '0';
    }
    if($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_client_payment_view_all')==0){
      // $data['i.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['created_by']) && $_POST['created_by']!='' && $_POST['created_by']!='all'){
      $this->db->where("i.created_by",$_POST['created_by']);
    }
    if($this->session->userdata('user_role')=='office_staff') {
      $user_id = $this->session->userdata('user_id');
      $this->db->where("(wc.assigned_users=$user_id or pd.created_by=$user_id)");
    }

    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['wc.branch_id'] = $_POST['branch_id'];
    }

    $entry_approval = 1;
    if($this->config->item('User_enable_data_entry_approval')==1){//webapp users approval
      $entry_approval = 'all';
    }
    if($page_data_type=='approval_entries'){
      $entry_approval = 'all';
      $data['u1.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
      }
    }
    if($list_type=='payment'){
      $entry_approval = 'all';
    }
    $result = $this->Invoices->select_invoices("*,u1.user_id as i_created_by,u1.user_alias as i_created,i.created_date as i_created_date,wc.work_name,c.client_name,wc.branch_id as branch_id,i.client_id as invoice_client_id",$data,$entry_approval);
    $result_array=$result->result();

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

    foreach($result_array as $row):
      $btn_payment = $btn_edit=$btn_delete='';
      if(($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_id')==$row->created_by) && ($this->config->item('User_enable_data_entry_approval')!=1 || $row->entry_approval_status!=1 || $this->session->userdata('user_role')=='admin') ) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="document_edit_btn" href="'. base_url().'invoices/edit/'.$row->invoice_id.'" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="invoice_delete_btn" href="#invoice_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      }

      if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='general_manager') || $this->session->userdata('user_id')== $row->i_created_by || ($this->session->userdata('user_role')=='auditor' && $this->session->userdata('user_data_permission')['adding']==1)) {
        if($row->balance_amount>0){
          $btn_payment = '<a style="margin-left: 5px;margin-right: 5px" id="invoice_payment_btn" href="#client_payment_add_modal" data-toggle="modal" class="btn btn-brand m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-money"></i>
          </a>';
        }
      }

      if($row->payment_status==1){
        $status = '<span style="margin-top: 5px" class="m-badge m-badge--success m-badge--wide"><i class="fa fa-check-circle-o"></i>Received</span>';
      }elseif($row->payment_status==2){
        $status = '<span style="margin-top: 5px" class="m-badge m-badge--warning m-badge--wide">Partially Received</span>';
      }else{
        $status = '<span style="margin-top: 5px" class="m-badge m-badge--danger m-badge--wide">Not Received</span>';
      }

      if($row->invoice_type=='other_income'){
        if($row->project_status==1){
          $status .= '<br/><span style="margin-top: 5px" class="m-badge m-badge--success m-badge--wide"><i class="fa fa-check-circle"></i> Work Completed</span>';
        }elseif($row->project_status==2){
          $status .= '<br/><span style="margin-top: 5px" class="m-badge m-badge--warning m-badge--wide"> Work Pending</span>';
        }
      }

      $btn_approve = $entry_approval_status = '';
      if($this->session->userdata('user_role')=='admin' && $page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1){
        $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="client_invoice" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->invoice_id.'" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
        <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
        </a>';
      }
      if(($page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1) || $this->config->item('User_enable_data_entry_approval')==1){
        if($row->entry_approval_status==1){
          $entry_approval_status="<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
        }elseif($row->entry_approval_status==2){
          $entry_approval_status="<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
        }else{
          $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
        }
      }

      if($this->session->userdata('user_role')=='general_manager' ||$this->session->userdata('user_role')=='auditor' || $this->session->userdata('user_role')=='accounts_manager' || $this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')== $row->i_created_by ){

        $row->tax1_amount = round($row->invoice_taxable_amount*$row->tax1_percent/100,$this->config->item('Currency_amount_decimals_2'));
        $row->tax2_amount = round($row->invoice_taxable_amount*$row->tax2_percent/100,$this->config->item('Currency_amount_decimals_2'));
        $row->tax3_amount = round($row->invoice_taxable_amount*$row->tax3_percent/100,$this->config->item('Currency_amount_decimals_2'));

        $invoice_no = '';
        if($row->invoice_type=='proforma'){
          $invoice_no .= $this->config->item('client_invoice_proforma_prefix');
        }else{
          if($row->tax_invoice==1){
            if ($this->config->item('Client_Payment_invoice_business_type') == 1) {
            if($row->business_type=='B2B'){
              $invoice_no .= $this->config->item('client_invoice_tax_b2b_prefix');
            }else{
              $invoice_no .= $this->config->item('client_invoice_tax_b2c_prefix');
            }
          }
          }else{
            $invoice_no .= $this->config->item('client_invoice_prefix');
          }
        }
        if (strpos($invoice_no, 'y') !== false) {
          $year = date('y',strtotime($row->invoice_date));
          $invoice_no = str_replace('y', $year, $invoice_no);
        }
        $invoice_no .= sprintf('%04u', $row->invoice_no);
        $invoice_no .= $row->invoice_suffix;
        if($row->reference_no!=''){
          $invoice_no .= '<br/>Ref No: '.$row->reference_no;
        }

        $sl_no++;
        $array[$j][]=$sl_no;
        $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
        $array[$j][]=ucwords(str_replace('_',' ',$row->invoice_type));
        $array[$j][]='<a href="'. base_url().'invoices/profile/'.$row->invoice_id.'">'.$invoice_no.'</a>';
        $array[$j][]=$row->client_name;
        $array[$j][]='<a href="'.base_url().'work/profile/'.$row->project_id.'">#'.$row->project_id.' - '.$row->work_name.'</a>';
        $array_out[$j]['work_name'] = $row->work_name;
        $array[$j][]=date('d-m-Y',strtotime($row->invoice_date));
        $array[$j][]= number_format($row->invoice_taxable_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]= $row->tax_percentage."%";
        $array[$j][]= number_format($row->invoice_tax_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=$row->tax1_percent;
        $array[$j][]=number_format($row->tax1_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=$row->tax2_percent;
        $array[$j][]=number_format($row->tax2_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=$row->tax3_percent;
        $array[$j][]=number_format($row->tax3_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][]=$array_out[$j]['total'] = $row->invoice_total_amount;
        $array[$j][]=$array_out[$j]['total_paid'] = $row->total_paid;
        $array[$j][]=$array_out[$j]['balance'] = $row->balance_amount;
        $array[$j][]=$status;
        $array[$j][]=$row->i_created.$entry_approval_status;
        if ($this->config->item('UI_hide_created_date_field')==0){
          $array[$j][]=date('d-m-Y',strtotime($row->i_created_date));
        }else{
          $array[$j][]='';
        }
        $array[$j][]=$btn_payment.$btn_edit.$btn_delete.$btn_approve;
        $array[$j][]=$array_out[$j]['invoice_id'] = $row->invoice_id;
        $array[$j][] = $row->entry_approval_status;
        $array[$j][] = $row->invoice_type;
        if($row->invoice_type=='other_income'){
          $array[$j][] = $row->invoice_client_id;
        }else{
          $array[$j][] = $row->project_id;
        }

        $array_out[$j]['client_name'] = $row->client_name;
        $array_out[$j]['work_id'] = $row->work_id;

        $taxable_amount+=$row->invoice_taxable_amount;
        $tax_amount+=$row->invoice_tax_amount;
        $tax1_amount+=$row->tax1_amount;
        $tax2_amount+=$row->tax2_amount;
        $tax3_amount+=$row->tax3_amount;
        $total_amount+=$row->invoice_total_amount;
        $total_received+=$row->total_paid;
        $total_balance+=$row->balance_amount;

        $j++;
      }

    endforeach;

    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($taxable_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($tax_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][] = '';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($tax1_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][] = '';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($tax2_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($tax3_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_received,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_balance,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
    }

    $json_data['data']=$array;
    if($list_type=='payment'){
      $json_data = $array_out;
    }
    echo json_encode($json_data);  // send data as json format
  }

  public function create()
  {
    $data['invoice_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('bill_date'))));
    $invoice_month = date('m',strtotime($data['invoice_date']));
    $invoice_year = date('Y',strtotime($data['invoice_date']));
    if($invoice_month>=4){
      $fin_year_name = $invoice_year.'-'.($invoice_year+1);
      $fin_year_short = date('y',strtotime($invoice_year)).'-'.(date('y',strtotime($invoice_year))+1);
    }else{
      $fin_year_name = ($invoice_year-1).'-'.($invoice_year);
      $fin_year_short = (date('y',strtotime($invoice_year))-1).'-'.date('y',strtotime($invoice_year));
    }
    $fin_year_data = $this->Settings->select_finyear('',array("fin_year"=>$fin_year_name));
    if($fin_year_data->num_rows()==1){
      $data['finyear'] = $fin_year_data->row()->finyear_id;
      $fin_year = $fin_year_data->row()->fin_year;
    }elseif($fin_year_data->num_rows()==0){
      $fin_year = $insert_data['fin_year'] = $fin_year_name;
      $insert_data['fin_year_short'] = $fin_year_short;
      $insert_data['active_status'] = 0;
      $fin_year_insert_result = $this->Settings->insert_finyear($insert_data);
      $data['finyear'] = $fin_year_insert_result['insert_id'];
    }elseif($fin_year_data->num_rows()>1){
      $data['finyear'] = $fin_year_data[0]->row()->finyear_id;
      $fin_year = $fin_year_data[0]->row()->fin_year;
    }
    if(isset($data['finyear'])){
      if($this->config->item('client_invoice_suffix')=='/d/m/Y'){
        $data['invoice_suffix'] = "/".date('d/m/Y',strtotime($this->security->xss_clean($this->input->post('bill_date'))));
      }elseif($this->config->item('client_invoice_suffix')=='/fy'){
        $fin_year_array = explode("-",$fin_year);
        $fin_year_2 = $fin_year_array[0];
        $fin_year_2 = substr( $fin_year_2, -2);
        $data['invoice_suffix'] = "/".$fin_year_2;
      }elseif($this->config->item('client_invoice_suffix')=='/fy-y'){
        $fin_year_array = explode("-",$fin_year);
        $fin_year_2 = $fin_year_array[0];
        $fin_year_2 = substr( $fin_year_2, -2);
        $fin_year_3 = $fin_year_array[1];
        $fin_year_3 = substr( $fin_year_3, -2);
        $data['invoice_suffix'] = "/".$fin_year_2.'-'.$fin_year_3;
      }elseif($this->config->item('client_invoice_suffix')=='/y'){
        $data['invoice_suffix'] = "/".date('Y',strtotime($this->security->xss_clean($this->input->post('bill_date'))));
      }
    }

    $data['tax_invoice'] = $this->security->xss_clean($this->input->post('invoice_tax_type'));
    $data['invoice_type'] = $this->security->xss_clean($this->input->post('invoice_type'));
    $data['business_type'] = '';
    if($data['tax_invoice']==1 && $this->input->post('business_type')){
      $data['business_type'] = $this->security->xss_clean($this->input->post('business_type'));
      $invoice_where['i.business_type'] = $data['business_type'];
    }
    // $data['branch_id'] = $this->session->userdata('branch_id');
    // $invoice_where['i.branch_id'] = $data['branch_id'];
    $invoice_where['i.tax_invoice'] = $data['tax_invoice'];
    if($this->config->item('Client_Payment_invoice_no_based_finyear')==1){
      $invoice_where['i.finyear'] = $data['finyear'];
    }
    if($data['invoice_type']=='proforma'){
      $invoice_where['i.invoice_type'] = $data['invoice_type'];
    }
    $invoice_last_data = $this->Invoices->select_invoices("max(i.invoice_no) as max_invoice_no",$invoice_where,'all');
    if($invoice_last_data->num_rows()==1){
      $data['invoice_no'] = ($invoice_last_data->row()->max_invoice_no)+1;
    }else{
      $data['invoice_no'] = 1;
    }
    if($this->input->post('invoice_rate_type')){
      $data['invoice_rate_type'] = $this->security->xss_clean($this->input->post('invoice_rate_type'));
    }

    $data['reference_no'] = $this->security->xss_clean($this->input->post('bill_no'));
    if($this->input->post('vehicle_id')){
      $data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
    }
    if($this->input->post('work_status')){
      $data['project_status'] = $this->security->xss_clean($this->input->post('work_status'));
    }
    $data['prepared_by'] = $this->security->xss_clean($this->input->post('prepared_by'));
    $data['invoice_from'] = $this->security->xss_clean($this->input->post('bill_from'));
    if($data['invoice_type']=='other_income'){
      $data['client_id'] = $this->security->xss_clean($this->input->post('client'));
    }else{
      $data['project_id'] = $this->security->xss_clean($this->input->post('work'));
      $data['client_id'] = $this->Work->select_work("w.client_id",array("work_id"=>$data['project_id']))->row()->client_id;
      $data['project_stage_id'] = $this->projects_management->get_project_stage_id($data['project_id']);
      $payment_data['tr_project_stage_id'] = $this->projects_management->get_project_stage_id($data['project_id']);
    }
    $data['invoice_total_amount'] = $this->security->xss_clean($this->input->post('bill_total_amount'));
    $data['invoice_tax_inclusive'] =  $this->security->xss_clean($this->input->post('tax_inclusive'));
    $data['invoice_taxable_amount'] = $this->security->xss_clean($this->input->post('bill_taxable_amount'));
    if($this->config->item('Client_Payment_client_payment_invoice_template')!=3 && $this->config->item('Client_Payment_client_payment_invoice_template')!=5 && $this->config->item('Client_Payment_client_payment_invoice_template')!=6 && $this->config->item('Client_Payment_client_payment_invoice_template')!=7){
      $data['invoice_tax_percent'] = $this->security->xss_clean($this->input->post('client_payment_tax_percent'));
    }
    $data['invoice_tax_amount'] = $this->security->xss_clean($this->input->post('bill_tax_amount'));
    $data['invoice_retention_percent'] = $this->security->xss_clean($this->input->post('bill_retention_percent'));
    $data['invoice_retention_amount'] = $this->security->xss_clean($this->input->post('bill_retention_amount'));
    $data['invoice_tds_percent'] = $this->security->xss_clean($this->input->post('bill_tds_percent'));
    $data['invoice_tds_amount'] = $this->security->xss_clean($this->input->post('bill_tds_amount'));
    $data['invoice_discount_amount'] = $this->security->xss_clean($this->input->post('bill_discount_amount'));
    $data['advance_recovery_amt'] = $this->security->xss_clean($this->input->post('bill_advance_recovery_amount'));
    $data['invoice_round_amount'] = $this->security->xss_clean($this->input->post('bill_round_amount'));
    $data['invoice_notes'] = $this->security->xss_clean($this->input->post('invoice_notes'));
    $data['delivery_note'] = $this->security->xss_clean($this->input->post('delivery_note'));
    $data['supplier_reference_no'] = $this->security->xss_clean($this->input->post('suppliers_ref_no'));
    $data['other_reference'] = $this->security->xss_clean($this->input->post('other_reference'));
    $data['buyers_orderno'] = $this->security->xss_clean($this->input->post('buyers_order_no'));
    $data['quotation_no'] = $this->security->xss_clean($this->input->post('quotation_no'));
    $data['quotation_id'] = $this->security->xss_clean($this->input->post('quotation_id'));
    $data['despatch_doc_no'] = $this->security->xss_clean($this->input->post('despatch_doc_no'));
    $data['despatched_through'] = $this->security->xss_clean($this->input->post('despatched_through'));
    $data['destination'] = $this->security->xss_clean($this->input->post('destination'));
    $data['delivery_terms'] = $this->security->xss_clean($this->input->post('delivery_terms'));
    if($data['invoice_type']=='proforma'){
      $data['claiming_advance_percentage'] = $this->security->xss_clean($this->input->post('advance_claim_percent'));
      $data['claiming_advance_amount'] = $this->security->xss_clean($this->input->post('advance_claim_amount'));
    }
    if($this->input->post('buyers_order_date') && $this->input->post('buyers_order_date')!=''){
      $data['buyers_order_date'] = date('Y-m-d',strtotime($this->input->post('buyers_order_date')));
    }
    if($this->input->post('quotation_date') && $this->input->post('quotation_date')!=''){
      $data['quotation_date'] = date('Y-m-d',strtotime($this->input->post('quotation_date')));
    }
    if($this->input->post('delivery_note_date') && $this->input->post('delivery_note_date')!=''){
      $data['delivery_note_date'] = date('Y-m-d',strtotime($this->input->post('delivery_note_date')));
    }
    if($this->input->post('delivery_date') && $this->input->post('delivery_date')!=''){
      $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('delivery_date')));
    }
    if($this->input->post('shipping_name')){
      $data['shipping_name'] = $this->security->xss_clean($this->input->post('shipping_name'));
    }
    if($this->input->post('shipping_address')){
      $data['shipping_address'] = $this->security->xss_clean($this->input->post('shipping_address'));
    }
    $data['works_carried_at'] = $this->security->xss_clean($this->input->post('works_carried_at'));
    $data['payment_terms'] = $this->security->xss_clean($this->input->post('payment_terms'));
    $data['other_terms'] = $this->security->xss_clean($this->input->post('other_terms'));
    $data['bank_account'] = $this->security->xss_clean($this->input->post('bank_account'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');


    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $data['entry_approval_status'] = 0;
    }

    $row_count = $this->input->post('current_row_count');
    $result = $this->Invoices->create_invoice($data);

    if($this->input->post('received_amount') && $this->input->post('received_amount')>0){

      $payment_data['invoice_id'] = $result['insert_id'];
      if($data['invoice_type']=='other_income'){
        $payment_data['tr_type'] = 'income_receipt_transaction';
        $payment_data['reference_id'] = $data['client_id'];
        $payment_data['reference_type'] = 'client';
      }else{
        $payment_data['tr_type'] = 'client_payment_transaction';
        $payment_data['reference_id'] = $data['project_id'];
        $payment_data['reference_type'] = 'project';
      }
      $payment_data['tr_description'] = ucwords(str_replace('_',' ',$payment_data['tr_type']));
      $payment_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $payment_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('received_date'))));
      $payment_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $payment_data['tr_debit_acc'] = 2;//Client Payment Receipts
      $payment_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
      $payment_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
      $payment_data['created_date'] = $data['created_date'];
      $payment_data['created_by'] = $data['created_by'];
      $transaction_result =  $this->Account->create_account_transaction($payment_data);

    }

    if($row_count > 0){
      for ($i=0; $i < $row_count ; $i++)
      {
        $data2['invoice_id'] = $result['insert_id'];
        if($this->config->item('Client_Payment_client_payment_invoice_template')==1 || $this->config->item('Client_Payment_client_payment_invoice_template')==4){
          $data2['name'] = $this->input->post('item_name['.$i.']');
          $data2['item_code'] = $this->input->post('item_code['.$i.']');
          $data2['unit'] = $this->input->post('item_unit['.$i.']');
          $data2['quantity'] = $this->input->post('item_qty['.$i.']');
          $data2['price'] = $this->input->post('item_price['.$i.']');
          $data2['total_amount'] = $this->input->post('item_total['.$i.']');
        }elseif($this->config->item('Client_Payment_client_payment_invoice_template')==2){
          $data2['name'] = $this->input->post('item_date['.$i.']');
          $data2['quantity'] = 1;
          $data2['price'] = $this->input->post('item_total['.$i.']');
          $data2['total_amount'] = $this->input->post('item_total['.$i.']');
          $data2['description'] = $this->input->post('item_description['.$i.']');
        }elseif($this->config->item('Client_Payment_client_payment_invoice_template')==3){
          $data2['item_code'] = $this->input->post('item_code['.$i.']');
          $data2['name'] = $this->input->post('item_name['.$i.']');
          $data2['hsn_code'] = $this->input->post('item_hsn['.$i.']');
          $data2['mrp_amount'] = $this->input->post('item_mrp['.$i.']');
          $data2['unit'] = $this->input->post('item_unit['.$i.']');
          $data2['quantity'] = $this->input->post('item_qty['.$i.']');
          $data2['price'] = $this->input->post('item_price['.$i.']');
          $data2['item_taxable_amount'] = $this->input->post('item_taxable_amt['.$i.']');
          $data2['item_tax_percent'] = $this->input->post('item_tax_percent['.$i.']');
          $data2['item_tax_amount'] = $this->input->post('item_tax_amt['.$i.']');
          $data2['item_discount_percent'] = $this->input->post('item_disc_percent['.$i.']');
          $data2['item_discount_amount'] = $this->input->post('item_disc_amt['.$i.']');
          $data2['total_amount'] = $this->input->post('item_total['.$i.']');
        }elseif($this->config->item('Client_Payment_client_payment_invoice_template')==5 || $this->config->item('Client_Payment_client_payment_invoice_template')==6 || $this->config->item('Client_Payment_client_payment_invoice_template')==7){
          $data2['item_code'] = $this->input->post('item_code['.$i.']');
          $data2['name'] = $this->input->post('item_name['.$i.']');
          $data2['unit'] = $this->input->post('item_unit['.$i.']');
          $data2['quantity'] = $this->input->post('item_qty['.$i.']');
          $data2['price'] = $this->input->post('item_price['.$i.']');
          $data2['item_discount_percent'] = $this->input->post('item_disc_percent['.$i.']');
          $data2['item_discount_amount'] = $this->input->post('item_disc_amt['.$i.']');
          $data2['item_taxable_amount'] = $this->input->post('item_taxable_amt['.$i.']');
          $data2['item_tax_percent'] = $this->input->post('item_tax_percent['.$i.']');
          $data2['item_tax_amount'] = $this->input->post('item_tax_amt['.$i.']');
          $data2['total_amount'] = $this->input->post('item_total['.$i.']');
        }
        if ($this->config->item('Client_Invoice_work_order_connected') == 1){
          $data2['work_order_item_id'] = $this->input->post('item_work_order_task['.$i.']');
        }
        $data2['created_date'] = date('Y-m-d H:i:s');
        $data2['created_by'] = $this->session->userdata('user_id');
        $result_items = $this->Invoices->create_invoice_items($data2);
      }
    }
    $flash_data['status'] = $result['status'];
    if($result['status'] == 1){

      $this->bills_management->calculate_invoice_payment_total($result['insert_id']);

      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Invoice Added Succesfully';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['invoice_id'] = $result['insert_id'];
      if($data['invoice_type']=='project_invoice'){
        $flash_data['work_id'] = $data['project_id'];
      }
    }
    else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }


    echo json_encode($flash_data);
  }
  public function update()
  {
    $invoice_type = $this->security->xss_clean($this->input->post('invoice_type'));
    $data['invoice_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('bill_date'))));

    $invoice_month = date('m',strtotime($data['invoice_date']));
    $invoice_year = date('Y',strtotime($data['invoice_date']));
    if($invoice_month>=4){
      $fin_year_name = $invoice_year.'-'.($invoice_year+1);
      $fin_year_short = date('y',strtotime($invoice_year)).'-'.(date('y',strtotime($invoice_year))+1);
    }else{
      $fin_year_name = ($invoice_year-1).'-'.($invoice_year);
      $fin_year_short = (date('y',strtotime($invoice_year))-1).'-'.date('y',strtotime($invoice_year));
    }
    $fin_year_data = $this->Settings->select_finyear('',array("fin_year"=>$fin_year_name));
    if($fin_year_data->num_rows()==1){
      $data['finyear'] = $fin_year_data->row()->finyear_id;
      $fin_year = $fin_year_data->row()->fin_year;
    }elseif($fin_year_data->num_rows()==0){
      $fin_year = $insert_data['fin_year'] = $fin_year_name;
      $insert_data['fin_year_short'] = $fin_year_short;
      $insert_data['active_status'] = 0;
      $fin_year_insert_result = $this->Settings->insert_finyear($insert_data);
      $data['finyear'] = $fin_year_insert_result['insert_id'];
    }elseif($fin_year_data->num_rows()>1){
      $data['finyear'] = $fin_year_data[0]->row()->finyear_id;
      $fin_year = $fin_year_data[0]->row()->fin_year;
    }
    if(isset($data['finyear'])){
      if($this->config->item('client_invoice_suffix')=='/d/m/Y'){
        $data['invoice_suffix'] = "/".date('d/m/Y',strtotime($this->security->xss_clean($this->input->post('bill_date'))));
      }elseif($this->config->item('client_invoice_suffix')=='/fy'){
        $fin_year_array = explode("-",$fin_year);
        $fin_year_2 = $fin_year_array[0];
        $fin_year_2 = substr( $fin_year_2, -2);
        $data['invoice_suffix'] = "/".$fin_year_2;
      }elseif($this->config->item('client_invoice_suffix')=='/fy-y'){
        $fin_year_array = explode("-",$fin_year);
        $fin_year_2 = $fin_year_array[0];
        $fin_year_2 = substr( $fin_year_2, -2);
        $fin_year_3 = $fin_year_array[1];
        $fin_year_3 = substr( $fin_year_3, -2);
        $data['invoice_suffix'] = "/".$fin_year_2.'-'.$fin_year_3;
      }elseif($this->config->item('client_invoice_suffix')=='/y'){
        $data['invoice_suffix'] = "/".date('Y',strtotime($this->security->xss_clean($this->input->post('bill_date'))));
      }
    }
    if($this->input->post('invoice_rate_type')){
      $data['invoice_rate_type'] = $this->security->xss_clean($this->input->post('invoice_rate_type'));
    }
    $data['prepared_by'] = $this->security->xss_clean($this->input->post('prepared_by'));
    $data['reference_no'] = $this->security->xss_clean($this->input->post('bill_no'));
    $data['invoice_from'] = $this->security->xss_clean($this->input->post('bill_from'));
    if($invoice_type=='other_income'){
      $data['client_id'] = $this->security->xss_clean($this->input->post('client'));
    }else{
      $data['project_id'] = $this->security->xss_clean($this->input->post('work'));
      $data['client_id'] = $this->Work->select_work("w.client_id",array("work_id"=>$data['project_id']))->row()->client_id;
    }
    $data3['invoice_id'] = $data['invoice_id'] = $this->security->xss_clean($this->input->post('invoice_id'));
    $invoice_details = $this->Invoices->select_invoices("i.*",array("i.invoice_id"=>$data['invoice_id']))->row();
    if($invoice_details->finyear != $data['finyear'] && $this->config->item('Client_Payment_invoice_no_based_finyear')==1){
      if($invoice_details->tax_invoice==1){
        $invoice_where['i.business_type'] = $invoice_details->business_type;
      }
      // $data['branch_id'] = $this->session->userdata('branch_id');
      // $invoice_where['i.branch_id'] = $data['branch_id'];
      $invoice_where['i.tax_invoice'] = $invoice_details->tax_invoice;
      if($this->config->item('Client_Payment_invoice_no_based_finyear')==1){
        $invoice_where['i.finyear'] = $data['finyear'];
      }
      $invoice_last_data = $this->Invoices->select_invoices("max(i.invoice_no) as max_invoice_no",$invoice_where,'all');
      if($invoice_last_data->num_rows()==1){
        $data['invoice_no'] = ($invoice_last_data->row()->max_invoice_no)+1;
      }else{
        $data['invoice_no'] = 1;
      }
    }
    $data['invoice_total_amount'] = $this->security->xss_clean($this->input->post('bill_total_amount'));
    $data['invoice_tax_inclusive'] =  $this->security->xss_clean($this->input->post('tax_inclusive'));
    $data['invoice_taxable_amount'] = $this->security->xss_clean($this->input->post('bill_taxable_amount'));
    if($this->config->item('Client_Payment_client_payment_invoice_template')!=3 && $this->config->item('Client_Payment_client_payment_invoice_template')!=5 && $this->config->item('Client_Payment_client_payment_invoice_template')!=6 && $this->config->item('Client_Payment_client_payment_invoice_template')!=7){
      $data['invoice_tax_percent'] = $this->security->xss_clean($this->input->post('client_payment_tax_percent'));
    }else{
      $data['invoice_tax_percent'] = 0;
    }
    if($this->input->post('vehicle_id')){
      $data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
    }
    if($this->input->post('work_status')){
      $data['project_status'] = $this->security->xss_clean($this->input->post('work_status'));
    }
    $data['invoice_tax_amount'] = $this->security->xss_clean($this->input->post('bill_tax_amount'));
    $data['invoice_retention_percent'] = $this->security->xss_clean($this->input->post('bill_retention_percent'));
    $data['invoice_retention_amount'] = $this->security->xss_clean($this->input->post('bill_retention_amount'));
    $data['invoice_tds_percent'] = $this->security->xss_clean($this->input->post('bill_tds_percent'));
    $data['invoice_tds_amount'] = $this->security->xss_clean($this->input->post('bill_tds_amount'));
    $data['invoice_discount_amount'] = $this->security->xss_clean($this->input->post('bill_discount_amount'));
    $data['advance_recovery_amt'] = $this->security->xss_clean($this->input->post('bill_advance_recovery_amount'));
    $data['invoice_round_amount'] = $this->security->xss_clean($this->input->post('bill_round_amount'));
    $data['invoice_notes'] = $this->security->xss_clean($this->input->post('invoice_notes'));
    $data['delivery_note'] = $this->security->xss_clean($this->input->post('delivery_note'));
    $data['supplier_reference_no'] = $this->security->xss_clean($this->input->post('suppliers_ref_no'));
    $data['other_reference'] = $this->security->xss_clean($this->input->post('other_reference'));
    $data['buyers_orderno'] = $this->security->xss_clean($this->input->post('buyers_order_no'));
    $data['quotation_no'] = $this->security->xss_clean($this->input->post('quotation_no'));
    $data['quotation_id'] = $this->security->xss_clean($this->input->post('quotation_id'));
    $data['work_order_id'] = $this->security->xss_clean($this->input->post('work_order_id'));
    $data['despatch_doc_no'] = $this->security->xss_clean($this->input->post('despatch_doc_no'));
    $data['despatched_through'] = $this->security->xss_clean($this->input->post('despatched_through'));
    $data['destination'] = $this->security->xss_clean($this->input->post('destination'));
    $data['delivery_terms'] = $this->security->xss_clean($this->input->post('delivery_terms'));
    if($invoice_details->invoice_type=='proforma'){
      $data['claiming_advance_percentage'] = $this->security->xss_clean($this->input->post('advance_claim_percent'));
      $data['claiming_advance_amount'] = $this->security->xss_clean($this->input->post('advance_claim_amount'));
    }
    if($this->input->post('buyers_order_date') && $this->input->post('buyers_order_date')!=''){
      $data['buyers_order_date'] = date('Y-m-d',strtotime($this->input->post('buyers_order_date')));
    }
    if($this->input->post('quotation_date') && $this->input->post('quotation_date')!=''){
      $data['quotation_date'] = date('Y-m-d',strtotime($this->input->post('quotation_date')));
    }
    if($this->input->post('delivery_note_date') && $this->input->post('delivery_note_date')!=''){
      $data['delivery_note_date'] = date('Y-m-d',strtotime($this->input->post('delivery_note_date')));
    }
    if($this->input->post('delivery_date') && $this->input->post('delivery_date')!=''){
      $data['delivery_date'] = date('Y-m-d',strtotime($this->input->post('delivery_date')));
    }
    if($this->input->post('shipping_name')){
      $data['shipping_name'] = $this->security->xss_clean($this->input->post('shipping_name'));
    }
    if($this->input->post('shipping_address')){
      $data['shipping_address'] = $this->security->xss_clean($this->input->post('shipping_address'));
    }
    $data['works_carried_at'] = $this->security->xss_clean($this->input->post('works_carried_at'));
    $data['payment_terms'] = $this->security->xss_clean($this->input->post('payment_terms'));
    $data['other_terms'] = $this->security->xss_clean($this->input->post('other_terms'));
    $data['bank_account'] = $this->security->xss_clean($this->input->post('bank_account'));
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['updated_by'] = $this->session->userdata('user_id');
    $row_count = $this->input->post('current_row_count');
    $result = $this->Invoices->update_invoice($data);
    $item_id = $this->input->post('item_id');

    if($result==1){
      // Insert/Update Items
      $row_count = sizeof($this->input->post('item_name'));
      if($row_count > 0){
        foreach ($this->input->post('item_name') as $key => $value){
          $item_data=array();
          $item_data['invoice_id'] = $data['invoice_id'];
          if($this->config->item('Client_Payment_client_payment_invoice_template')==1 || $this->config->item('Client_Payment_client_payment_invoice_template')==4){
            $item_data['name'] = $this->input->post('item_name['.$key.']');
            $item_data['item_code'] = $this->input->post('item_code['.$key.']');
            $item_data['unit'] = $this->input->post('item_unit['.$key.']');
            $item_data['quantity'] = $this->input->post('item_qty['.$key.']');
            $item_data['price'] = $this->input->post('item_price['.$key.']');
            $item_data['total_amount'] = $this->input->post('item_total['.$key.']');
          }elseif($this->config->item('Client_Payment_client_payment_invoice_template')==2){
            $item_data['name'] = $this->input->post('item_date['.$key.']');
            $item_data['quantity'] = 1;
            $item_data['price'] = $this->input->post('item_total['.$key.']');
            $item_data['total_amount'] = $this->input->post('item_total['.$key.']');
            $item_data['description'] = $this->input->post('item_description['.$key.']');
          }elseif($this->config->item('Client_Payment_client_payment_invoice_template')==3){
            $item_data['item_code'] = $this->input->post('item_code['.$key.']');
            $item_data['name'] = $this->input->post('item_name['.$key.']');
            $item_data['hsn_code'] = $this->input->post('item_hsn['.$key.']');
            $item_data['mrp_amount'] = $this->input->post('item_mrp['.$key.']');
            $item_data['unit'] = $this->input->post('item_unit['.$key.']');
            $item_data['quantity'] = $this->input->post('item_qty['.$key.']');
            $item_data['price'] = $this->input->post('item_price['.$key.']');
            $item_data['item_taxable_amount'] = $this->input->post('item_taxable_amt['.$key.']');
            $item_data['item_tax_percent'] = $this->input->post('item_tax_percent['.$key.']');
            $item_data['item_tax_amount'] = $this->input->post('item_tax_amt['.$key.']');
            $item_data['item_discount_percent'] = $this->input->post('item_disc_percent['.$key.']');
            $item_data['item_discount_amount'] = $this->input->post('item_disc_amt['.$key.']');
            $item_data['total_amount'] = $this->input->post('item_total['.$key.']');
          }elseif($this->config->item('Client_Payment_client_payment_invoice_template')==5 || $this->config->item('Client_Payment_client_payment_invoice_template')==6  || $this->config->item('Client_Payment_client_payment_invoice_template')==7){
            $item_data['item_code'] = $this->input->post('item_code['.$key.']');
            $item_data['name'] = $this->input->post('item_name['.$key.']');
            $item_data['unit'] = $this->input->post('item_unit['.$key.']');
            $item_data['quantity'] = $this->input->post('item_qty['.$key.']');
            $item_data['price'] = $this->input->post('item_price['.$key.']');
            $item_data['item_discount_percent'] = $this->input->post('item_disc_percent['.$key.']');
            $item_data['item_discount_amount'] = $this->input->post('item_disc_amt['.$key.']');
            $item_data['item_taxable_amount'] = $this->input->post('item_taxable_amt['.$key.']');
            $item_data['item_tax_percent'] = $this->input->post('item_tax_percent['.$key.']');
            $item_data['item_tax_amount'] = $this->input->post('item_tax_amt['.$key.']');
            $item_data['total_amount'] = $this->input->post('item_total['.$key.']');
          }
          if ($this->config->item('Client_Invoice_work_order_connected') == 1){
            $item_data['work_order_item_id'] = $this->input->post('item_work_order_task['.$key.']');
          }
          if($this->input->post('item_id['.$key.']') && $this->input->post('item_id['.$key.']')!=''){
            // Update Existing Data
            $item_data['item_id'] = $this->input->post('item_id['.$key.']');
            $item_result =  $this->Invoices->update_invoice_items($item_data);
          }else{
            // Create New Data
            $item_result =  $this->Invoices->create_invoice_items($item_data);
          }
        }
      }

      // $items_array=$newArrayitems=array();
      // if($this->input->post('item')){
      //   $items_array = $this->input->post('item');
      // }
      // $items_array_length = sizeof($items_array);
      // // Convert to New Formatted Array
      // foreach (array_keys($items_array) as $fieldKey) {
      //   foreach ($items_array[$fieldKey] as $key=>$value) {
      //     $newArrayitems[$key][$fieldKey] = $value;
      //   }
      // }

      // foreach ($newArrayitems as $row) {
      //   $item_data=array();
      //   $item_data['invoice_id'] = $data['invoice_id'];
      //   $item_data['name'] = $row['item_name'];
      //   $item_data['unit'] = $row['item_unit'];
      //   $item_data['quantity'] = $row['item_qty'];
      //   $item_data['price'] = $row['item_price'];
      //   $item_data['total_amount'] = $row['item_total'];
      //   $item_data['created_date'] = date('Y-m-d H:i:s');
      //   $item_data['created_by'] = $this->session->userdata('user_id');
      //   if(isset($row['item_id']) && $row['item_id']!=''){
      //     // Update Existing Data
      //     $item_data['item_id'] = $row['item_id'];
      //     $item_result =  $this->Invoices->update_invoice_items($item_data);
      //   }else{
      //     // Create New Data
      //     $item_result =  $this->Invoices->create_invoice_items($item_data);
      //   }
      // }

      // Check Items Deleted
      $deleted_items = $this->security->xss_clean($this->input->post('deleted_items'));
      if($deleted_items!=''){
        $items = explode(',',$deleted_items);
        foreach ($items as $key => $value) {
          $item_data=array();
          $item_data['delete_status'] = 1;
          $item_data['item_id'] = $value;
          $this->Invoices->update_invoice_items($item_data);
        }
      }
      $this->bills_management->calculate_invoice_payment_total($data['invoice_id']);
      $flash_data['status'] = $result;
      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Invoice update Succesfully';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['invoice_id'] = $data['invoice_id'];
      if($invoice_type=='project_invoice'){
        $flash_data['work_id'] = $data['project_id'];
      }
    }
    else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }


    echo json_encode($flash_data);
  }
  public function delete()
  {
    //  Delete Received Amount
    $data2['invoice_id'] = $this->security->xss_clean($this->input->post('id_delete'));
    $data2['delete_status']=1;
    $result2 = $this->Invoices->update_invoice($data2);

    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Invoice Deleted Succesfully';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }

}
?>
