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

class Sales_quotation extends CI_Controller {

  public $page_data=array();

  function __construct()
  {
    parent::__construct();
    //Calling Initial Functions
    $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('Sales_quotation_model','Sales_quotation');
    $this->load->model('Work_order_model','Work_order');
    $this->load->model('Settings_model', 'Settings');
    $this->load->library('Accounts_management', 'accounts_management');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Enquiries_model','Enquiries');
    $this->load->library('Projects_management','projects_management');

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

    $this->page_data['step'] = $step;
    $this->page_data['quotation_id'] = $quotation_id;
    $this->page_data['measure_units'] = $this->Material->select_unit()->result();
    $this->page_data['terms_and_condition_templates'] = $this->Settings->select_terms_and_condition_templates('',array("terms_type"=>'Sales Quotation'))->result();
    $this->page_data['sales_quotation_templates'] = $this->Sales_quotation->select_quotation_templates()->result();
    $this->page_data['selected_template_id'] = $this->page_data['selected_template_data'] = '';
    if(isset($_POST['template_id']) && $_POST['template_id']!=''){
      $this->page_data['selected_template_id'] = implode(',', $this->input->post('template_id'));
      $this->db->where('template_id IN ('.$this->page_data['selected_template_id'].')');
      $this->page_data['selected_template_data'] = $this->Sales_quotation->select_quotation_templates("*",);
      if($this->page_data['selected_template_data']->num_rows()>=1){
        $this->page_data['selected_template_data'] = $this->page_data['selected_template_data']->result();
      }
    }
    if(isset($_GET['clone']) && $_GET['clone']!=''){
      $this->page_data['clone_quotation_data'] = $this->Sales_quotation->select_quotations("*,u1.user_alias as prepared_by_name,u1.phone_no as prepared_by_phone", array("quotation_id"=>$_GET['clone']));
      if($this->page_data['clone_quotation_data']->num_rows()==1){
        $this->page_data['clone_quotation_data'] = $this->page_data['clone_quotation_data']->row();
        $this->page_data['clone_items_data'] = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$this->page_data['clone_quotation_data']->quotation_id))->result();
      }
    }
    $this->page_data['enquiry_data'] = array();
    if(isset($_GET['enquiry_id']) && $_GET['enquiry_id']!=''){
      $this->page_data['enquiry_data'] = $this->Enquiries->select_enquiries("*,u1.user_alias as assigned_user", array("enquiry_id"=>$_GET['enquiry_id']));
      if($this->page_data['enquiry_data']->num_rows()==1){
        $this->page_data['enquiry_data'] = $this->page_data['enquiry_data']->row();
      }
    }

    // sale_staff type user from users table
    // $sales_staff_where['user_role'] = 25;
    $sales_staff_where = array();
    $this->page_data['sales_staffs'] = $this->User->select_user("*",$sales_staff_where)->result();
    if($quotation_id!=''){
      $data['sq.quotation_id'] = $quotation_id;
      $this->page_data['quotation_data'] = $this->Sales_quotation->select_quotations("*,u1.user_alias as prepared_by_name,u1.phone_no as prepared_by_phone", $data);
      if($this->page_data['quotation_data']->num_rows()==1){
        $this->page_data['quotation_data'] = $this->page_data['quotation_data']->row();
        if($this->page_data['quotation_data']->enquiry_id!=0){
          $this->page_data['enquiry_data'] = $this->Enquiries->select_enquiries("*,u1.user_alias as assigned_user", array("enquiry_id"=>$this->page_data['quotation_data']->enquiry_id));
          if($this->page_data['enquiry_data']->num_rows()==1){
            $this->page_data['enquiry_data'] = $this->page_data['enquiry_data']->row();
          }
        }
      }
    }
    if($this->config->item('Quotation_template')==1){
      $this->page_data['page_name'] = 'sales_quotation_add_'.$this->config->item('Quotation_template')."_step_".$step;
    }else{
      $this->page_data['page_name'] = 'sales_quotation_add_'.$this->config->item('Quotation_template');
    }

    $this->load->view('Index',$this->page_data);
  }
  public function view()
  {
    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","sales_manager","general_manager","supervisor","sales_staff","accounts_manager","operation_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }

    $this->page_data['page_name'] = 'sales_quotation_view';
    $this->load->view('Index',$this->page_data);
  }
  public function templates()
  {
    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","sales_manager","general_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    if ($this->session->userdata('branch_id') == 0) {
      $this->page_data['page_name'] = 'sales_quotation_templates';
      $this->load->view('Index',$this->page_data);
    }else{
      show_404();
    }
  }

  public function profile($view_type='',$id='')
  {
    if($id!=""){
      if($this->config->item('user_data_access_view_all')!=1){
        $data['sq.created_by'] = $this->session->userdata('user_id');
      }
      if($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_client_payment_view_all')==0){
        $data['sq.created_by'] = $this->session->userdata('user_id');
      }
      $data['sq.quotation_id'] = $id;
      $this->page_data['quotation_data'] = $this->Sales_quotation->select_quotations("sq.*,u1.user_alias as prepared_by_name,u1.phone_no as prepared_by_phone,c.customer_name as c_customer_name,c.customer_phone as c_customer_phone,c.customer_location,c.contact_person,b.*,tsc.state_name,tt.tax_percentage", $data);
      if($this->page_data['quotation_data']->num_rows()==1){
        $this->page_data['quotation_data'] = $this->page_data['quotation_data']->row();
        if($this->page_data['quotation_data']->branch_id==0){
          $default_branch_data = $this->config->item('default_branch_data');
          $this->page_data['quotation_data']->branch_name = $default_branch_data['branch_name'];
          $this->page_data['quotation_data']->quotation_prefix = $default_branch_data['quotation_prefix'];
          $this->page_data['quotation_data']->quotation_header = $default_branch_data['quotation_header'];
          $this->page_data['quotation_data']->quotation_footer = $default_branch_data['quotation_footer'];
        }
        $this->page_data['quotation_data']->receivable_amount_in_words = $this->accounts_management->amount_in_words($this->page_data['quotation_data']->quotation_net_total);
        $this->page_data['work_types'] = array();
        if($this->page_data['quotation_data']->work_types!=''){
          $work_types = explode(",",$this->page_data['quotation_data']->work_types);
          foreach ($work_types as $key => $value) {
            $this->page_data['work_types'][$key]['type_id'] = $value;
            $this->page_data['work_types'][$key]['type_name'] = $this->Work->select_work_types("",array("type_id"=>$value))->row()->type_name;
            $this->page_data['work_types'][$key]['items'] = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$this->page_data['quotation_data']->quotation_id,'sqi.work_type_id'=>$value,'sqi.item_type'=>'task'))->result();
            $this->page_data['work_types'][$key]['descriptions'] = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$this->page_data['quotation_data']->quotation_id,'sqi.work_type_id'=>$value,'sqi.item_type'=>'description'))->result();
          }
        }
        $this->page_data['items_data'] = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$this->page_data['quotation_data']->quotation_id))->result();

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

        if($view_type=='print'){
          $this->load->view('modules/sales_quotation/sales_quotation_print_'.$this->config->item('Quotation_template'), $this->page_data);
        }else{
          $this->page_data['page_name'] = 'sales_quotation_profile_'.$this->config->item('Quotation_template');
          $this->load->view('Index', $this->page_data);
        }
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function edit($id='')
  {
    // sale_staff type user from users table
    // $sales_staff_where['user_role'] = 25;
    $sales_staff_where = array();
    $this->page_data['sales_staffs'] = $this->User->select_user("*",$sales_staff_where)->result();

    if($id!=""){
      if($this->config->item('user_data_access_view_all')!=1){
        $data['sq.created_by'] = $this->session->userdata('user_id');
      }
      if($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_client_payment_view_all')==0){
        $data['sq.created_by'] = $this->session->userdata('user_id');
      }
      $data['sq.quotation_id'] = $id;
      $this->page_data['quotation_data'] = $this->Sales_quotation->select_quotations("*,u1.user_alias as prepared_by_name,u1.phone_no as prepared_by_phone", $data);
      if($this->page_data['quotation_data']->num_rows()==1 && $this->config->item('Quotation_template')==1){
        $this->page_data['quotation_data'] = $this->page_data['quotation_data']->row();
        if(($this->page_data['quotation_data']->approval_status!=0 && $this->session->userdata('user_role')=='admin') || $this->page_data['quotation_data']->approval_status==0){
          if($this->page_data['quotation_data']->branch_id==0){
            $default_branch_data = $this->config->item('default_branch_data');
            $this->page_data['quotation_data']->branch_name = $default_branch_data['branch_name'];
            $this->page_data['quotation_data']->quotation_prefix = $default_branch_data['quotation_prefix'];
            $this->page_data['quotation_data']->quotation_header = $default_branch_data['quotation_header'];
            $this->page_data['quotation_data']->quotation_footer = $default_branch_data['quotation_footer'];
          }
          $this->page_data['quotation_data']->receivable_amount_in_words = $this->accounts_management->amount_in_words($this->page_data['quotation_data']->quotation_net_total);
          $this->page_data['items_data'] = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$this->page_data['quotation_data']->quotation_id))->result();
          $this->page_data['enquiry_data'] = array();
          if($this->page_data['quotation_data']->enquiry_id!=0){
            $this->page_data['enquiry_data'] = $this->Enquiries->select_enquiries("*,u1.user_alias as assigned_user", array("enquiry_id"=>$this->page_data['quotation_data']->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['page_name'] = 'sales_quotation_edit_'.$this->config->item('Quotation_template');
          $this->load->view('Index', $this->page_data);
        }else{
          $flash_data['status'] = 2;
          $flash_data['flashdata_msg'] = 'Sorry.. '.$this->config->item('Quotation_sales_quotation_title').' is Approved/Rejected!';
          $flash_data['flashdata_type'] = 'warning';
          $flash_data['alert_type'] = 'warning';
          $flash_data['flashdata_title'] = 'Approved/Rejected !!';

          $this->session->set_flashdata($flash_data);
          redirect(base_url() . 'sales_quotation', 'refresh');
        }
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function preview_template($id='')
  {
    if($id!=""){
      $this->page_data['quotation_template_data'] = $this->Sales_quotation->select_quotation_templates("*", array("template_id" => $id));
      if($this->page_data['quotation_template_data']->num_rows()==1){
        $this->page_data['quotation_template_data'] = $this->page_data['quotation_template_data']->row();

        $this->load->view('modules/sales_quotation/sales_quotation_template_preview', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function create()
  {
    $data['date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('quotation_date'))));
    $data['customer_id'] = $this->security->xss_clean($this->input->post('customer'));
    if($this->input->post('enquiry_id')){
      $data['enquiry_id'] = $this->security->xss_clean($this->input->post('enquiry_id'));
    }
    // $data['customer_phone'] = $this->security->xss_clean($this->input->post('customer_phone'));
    // $data['customer_address'] = $this->security->xss_clean($this->input->post('address'));
    // $data['state'] = $this->security->xss_clean($this->input->post('state'));
    if($this->input->post('expiry_date') && $this->input->post('expiry_date')!=''){
      $data['expiry_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('expiry_date'))));
    }
    if($this->input->post('prepared_by')){
      $data['prepared_by'] = $this->security->xss_clean($this->input->post('prepared_by'));
    }
    $data['reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    $data['project_name'] = $this->security->xss_clean($this->input->post('project_name'));
    if($this->input->post('quotation_type')){
      $data['quotation_type'] = $this->security->xss_clean($this->input->post('quotation_type'));
    }
    if($this->config->item('Quotation_template')==1){
      $data['quotation_subject'] = $this->security->xss_clean($this->input->post('subject'));
      $data['quotation_description'] = $this->security->xss_clean($this->input->post('quotation_description'));
      $data['quotation_notes'] = $this->security->xss_clean($this->input->post('notes'));
      if($this->input->post('grand_total_amount')){
        $data['quotation_total_amount'] = $this->security->xss_clean($this->input->post('grand_total_amount'));
      }
      if($this->input->post('discount_amount')){
        $data['quotation_discount_amount'] = $this->security->xss_clean($this->input->post('discount_amount'));
      }
      if($this->input->post('tax_percent')){
        $data['quotation_tax_percent'] = $this->security->xss_clean($this->input->post('tax_percent'));
        $data['quotation_tax_amount'] = $this->security->xss_clean($this->input->post('total_tax_amount'));
      }
      if($this->input->post('net_total_amount')){
        $data['quotation_net_total'] = $this->security->xss_clean($this->input->post('net_total_amount'));
      }
      if($this->config->item('Quotation_quotation_no_suffix')=='/d/m/Y'){
        $data['quotation_no_suffix'] = "/".date('d/m/Y',strtotime($this->security->xss_clean($this->input->post('quotation_date'))));
      }
      if($this->config->item('Quotation_quotation_no_suffix')=='/y'){
        $data['quotation_no_suffix'] = "/".date('y',strtotime($this->security->xss_clean($this->input->post('quotation_date'))));
      }
      if($this->config->item('quotation_prefix')!=''){
        $data['quotation_no_prefix'] = $this->config->item('quotation_prefix');
        if (strpos($data['quotation_no_prefix'], 'y') !== false) {
          $year = date('y',strtotime($data['date']));
          $data['quotation_no_prefix'] = str_replace('y', $year, $data['quotation_no_prefix']);
        }
      }
    }
    $data['created_date'] = $item_data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $item_data['created_by'] = $this->session->userdata('user_id');
    if($this->config->item('Quotation_sales_quotation_no_manual')==1){
      $data['quotation_no_suffix'] = $this->security->xss_clean($this->input->post('quotation_no'));
      $count = $this->Sales_quotation->select_quotations("quotation_no_suffix",array("sq.quotation_no_suffix"=>$data['quotation_no_suffix']))->num_rows();
    }else{
      $count = 0;
      // Generate Quotation No
      $quotation_where = array();
      if($this->config->item('Quotation_quotation_no_based_on')=='year'){
        $quotation_where['sq.date >='] = date('Y',strtotime($data['date'])).'-01-01';
        $quotation_where['sq.date <='] = date('Y',strtotime($data['date'])).'-12-31';
      }
      $last_data = $this->Sales_quotation->select_quotations("max(sq.quotation_no) as max_quotation_no",$quotation_where);
      if($last_data->num_rows()==1){
        $data['quotation_no'] = ($last_data->row()->max_quotation_no)+1;
      }else{
        $data['quotation_no'] = 1;
      }
    }


    //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) {
      if(isset($row['title'])){
        $terms_new[$i]['title'] = $row['title'];
      }
      $terms_new[$i]['description'] = $row['description'];
      $i++;
    }
    if(sizeof($newArrayterms)){
      $data['terms_and_conditions'] = serialize($terms_new);
    }
    if($count==0){
      $result = $this->Sales_quotation->insert_quotation($data);

      $flash_data['status'] = $result['status'];
      if ($flash_data['status'] == 1) {
        if($this->input->post('enquiry_id')){
          $enquiry_update_data['enquiry_id'] = $this->input->post('enquiry_id');
          $enquiry_update_data['enquiry_status'] = 'Quotation Created';
          $enquiry_result = $this->Enquiries->update_enquiry($enquiry_update_data);
        }
        // Insert Items
        $item_data['quotation_id'] = $result['insert_id'];
        if($this->config->item('Quotation_template')==2){
          $selected_template_id = explode(',',$this->input->post('template_id'));
          foreach ($selected_template_id as $key => $value) {
            $item_data['template_id'] = $value;
            $item_data['title'] = $this->security->xss_clean($this->input->post('title_'.$value));
            $item_data['sub_title'] = $this->security->xss_clean($this->input->post('subtitle_'.$value));
            $item_data['description'] = $this->security->xss_clean($this->input->post('description_'.$value));
            $item_data['products'] = $this->security->xss_clean($this->input->post('products_'.$value));
            $item_data['unit_price'] = $this->security->xss_clean($this->input->post('amount_'.$value));
            $item_data['warranty'] = $this->security->xss_clean($this->input->post('warranty_'.$value));
            $item_data['method_of_application'] = $this->security->xss_clean($this->input->post('methods_'.$value));
            $item_data['quantity'] = $this->security->xss_clean($this->input->post('quantity_'.$value));
            $item_data['total_amount'] = $this->security->xss_clean($this->input->post('total_amount_'.$value));
            $item_data['notes'] = $this->security->xss_clean($this->input->post('notes_'.$value));
            $item_result = $this->Sales_quotation->insert_quotation_item($item_data);
          }
        }else{
          // Insert Items
          $row_count = $this->input->post('current_row_count');
          if($row_count > 0){
            for ($i=0; $i < $row_count ; $i++)
            {
              if($this->input->post('item_qty['.$i.']')){
                $item_data['description'] = $this->input->post('item_description['.$i.']');
                $item_data['unit'] = $this->input->post('item_unit['.$i.']');
                $item_data['quantity'] = $this->input->post('item_qty['.$i.']');
                $item_data['unit_price'] = $this->input->post('item_unit_price['.$i.']');
                $item_data['total_amount'] = $this->input->post('item_total['.$i.']');
                $result_items = $this->Sales_quotation->insert_quotation_item($item_data);
              }
            }
          }
        }

        if($this->config->item('Quotation_template')==1 && $this->input->post('step')==1){
          $flash_data['flashdata_msg'] = $this->config->item('Quotation_sales_quotation_title').' Created. Please Proceed to Add Items.';
        }else{
          $flash_data['flashdata_msg'] = $this->config->item('Quotation_sales_quotation_title').' Added Successfully!.';
        }
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
        $flash_data['quotation_id'] = $result['insert_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 !!';
      }
    }else{
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. Quotation No Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }

    echo(json_encode($flash_data));
  }
  public function update()
  {
    $data['quotation_id'] = $this->security->xss_clean($this->input->post('quotation_id'));
    $data['date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('quotation_date'))));
    $data['customer_id'] = $this->security->xss_clean($this->input->post('customer'));
    if($this->input->post('expiry_date') && $this->input->post('expiry_date')!=''){
      $data['expiry_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('expiry_date'))));
    }else{
      $data['expiry_date'] = '0000-00-00';
    }
    $data['reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    $data['project_name'] = $this->security->xss_clean($this->input->post('project_name'));
    if($this->input->post('prepared_by')){
      $data['prepared_by'] = $this->security->xss_clean($this->input->post('prepared_by'));
    }
    if($this->input->post('quotation_type')){
      $data['quotation_type'] = $this->security->xss_clean($this->input->post('quotation_type'));
    }
    if($this->config->item('Quotation_template')==1){
      $data['quotation_subject'] = $this->security->xss_clean($this->input->post('subject'));
      $data['quotation_description'] = $this->security->xss_clean($this->input->post('quotation_description'));
      $data['quotation_notes'] = $this->security->xss_clean($this->input->post('notes'));
      // $data['quotation_total_amount'] = $this->security->xss_clean($this->input->post('grand_total_amount'));
      // $data['quotation_discount_amount'] = $this->security->xss_clean($this->input->post('discount_amount'));
      // $data['quotation_tax_percent'] = $this->security->xss_clean($this->input->post('tax_percent'));
      // $data['quotation_tax_amount'] = $this->security->xss_clean($this->input->post('total_tax_amount'));
      // $data['quotation_net_total'] = $this->security->xss_clean($this->input->post('net_total_amount'));
      if($this->config->item('Quotation_quotation_no_suffix')=='/d/m/Y'){
        $data['quotation_no_suffix'] = "/".date('d/m/Y',strtotime($this->security->xss_clean($this->input->post('quotation_date'))));
      }
      if($this->config->item('Quotation_quotation_no_suffix')=='/y'){
        $data['quotation_no_suffix'] = "/".date('y',strtotime($this->security->xss_clean($this->input->post('quotation_date'))));
      }
    }
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['updated_by']  = $this->session->userdata('user_id');

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

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

    $result = $this->Sales_quotation->update_quotation($data);

    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {

      if($this->config->item('Quotation_template')==2){
        $selected_template_id = explode(',',$this->input->post('template_id'));
        foreach ($selected_template_id as $key => $value) {
          $item_data=array();
          $item_data['template_id'] = $value;
          $item_data['title'] = $this->security->xss_clean($this->input->post('title_'.$value));
          $item_data['sub_title'] = $this->security->xss_clean($this->input->post('subtitle_'.$value));
          $item_data['description'] = $this->security->xss_clean($this->input->post('description_'.$value));
          $item_data['products'] = $this->security->xss_clean($this->input->post('products_'.$value));
          $item_data['unit_price'] = $this->security->xss_clean($this->input->post('amount_'.$value));
          $item_data['warranty'] = $this->security->xss_clean($this->input->post('warranty_'.$value));
          $item_data['method_of_application'] = $this->security->xss_clean($this->input->post('methods_'.$value));
          $item_data['quantity'] = $this->security->xss_clean($this->input->post('quantity_'.$value));
          $item_data['total_amount'] = $this->security->xss_clean($this->input->post('total_amount_'.$value));
          $item_data['notes'] = $this->security->xss_clean($this->input->post('notes_'.$value));
          if($this->input->post('item_id['.$i.']') && $this->input->post('item_id['.$i.']')!=''){
            // Update Existing Data
            $item_data['item_id'] = $this->input->post('item_id['.$i.']');
            $item_result =  $this->Sales_quotation->update_quotation_item($item_data);
          }else{
            // Create New Data
            $item_data['quotation_id'] =  $data['quotation_id'];
            $item_result =  $this->Sales_quotation->insert_quotation_item($item_data);
          }
        }
      }else{
        // Insert Items
        $row_count = $this->input->post('current_row_count');
        if($row_count > 0){
          for ($i=0; $i < $row_count ; $i++)
          {
            // $item_data=array();
            // $item_data['description'] = $this->input->post('item_description['.$i.']');
            // $item_data['unit'] = $this->input->post('item_unit['.$i.']');
            // $item_data['quantity'] = $this->input->post('item_qty['.$i.']');
            // $item_data['unit_price'] = $this->input->post('item_unit_price['.$i.']');
            // $item_data['total_amount'] = $this->input->post('item_total['.$i.']');
            // if($this->input->post('item_id['.$i.']') && $this->input->post('item_id['.$i.']')!=''){
            //   // Update Existing Data
            //   $item_data['item_id'] = $this->input->post('item_id['.$i.']');
            //   $item_result =  $this->Sales_quotation->update_quotation_item($item_data);
            // }else{
            //   // Create New Data
            //   $item_data['quotation_id'] =  $data['quotation_id'];
            //   $item_result =  $this->Sales_quotation->insert_quotation_item($item_data);
            // }
          }
        }
      }

      $flash_data['flashdata_msg'] = $this->config->item('Quotation_sales_quotation_title').' Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['quotation_id'] = $data['quotation_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_2()
  {
    $data['quotation_id'] = $this->security->xss_clean($this->input->post('quotation_id'));
    if($this->config->item('Quotation_template')==1){
      $data['quotation_total_amount'] = $this->security->xss_clean($this->input->post('grand_total_amount'));
      $data['quotation_discount_amount'] = $this->security->xss_clean($this->input->post('discount_amount'));
      $data['quotation_tax_percent'] = $this->security->xss_clean($this->input->post('tax_percent'));
      $data['quotation_tax_amount'] = $this->security->xss_clean($this->input->post('total_tax_amount'));
      $data['quotation_net_total'] = $this->security->xss_clean($this->input->post('net_total_amount'));
    }
    $result = $this->Sales_quotation->update_quotation($data);

    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = $this->config->item('Quotation_sales_quotation_title').' Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['quotation_id'] = $data['quotation_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 approve()
  {
    $data['quotation_id']=$this->security->xss_clean($this->input->post('quotation_id'));
    $data['approval_status']=$this->security->xss_clean($this->input->post('quotation_approval_status'));
    $data['approval_remarks']=$this->security->xss_clean($this->input->post('remarks'));
    $result = $this->Sales_quotation->update_quotation($data);

    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = $this->config->item('Quotation_sales_quotation_title').' Approval Status Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

      if($data['approval_status']==1 && $this->config->item('Quotation_project_creation_on_quotation_approval')==1){
        $this->projects_management->create_project('project_creation_on_quotation_approval',$data['quotation_id'],'sales_quotation');
      }
    }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 select_sales_quotation($type='')
  {
    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();
    if($this->config->item('user_data_access_view_all')!=1){
      $data['sq.created_by'] = $this->session->userdata('user_id');
    }
    if($this->session->userdata('user_role')=='general_manager' && $this->config->item('User_general_manager_client_payment_view_all')==0){
      $data['sq.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['sq.branch_id'] = $_POST['branch_id'];
    }
    if($this->session->userdata('branch_id') != 0){
      $data['sq.branch_id'] = $this->session->userdata('branch_id');
    }
    $result = $this->Sales_quotation->select_quotations("sq.*,u1.user_alias as prepared_by_name,u1.phone_no as prepared_by_phone,c.customer_name as c_customer_name,c.customer_phone as c_customer_phone,c.customer_location,c.contact_person,b.*,tsc.state_name,tt.tax_percentage,u.user_alias as created_user",$data);
    $result_array=$result->result();

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

    foreach($result_array as $row):

      $btn_copy = $btn_edit = $btn_delete = $btn_approve = '';
      if($row->approval_status==1){
        $approval_status='<span class="m-badge m-badge--success m-badge--wide">Quotation Approved</span>';
      }elseif($row->approval_status==2){
        $approval_status='<span class="m-badge m-badge--danger m-badge--wide">Quotation Rejected</span>';
      }else{
        $approval_status='<span class="m-badge m-badge--warning m-badge--wide">Approval Pending</span>';
        if($this->config->item('Quotation_template')==1){
          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"  href="' . base_url() . 'sales_quotation/edit/' . $row->quotation_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>';
          }
        }
      }
      $approval_status.='<br/>Remarks:'.$row->approval_remarks;
      if($this->config->item('Quotation_template')==1){
        $btn_copy = '<a style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'sales_quotation/add?clone=' . $row->quotation_id . '" class="btn btn-focus m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
        <i class="la la-copy"></i>
        </a>';
      }
      if($row->approval_status!=1){
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="quotation_delete_btn" href="#quotation_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>';
      }
      $show_quotation=1;
      $work_order = $this->Work_order->select_work_orders("*", array("wo.quotation_id"=>$row->quotation_id))->result();
      foreach ($work_order as $key => $value) {
        $approval_status.='<br/><a target="_blank" href="'.base_url().'work_order/profile/'.$value->order_id.'"><span class="m-badge m-badge--focus m-badge--wide">Work Order #BIW-'.$value->order_id.' Created</span></a>';
      }
      if($this->config->item('Quotation_hide_work_order_created')==1 && sizeof($work_order)>0){
        $show_quotation=0;
      }

      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')==$row->created_by){
        $btn_approve = '<a style="margin-left: 5px;margin-right: 5px"  id="btn_approve_quotation" href="#quotation_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>';
      }

      $item_details = '';
      $items = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",array("sqi.quotation_id"=>$row->quotation_id))->result();
      foreach ($items as $key => $value) {
        if($this->config->item('Quotation_template')==2){
          $item_details.= $value->title.'['.$value->template_no.'] - '.$value->quantity.' X '.$value->unit_price.' = '.$value->total_amount.'+GST<br/>';
        }else{
          $item_details.= $value->description.' - '.$value->quantity.' X '.$value->unit_price.' = '.$value->total_amount.'<br/>';
        }
      }
      if($row->branch_id==0){
        $default_branch_data = $this->config->item('default_branch_data');
        $row->branch_name = $default_branch_data['branch_name'];
        $row->quotation_prefix = $default_branch_data['quotation_prefix'];
      }
      if($row->quotation_no_prefix!=''){
        $row->quotation_prefix = $row->quotation_no_prefix;
      }
      $phone='';
      if($row->customer_id==0 && $row->customer_phone!=''){
        $phone="<br/>Phone: ".$row->customer_phone;
      }elseif($row->customer_id!=0 && $row->c_customer_phone!=''){
        $phone="<br/>Phone: ".$row->c_customer_phone;
      }

      if($this->config->item('Quotation_sales_quotation_no_manual')==1){
        $quotation_no = '<a  href="'.base_url().'sales_quotation/profile/view/'.$row->quotation_id.'" >'.$row->quotation_no_suffix.'</a>';
      }else{
        $row->quotation_no = sprintf("%04d", $row->quotation_no);
        $quotation_no = '<a  href="'.base_url().'sales_quotation/profile/view/'.$row->quotation_id.'" >#'.$row->quotation_prefix.$row->quotation_no.$row->quotation_no_suffix.'</a>';
      }
      if($row->enquiry_id!=0){
        $enquiry_data = $this->Enquiries->select_enquiries("*,u1.user_alias as assigned_user", array("enquiry_id"=>$row->enquiry_id))->row();
      }
      if($show_quotation==1){
        $array[$j][]=$j+1;
        $array[$j][]=$row->quotation_id;
        $array[$j][]=$quotation_no;
        $array[$j][]=$row->branch_name;
        $array[$j][]=$row->quotation_subject;
        if($row->customer_id==0){
          $array[$j][]=$row->customer_name;
          $array[$j][]=nl2br($row->customer_address).$phone;
          $array[$j][]='';
        }elseif($row->enquiry_id!=0 && isset($enquiry_data)){
          $array[$j][]=$row->c_customer_name;
          $array[$j][]=nl2br($row->customer_location);
          $array[$j][]=$enquiry_data->enq_contact_person."<br/>".$enquiry_data->enq_contact_person_mobile;
        }else{
          $array[$j][]=$row->c_customer_name."<br/>".$row->contact_person;
          $array[$j][]=nl2br($row->customer_location).$phone;
          $array[$j][]=$row->contact_person."<br/>".$phone;
        }
        $array[$j][]=date('d-m-Y',strtotime($row->date));
        if(is_numeric($row->prepared_by)){
          $array[$j][]=$row->prepared_by_name;
        }else{
          $array[$j][]=nl2br($row->prepared_by);
        }

        $array[$j][]=$item_details;
        $array[$j][]=$row->quotation_net_total;
        $array[$j][]=$approval_status;
        if ($this->config->item('UI_hide_created_date_field')==0){
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->created_date))."</li><li>Created By : ".$row->created_user."</li>";
        }else{
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->created_user.'</li>';
        }
        $array[$j][]=$btn_copy.$btn_edit.$btn_delete.$btn_approve;
        $array[$j][]=$row->approval_status;
        $array[$j][]=$row->approval_remarks;

        $j++;
      }
    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_quotation_details(){
    $data = array();
    if(isset($_POST['quotation_id']) && $_POST['quotation_id']!=""){
      $data['sq.quotation_id'] = $_POST['quotation_id'];
    }
    $result	= $this->Sales_quotation->select_quotations("sq.*",$data);
    if($result->num_rows()==1) {
      $result = $result->row();
      $result->items = $this->Sales_quotation->select_quotation_items("sqi.*",array("sqi.quotation_id"=>$result->quotation_id))->result();
      echo json_encode(array("count" => 1,"data" => $result));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function create_template()
  {
    $data['template_no']=$template_where['sqt.template_no']=$this->security->xss_clean($this->input->post('template_no'));
    $count = $this->Sales_quotation->select_quotation_templates("*",$template_where)->num_rows();
    if($count == 0) {
      $data['title'] = $this->security->xss_clean($this->input->post('title'));
      $data['sub_title'] = $this->security->xss_clean($this->input->post('subtitle'));
      $data['description'] = $this->security->xss_clean($this->input->post('description'));
      $data['products'] = $this->security->xss_clean($this->input->post('products'));
      $data['unit_price'] = $this->security->xss_clean($this->input->post('amount'));
      $data['warranty'] = $this->security->xss_clean($this->input->post('warranty'));
      $data['method_of_application'] = $this->security->xss_clean($this->input->post('methods'));
      $data['notes'] = $this->security->xss_clean($this->input->post('notes'));
      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->session->userdata('user_id');
      $result = $this->Sales_quotation->insert_quotation_templates($data);

      $flash_data['status'] = $result['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Quotation Template Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }

    }else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. Quotation Template With Same Template No Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    echo(json_encode($flash_data));

  }
  public function update_template()
  {
    $data['template_id']=$template_where['sqt.template_id !=']=$this->security->xss_clean($this->input->post('template_id'));
    $data['template_no']=$template_where['sqt.template_no']=$this->security->xss_clean($this->input->post('template_no'));
    $count = $this->Sales_quotation->select_quotation_templates("*",$template_where)->num_rows();
    if($count == 0) {
      $data['title'] = $this->security->xss_clean($this->input->post('title'));
      $data['sub_title'] = $this->security->xss_clean($this->input->post('subtitle'));
      $data['description'] = $this->security->xss_clean($this->input->post('description'));
      $data['products'] = $this->security->xss_clean($this->input->post('products'));
      $data['unit_price'] = $this->security->xss_clean($this->input->post('amount'));
      $data['warranty'] = $this->security->xss_clean($this->input->post('warranty'));
      $data['method_of_application'] = $this->security->xss_clean($this->input->post('methods'));
      $data['notes'] = $this->security->xss_clean($this->input->post('notes'));
      $result = $this->Sales_quotation->update_quotation_templates($data);

      $flash_data['status'] = $result;
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Quotation Template Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }

    }else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. Quotation Template With Same Template No Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    echo(json_encode($flash_data));

  }
  public function delete_template()
  {

    $data['template_id']=$this->security->xss_clean($this->input->post('template_id'));
    $data['delete_status']=1;
    $result = $this->Sales_quotation->update_quotation_templates($data);

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

    echo(json_encode($flash_data));
  }
  public function select_templates($type='')
  {
    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();

    $result = $this->Sales_quotation->select_quotation_templates("sqt.*,u.user_alias",$data);
    $result_array=$result->result();

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

    foreach($result_array as $row):

      $btn_edit = $btn_delete = '';

      if($this->session->userdata('user_role')!='auditor') {
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="quotation_template_edit_btn" href="#quotation_template_edit_modal" data-toggle="modal" 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="quotation_template_delete_btn" href="#quotation_template_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>';
      }

      $array[$j][]=$j+1;
      $array[$j][]=$row->template_id;
      $array[$j][]='<a id="btn_view_template" data-template-id="'.$row->template_id.'" href="javascript:;" >'.$row->template_no.'</a>';
      $array[$j][]=$row->title;
      $array[$j][]=$row->sub_title;
      $array[$j][]=$row->description;
      $array[$j][]=$row->products;
      $array[$j][]=$row->unit_price;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->created_date))."</li><li>Created By : ".$row->user_alias."</li>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][]=$row->template_no;
      $array[$j][]=$row->warranty;
      $array[$j][]=$row->method_of_application;
      $array[$j][]=$row->notes;

      $j++;
    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function delete()
  {
    $data['quotation_id']=$this->security->xss_clean($this->input->post('quotation_id'));
    $data['delete_status']=1;
    $result = $this->Sales_quotation->update_quotation($data);
    $flash_data['status'] = $result;
    if ($result == 1 ) {
      $flash_data['flashdata_msg'] = $this->config->item('Quotation_sales_quotation_title').' Deleted Successfully!';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !!';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo(json_encode($flash_data));
  }

  public function create_item()
  {
    $item_data['quotation_id'] = $this->input->post('quotation_id');
    $item_data['description'] = $this->input->post('item_description');
    $item_data['item_type'] = $this->input->post('item_type');
    if($this->input->post('work_type_id')){
      $item_data['work_type_id'] = $this->input->post('work_type_id');
    }
    if($item_data['item_type']=='task'){
      $item_data['unit'] = $this->input->post('item_unit');
      $item_data['quantity'] = $this->input->post('item_qty');
      $item_data['unit_price'] = $this->input->post('item_unit_price');
      if($this->config->item('Quotation_rate_type')=='supply_installation'){
        $item_data['unit_price_2'] = $this->input->post('item_unit_price_2');
      }
      $item_data['total_amount'] = $this->input->post('item_total');
    }
    $result = $this->Sales_quotation->insert_quotation_item($item_data);
    $flash_data['status'] = $result['status'];
    if($flash_data['status'] == 1){
      $flash_data['flashdata_msg'] = 'Item Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else{
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $this->session->set_flashdata($flash_data);
    redirect($this->input->post('redirect_url'),'refresh');
    // echo(json_encode($flash_data));
  }
  public function update_item()
  {
    $item_data['item_id'] = $this->input->post('item_id');
    $item_data['description'] = $this->input->post('item_description');
    $item_data['work_type_id'] = $this->input->post('work_type_id');
    $item_data['item_type'] = $this->input->post('item_type_edit');
    if($item_data['item_type']=='task'){
      $item_data['unit'] = $this->input->post('item_unit');
      $item_data['quantity'] = $this->input->post('item_qty');
      $item_data['unit_price'] = $this->input->post('item_unit_price');
      if($this->config->item('Quotation_rate_type')=='supply_installation'){
        $item_data['unit_price_2'] = $this->input->post('item_unit_price_2');
      }
      $item_data['total_amount'] = $this->input->post('item_total');
    }
    $result = $this->Sales_quotation->update_quotation_item($item_data);
    $flash_data['status'] = $result;
    if($flash_data['status'] == 1){
      $flash_data['flashdata_msg'] = 'Item Details Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else{
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $this->session->set_flashdata($flash_data);
    redirect($this->input->post('redirect_url'),'refresh');
    // echo(json_encode($flash_data));
  }
  public function create_work_type()
  {
    $quotation_id = $this->input->post('quotation_id');
    $work_type = $this->input->post('work_type');
    $data['sq.quotation_id'] = $quotation_id;
    $quotation_data = $this->Sales_quotation->select_quotations("", array("sq.quotation_id"=>$quotation_id));
    if($quotation_data->num_rows()==1){
      $quotation_data = $quotation_data->row();
      $work_types_array = array();
      if($quotation_data->work_types!=''){
        $work_types_array = explode(',',$quotation_data->work_types);
        if (!in_array($work_type,$work_types_array)){
          array_push($work_types_array,$work_type);
        }
      }else{
        $work_types_array[] = $work_type;
      }
      $update_data['quotation_id'] = $quotation_id;
      $update_data['work_types'] = implode(',',$work_types_array);
      $result = $this->Sales_quotation->update_quotation($update_data);
      $flash_data['status'] = $result;
      if($result == 1){
        $flash_data['flashdata_msg'] = 'Work Type Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }else{
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $this->session->set_flashdata($flash_data);
    redirect($this->input->post('redirect_url'),'refresh');
    // echo(json_encode($flash_data));
  }
  public function select_quotation_items() {
    $item_table_body ='';
    $data['sq.quotation_id'] = $this->input->post('quotation_id');
    $quotation_data = $this->Sales_quotation->select_quotations("", $data);
    if($quotation_data->num_rows()==1){
      $quotation_data = $quotation_data->row();
      $work_types_array = array();
      if($quotation_data->work_types!=''){
        $work_types_array = explode(',',$quotation_data->work_types);
        $item_no = 1;
        foreach ($work_types_array as $key => $value) {
          $item_subno = 1;
          $work_type_name = $this->Work->select_work_types("",array("type_id"=>$value))->row()->type_name;
          $item_table_body.='<tr>'.
          '<td><strong>'.$item_no.'</strong></td>'.
          '<td colspan="5"><strong>'.$work_type_name.'</strong></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td style="display: none"></td>'.
          '<td></td>'.
          '<td style="display: none"></td>'.
          '<td  class="delete_column"><a style="margin-left: 5px;margin-right: 5px" id="btn_work_type_delete" data-work-type-id="'.$value.'" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#quotation_work_type_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a></td>'.
          '<td></td>'.
          '<td></td>'.
          '<td></td>'.
          '<td></td>'.
          '<td></td>'.
          '</tr>';
          // Get Items
          $items_where["sqi.quotation_id"] = $data['sq.quotation_id'];
          $items_where["sqi.work_type_id"] = $value;
          $items_where["sqi.item_type"] = 'description';
          $items = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",$items_where)->result();
          foreach ($items as $key2 => $value2) {
            $item_table_body.='<tr>'.
            '<td></td>'.
            '<td>'.$value2->description.'</td>'.
            '<td></td>'.
            '<td></td>'.
            '<td></td>'.
            '<td></td>'.
            '<td></td>'.
            '<td class="delete_column">'.
            '<a style="margin-left: 5px;margin-right: 5px" id="btn_quotation_item_edit" data-item-id="'.$value2->item_id .'" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#item_edit_modal" data-toggle="modal"><i class="la la-edit"></i></a>'.
            '<a style="margin-left: 5px;margin-right: 5px" id="btn_quotation_item_delete" data-item-id="'.$value2->item_id .'" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#quotation_item_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a></td>'.
            '<td><input type="text" class="item_total_amount" value="'.$value2->total_amount.'"></td>'.
            '<td></td>'.
            '<td>'.$value2->work_type_id.'</td>'.
            '<td>'.$value2->description.'</td>'.
            '<td>'.$value2->item_type.'</td>'.
            '</tr>';
            // $item_subno++;
          }

          $items_where["sqi.quotation_id"] = $data['sq.quotation_id'];
          $items_where["sqi.work_type_id"] = $value;
          $items_where["sqi.item_type"] = 'task';
          $items = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",$items_where)->result();
          foreach ($items as $key2 => $value2) {
            $item_table_body.='<tr>'.
            '<td><strong>'.$item_no.'.'.$item_subno.'</strong></td>'.
            '<td>'.$value2->description.'</td>'.
            '<td>'.$value2->quantity.'</td>'.
            '<td>'.$value2->unit_name.'</td>'.
            '<td>'.$value2->unit_price.'</td>'.
            '<td>'.$value2->unit_price_2.'</td>'.
            '<td>'.$value2->total_amount.'</td>'.
            '<td class="delete_column">'.
            '<a style="margin-left: 5px;margin-right: 5px" id="btn_quotation_item_edit" data-item-id="'.$value2->item_id .'" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#item_edit_modal" data-toggle="modal"><i class="la la-edit"></i></a>'.
            '<a style="margin-left: 5px;margin-right: 5px" id="btn_quotation_item_delete" data-item-id="'.$value2->item_id .'" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#quotation_item_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a></td>'.
            '<td><input type="text" class="item_total_amount" value="'.$value2->total_amount.'"></td>'.
            '<td>'.$value2->unit.'</td>'.
            '<td>'.$value2->work_type_id.'</td>'.
            '<td>'.$value2->description.'</td>'.
            '<td>'.$value2->item_type.'</td>'.
            '</tr>';
            $item_subno++;
          }
          $item_no++;
        }
        echo json_encode(array("items_count"=>$item_no,"content"=>$item_table_body));
      }else{
        $items_where["sqi.quotation_id"] = $data['sq.quotation_id'];
        $items = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",$items_where)->result();
        $item_no=1;
        foreach ($items as $key2 => $value2) {
          $item_table_body.='<tr>'.
          '<td><strong>'.$item_no.'</strong></td>'.
          '<td>'.$value2->description.'</td>'.
          '<td>'.$value2->quantity.'</td>'.
          '<td>'.$value2->unit_name.'</td>'.
          '<td>'.$value2->unit_price.'</td>'.
          '<td>'.$value2->total_amount.'</td>'.
          '<td class="delete_column">'.
          '<a style="margin-left: 5px;margin-right: 5px" id="btn_quotation_item_edit" data-item-id="'.$value2->item_id .'" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#item_edit_modal" data-toggle="modal"><i class="la la-edit"></i></a>'.
          '<a style="margin-left: 5px;margin-right: 5px" id="btn_quotation_item_delete" data-item-id="'.$value2->item_id .'" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air"  href="#quotation_item_delete_modal" data-toggle="modal"><i class="la la-trash"></i></a></td>'.
          '<td><input type="text" class="item_total_amount" value="'.$value2->total_amount.'"></td>'.
          '<td>'.$value2->unit.'</td>'.
          '<td>'.$value2->work_type_id.'</td>'.
          '<td>'.$value2->description.'</td>'.
          '<td>'.$value2->item_type.'</td>'.
          '</tr>';
          $item_no++;
        }
        echo json_encode(array("items_count"=>$item_no,"content"=>$item_table_body));
      }
    }else{
      echo json_encode(array("items_count"=>0));
    }
  }
  public function select_quotation_work_types() {
    $data['sq.quotation_id'] = $this->input->post('quotation_id');
    $quotation_data = $this->Sales_quotation->select_quotations("", $data);
    if($quotation_data->num_rows()==1){
      $quotation_data = $quotation_data->row();
      $work_types_array = array();
      if($quotation_data->work_types!=''){
        $work_types_array = explode(',',$quotation_data->work_types);
        $id = array();
        foreach ($work_types_array as $key => $value) {
          $work_type_name = $this->Work->select_work_types("",array("type_id"=>$value))->row()->type_name;
          $id[] = $value;
          $name[] = $work_type_name;
        }
        echo json_encode(array("count" => sizeof($id),"id" => $id,"name" => $name));
      }else{
        echo json_encode(array("count" => 0));
      }
    }else{
      echo json_encode(array("count" => 0));
    }
  }
  public function delete_quotation_item()
  {
    $data['item_id'] = $this->input->post('item_id');
    $data['delete_status'] = 1;

    $result = $this->Sales_quotation->update_quotation_item($data);
    $flash_data['status'] = $result;
    if($result == 1){
      $flash_data['flashdata_msg'] = 'Item Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    }else{
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $this->session->set_flashdata($flash_data);
    redirect($this->input->post('redirect_url'),'refresh');
    // echo(json_encode($flash_data));
  }
  public function delete_work_type()
  {
    $data['quotation_id'] = $this->input->post('quotation_id');
    $work_type_id = $this->input->post('work_type_id');
    $quotation_data = $this->Sales_quotation->select_quotations("", $data);
    if($quotation_data->num_rows()==1){
      $quotation_data = $quotation_data->row();
      // Check Items Exist
      $items_where["sqi.quotation_id"] = $data['quotation_id'];
      $items_where["sqi.work_type_id"] = $work_type_id;
      $items = $this->Sales_quotation->select_quotation_items("sqi.*,sqt.template_no,mu.unit_name",$items_where);
      if($items->num_rows()==0){
        if($quotation_data->work_types!=''){
          $work_types_array = explode(',',$quotation_data->work_types);
          if (($key = array_search($work_type_id, $work_types_array)) !== false) {
            unset($work_types_array[$key]);
          }
          $update_data['quotation_id'] = $data['quotation_id'];
          $update_data['work_types'] = implode(',',$work_types_array);
          $result = $this->Sales_quotation->update_quotation($update_data);
          $flash_data['status'] = $result;
          if($result == 1){
            $flash_data['flashdata_msg'] = 'Item Deleted Successfully!.';
            $flash_data['flashdata_type'] = 'success';
            $flash_data['alert_type'] = 'success';
            $flash_data['flashdata_title'] = 'Success !';
          }else{
            $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
            $flash_data['flashdata_type'] = 'error';
            $flash_data['alert_type'] = 'danger';
            $flash_data['flashdata_title'] = 'Error !!';
          }
        }else{
          $flash_data['status'] = 2;
          $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
          $flash_data['flashdata_type'] = 'error';
          $flash_data['alert_type'] = 'danger';
          $flash_data['flashdata_title'] = 'Error !!';
        }
      }else{
        $flash_data['status'] = 2;
        $flash_data['flashdata_msg'] = 'Sorry.. Items Exist under Selected Work Type. Please Delete Items first!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Items Exist !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $this->session->set_flashdata($flash_data);
    redirect($this->input->post('redirect_url'),'refresh');
    // echo(json_encode($flash_data));
  }


}
?>
