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

class Purchase extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
         if (! $this->session->userdata ( 'user_logged_in' ) || !company_url($this->session->userdata ('company_slag'))) {
            redirect ( 'login', 'refresh' );
        }
        $this->load->vars ( array (
                'global' => 'Available to all views',
                'header' => 'common/header',
                'left' => 'common/left',
                'footer' => 'common/footer' 
        ) );

        $this->load->model('User_model');
        $this->load->model('Item_model');
        $this->load->model('Purchase_model');
        $this->load->model('Setings_model');
    }

    public function index(){
        $data['purchase_list'] = $this->Purchase_model->purchase_list();
        $this->load->view('purchase_list',$data);
    }

    public function newpurchase(){
        $data['bill_id'] = !empty($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        if (!empty($data['bill_id'])) {
            $bill_details = $this->Purchase_model->get_from_table('purchase_bill','*',array('bill_no' => $data['bill_id']));
            $data['bill_data'] = (array)$bill_details[0];
            $data['item_details'] = $this->Purchase_model->get_from_table('bill_item_detail','*',array('purchase_bill_id' => $data['bill_data']['purchase_bill_id']));
            $data['customer_details'] = $this->User_model->get_user_data($data['bill_data']['vendor_id']);
        } else {
            $data['bill_id'] = $this->purchaseId();
        }

        $where = array('contact_type' => 2,'status' => 1);
        $data['customer_list'] = $this->User_model->user_list_where($where);

        $data['item_list'] = $this->Item_model->get_items();
        $item_gst = array();
        $item_purchase_price = array();
        $item_uom = array();
        $item_hsn = array();
        $items_autocomplete = array();
        $items_barcode = array();
        if (count($data['item_list'])>0) {
            foreach ($data['item_list'] as $key => $value) {
                $items_autocomplete[$key] = new stdClass();
                $items_autocomplete[$key]->id = $value->item_id;
                $items_autocomplete[$key]->name = $value->item_name;
                
                $items_barcode[$value->item_no] = $value;

                $item_hsn[$value->item_id]=$value->hsn_code;
                $item_gst[$value->item_id]=$value->gst_rate;
                $item_purchase_price[$value->item_id]=$value->rate_purchase;
                $item_uom[$value->item_id]=$value->unit;
            }
        }
        $data['items_autocomplete'] = json_encode($items_autocomplete);
        $data['items_barcode'] = json_encode($items_barcode);
        $data['item_hsn'] = json_encode($item_hsn);
        $data['item_gst'] = json_encode($item_gst);
        $data['item_purchase_price'] = json_encode($item_purchase_price);
        $data['item_uom'] = json_encode($item_uom);

        //$data['bill_no'] = $this->purchaseId();
        $this->load->view('purchase_create',$data);
    }

    public function purchaseId(){
        return rand(0,5000).strtotime(date('d-m-y H:i:s'));
    }

    public function generate_bill(){
        $form_data = $this->input->post('bill_basic');
        $sum_amounts = $this->input->post('items_tot');
        $item_data = $this->input->post('items');
        $userState = $this->input->post('userState');
        $status = $this->input->post('status');

        $data['bill_data'] = array(
                'bill_no'    => $form_data[1]['value'],
                'vendor_id'   => $form_data[0]['value'],
                'order_no'      => $form_data[2]['value'],
                'bill_date'  => date('Y-m-d',strtotime(str_replace('/', '-', $form_data[3]['value']))),
                'due_date'      => date('Y-m-d',strtotime(str_replace('/', '-', $form_data[4]['value']))),
                'total'         => $sum_amounts['final_total'],
                'sub_total'     => $sum_amounts['sub_total'],
                'cgst_total'    => $sum_amounts['cgst'],
                'sgst_total'    => $sum_amounts['sgst'],
                'igst_total'    => $sum_amounts['igst'],
                'status'        => $status,
                'date_added'    => date('Y-m-d')
            );
        $check_bill = $this->Purchase_model->get_from_table('purchase_bill','*',array('bill_no' => $form_data[1]['value']));
        if (count($check_bill) > 0) {
            $purchase_bill_id =  $check_bill[0]->purchase_bill_id;
            $this->Purchase_model->update_data('purchase_bill',$data['bill_data'],array('bill_no' => $form_data[1]['value'],'purchase_bill_id' => $purchase_bill_id));
        } else {
            $purchase_bill_id = $this->Purchase_model->insert_data('purchase_bill',$data['bill_data']);    
        }

        if (count($item_data) > 0) {
            $stock_items = array();
            foreach ($item_data as $key => $value) {
                $item_details[] = array(
                    'purchase_bill_id' => $purchase_bill_id,
                    'item' => $value['item_name'],
                    'qty' => $value['quantity'],
                    'hsn_code'          => $value['hsn_code'],
                    'gst_rate'          => $value['item_gst'],
                    'uom' => $value['uom'],
                    'rate' => $value['unit_price'],
                    //'discount' => $value['discount'],
                    'amount' => $value['price'],
                    'cgst' => (($userState == 19) ? ((($value['quantity'] * $value['unit_price']) * ($value['item_gst']/2)) / 100) : 0),
                    'sgst' => (($userState == 19) ? ((($value['quantity'] * $value['unit_price']) * ($value['item_gst']/2)) / 100) : 0),
                    'igst' => (($userState != 19) ? ((($value['quantity'] * $value['unit_price']) * $value['item_gst']) / 100) : 0)
                );

                if ($value['item_id'] > 0) {
                    $stock_items= array(
                        'item_id' => $value['item_id'],
                        'qty_sale' => 0,
                        'qty_purchase' => $value['quantity'],
                        'inv_bill_id' => $purchase_bill_id,
                        'date_added' => date('Y-m-d'),
                        'is_note' => 2
                    );
                    $stock_id = $this->Purchase_model->insert_data('item_stock',$stock_items);

                    if (in_array($value['item_id'],array(1,2))) {
                        $metl_stone_stock = array(
                                'purchase_expence_id'  =>  $stock_id,
                                'material_item_id'  =>  $value['item_id'],
                                'material_weight_in_gm'  =>  $value['quantity'],
                                'purchase_expance'  =>  1,
                                'date_added'  =>  date('Y-m-d'),
                                'date_edited'  =>  date('Y-m-d'),
                                'status'  =>  1
                            );
                        $this->Purchase_model->insert_data('raw_material_stock',$metl_stone_stock);
                    }
                }
            }

            // $data['customer_details'] = $this->User_model->get_user_data($form_data[0]['value']);
            // $data['item_details'] = $item_details;
            if (count($check_bill) > 0) {
                $purchase_bill_id =  $check_bill[0]->purchase_bill_id;
                $this->Purchase_model->delete_data('bill_item_detail',array('purchase_bill_id' => $purchase_bill_id));
                $this->Purchase_model->delete_data('item_stock',array('inv_bill_id' => $purchase_bill_id,'is_note' =>2));
            }
            $this->Purchase_model->insert_data_batch('bill_item_detail',$item_details);
            // if (count($stock_items) > 0) {
            //     $this->Purchase_model->insert_data_batch('item_stock',$stock_items);
            // }
        }

        echo $form_data[1]['value'];
    }

    public function bill_print($id_bill){
        $data['setings'] = $this->Setings_model->get_setings();
        $data['bill_id'] = $id_bill;
        $bill_details = $this->Purchase_model->get_from_table('purchase_bill','*',array('purchase_bill_id' => $data['bill_id']));
        $data['bill_data'] = (array)$bill_details[0];
        $data['item_details'] = $this->Purchase_model->get_from_table('bill_item_detail','*',array('purchase_bill_id' => $data['bill_data']['purchase_bill_id']));
        // $data['item_details'] = $this->Invoice_model->get_bill_item_details(array('sale_bill_id' => $data['bill_data']['sale_bill_id']));
        $data['customer_details'] = $this->User_model->get_user_data($data['bill_data']['vendor_id']);
        $this->load->view('purchase_print',$data);
    }
}
?>