<?php
class Sales_estimation_model extends CI_Model
{
  function __construct()
  {
    parent::__construct();
  }

  public function create_sale_estimation($data){
    if ($this->session->userdata('branch_id') != 0) {
      $data['branch_id'] = $this->session->userdata('branch_id');
    }
    $query=$this->db->insert('sales_estimations', $data);
    $result=array();
    $result['insert_id']=$this->db->insert_id();
    $result['status']=$query;
    return $result;
  }
  public function update_sale_estimation($data)
  {
    if ($this->session->userdata('branch_id') != 0) {
      $this->db->where('branch_id', $this->session->userdata('branch_id'));
    }
    $this->db->where('estimation_id', $data['estimation_id']);
    $query=$this->db->update('sales_estimations', $data);
    return $query;
  }
  public function select_sale_estimation($columns="*",$data="")
  {
    $this->db->select($columns)->from('sales_estimations se');
    $this->db->join('customers c','se.buyer_customer_id=c.customer_id','left');
    $this->db->join('tax_state_codes tsc','tsc.state_id=se.buyer_state_id','left');
    $this->db->join('users u','se.created_by=u.user_id','left');
    $this->db->join('branches b','b.branch_id=se.branch_id','left');
    $this->db->join('branches b2','b2.branch_id=se.buyer_branch_id','left');
    $this->db->join('bank_account_details ba','ba.account_id=se.bill_bank_account','left');
    if(!empty($data)){
      $this->db->where($data);
    }
    if ($this->session->userdata('branch_id') != 0) {
      $this->db->where('se.branch_id', $this->session->userdata('branch_id'));
    }
    $this->db->order_by("se.estimation_date",'desc');
    $query = $this->db->get();
    return $query;
  }

  public function create_estimation_items($data){
    $query=$this->db->insert('sales_estimation_items', $data);
    $result=array();
    $result['insert_id']=$this->db->insert_id();
    $result['status']=$query;
    return $result;
  }
  public function select_estimation_sale_item($columns="*",$data="",$group_by="")
  {
    $this->db->select($columns)->from('sales_estimation_items sei');
    $this->db->join('sales_estimations se','sei.estimation_id=se.estimation_id');
    $this->db->join('tax_types tt','sei.tax_percent=tt.tax_id','left');
    $this->db->join('customers c','se.buyer_customer_id=c.customer_id','left');
    $this->db->join('materials m','sei.material_id=m.material_id');
    $this->db->join('measure_units mu','m.unit = mu.unit_id','left');
    $this->db->join('users u','sei.created_by=u.user_id','left');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("sei.delete_status",0);
    $this->db->where("se.delete_status",0);
    if ($this->session->userdata('branch_id') != 0) {
      $this->db->where('se.branch_id', $this->session->userdata('branch_id'));
    }
    if($group_by!=''){
      $this->db->group_by($group_by);
    }
    $this->db->order_by("sei.item_id",'asc');
    $query = $this->db->get();
    return $query;
  }

}
