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

class Debit_note 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('Purchase_model');
        $this->load->model('Item_model');
        $this->load->model('Setings_model');
    }

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

    public function new_debit_note(){
        $data['devid_note_edit_no'] = !empty($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        if (!empty($data['devid_note_no'])) {
            // $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['devid_note_no'] = $this->debitnoteId();
        }

        $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();
        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;

                $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['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);

        $this->load->view('debit_note_create',$data);
    }

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

    public function user_bill_list(){
        $user_id = $this->input->post('user_id');
        $bill_list = $this->Purchase_model->get_bills_for_user($user_id);
        $options = '';
        if (count($bill_list)>0) {
            foreach ($bill_list as $key => $value) {
                $options .= '<option value="'.$value->bill_no.'">'.$value->bill_no.'</option>';
            }
        }
        echo $options;
    }

    public function generate_debit_note(){
        $form_data = $this->input->post('debit_note_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['debit_data'] = array(
                'devid_note_no'       => $form_data[1]['value'],
                'vendor_id'     => $form_data[0]['value'],
                'bill_no'      => $form_data[2]['value'],
                'devid_date'     => date('Y-m-d',strtotime(str_replace('/', '-', $form_data[3]['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('devid_note','*',array('devid_note_no' => $form_data[1]['value']));
        if (count($check_bill) > 0) {
            $devid_note_id =  $check_bill[0]->devid_note_id;
            $this->Purchase_model->update_data('devid_note',$data['debit_data'],array('devid_note_no' => $form_data[1]['value'],'devid_note_id' => $devid_note_id));
        } else {
            $devid_note_id = $this->Purchase_model->insert_data('devid_note',$data['debit_data']);    
        }

        if (count($item_data) > 0) {
            $stock_items = array();
            foreach ($item_data as $key => $value) {
                $item_details[] = array(
                    'devid_note_id' => $devid_note_id,
                    'item'          => $value['item_name'],
                    'hsn_code'          => $value['hsn_code'],
                    'gst_rate'          => $value['item_gst'],
                    'qty' => $value['quantity'],
                    'uom' => $value['uom'],
                    'rate' => $value['unit_price'],
                    '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' => $value['quantity'],
                        'qty_purchase' => 0,
                        'inv_bill_id' => $devid_note_id,
                        'date_added' => date('Y-m-d'),
                        'is_note' => 4
                    );
                }
            }

            if (count($check_bill) > 0) {
                $devid_note_id =  $check_bill[0]->devid_note_id;
                $this->Purchase_model->delete_data('devid_note_item_detail',array('devid_note_id' => $devid_note_id));
                $this->Purchase_model->delete_data('item_stock',array('inv_bill_id' => $devid_note_id,'is_note' =>4));
            }
            $this->Purchase_model->insert_data_batch('devid_note_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 debit_note_print($key_debitnote){
        $data['setings'] = $this->Setings_model->get_setings();
        $data['dbtnote_id'] = $key_debitnote;
        $dbtnote_details = $this->Purchase_model->get_from_table('devid_note','*',array('devid_note_no' => $data['dbtnote_id']));
        $data['dbtnote_data'] = (array)$dbtnote_details[0];
        $data['item_details'] = $this->Purchase_model->get_from_table('devid_note_item_detail','*',array('devid_note_id' => $data['dbtnote_data']['devid_note_id']));
        $data['customer_details'] = $this->User_model->get_user_data($data['dbtnote_data']['vendor_id']);
        $this->load->view('debit_note_print',$data);
    }

}?>