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

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

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

    function new_credit_note(){
        $data['credit_note_edit_no'] = !empty($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        if (!empty($data['credit_note_no'])) {
            // $invoice_details = $this->Invoice_model->get_from_table('sale_invoice','*',array('invoice_no' => $data['invoice_id']));
            // $data['invoice_data'] = (array)$invoice_details[0];
            // $data['item_details'] = $this->Invoice_model->get_from_table('invoice_item_detail','*',array('sale_invoice_id' => $data['invoice_data']['sale_invoice_id']));
            // $data['customer_details'] = $this->User_model->get_user_data($data['invoice_data']['customer_id']);
        } else {
            $data['credit_note_no'] = $this->credit_note_no();
        }
        $where = array('contact_type' => 1,'status' => 1);
        $data['customer_list'] = $this->User_model->user_list_where($where);

        $data['item_list'] = $this->Item_model->get_items();
        $item_gst = array();
        $item_sale_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_sale_price[$value->item_id]=$value->rate_sale;
                $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_sale_price'] = json_encode($item_sale_price);
        $data['item_uom'] = json_encode($item_uom);

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

    public function credit_note_no(){
        $last_id = $this->Invoice_model->get_from_table('credit_note','max(credit_note_id) lastId','credit_note_id > 0');
        return 'BPFEJB'.sprintf('%06d', ($last_id[0]->lastId+1));
    }

    public function user_invoice_list(){
        $user_id = $this->input->post('user_id');
        $invoice_list = $this->Invoice_model->get_invoice_for_user($user_id);
        $options = '';
        if (count($invoice_list)>0) {
            foreach ($invoice_list as $key => $value) {
                $options .= '<option value="'.$value->invoice_no.'">'.$value->invoice_no.'</option>';
            }
        }
        echo $options;
    }


    public function generate_credit_note(){
        $form_data = $this->input->post('invoice_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['credit_note_data'] = array(
                'credit_note_no'    => $form_data[1]['value'],
                'customer_id'   => $form_data[0]['value'],
                'invoice_no'      => $form_data[2]['value'],
                'credit_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'],
                'is_adjusted'   => 0,
                'status'        => $status,
                'date_added'    => date('Y-m-d')
            );
        $check_credit_note = $this->Invoice_model->get_from_table('credit_note','*',array('credit_note_no' => $form_data[1]['value']));
        if (count($check_credit_note) > 0) {
            $credit_note_id =  $check_credit_note[0]->credit_note_id;
            $this->Invoice_model->update_data('credit_note',$data['credit_note_data'],array('credit_note_no' => $form_data[1]['value'],'credit_note_id' => $credit_note_id));
        } else {
            $credit_note_id = $this->Invoice_model->insert_data('credit_note',$data['credit_note_data']);    
        }
        //echo $this->db->last_query();
        if (count($item_data) > 0) {
            $stock_items = array();
            foreach ($item_data as $key => $value) {
                $item_details[] = array(
                    'credit_note_id' => $credit_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'],
                    '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)
                );

                $stock_items[]= array(
                        'item_id' => $value['item_id'],
                        'qty_sale' => 0,
                        'qty_purchase' => $value['quantity'],
                        'inv_bill_id' => $credit_note_id,
                        'date_added' => date('Y-m-d'),
                        'is_note' => 3
                    );
            }
           
            // $data['customer_details'] = $this->User_model->get_user_data($form_data[0]['value']);
            // $data['item_details'] = $item_details;
            if (count($check_credit_note) > 0) {
                $credit_note_id =  $check_credit_note[0]->credit_note_id;
                $this->Invoice_model->delete_data('credit_note_item_details',array('credit_note_id' => $credit_note_id));
                $this->Invoice_model->delete_data('item_stock',array('inv_bill_id' => $credit_note_id,'is_note' =>3));
            }
            $this->Invoice_model->insert_data_batch('credit_note_item_details',$item_details);
            if (count($stock_items) > 0) {
                $this->Invoice_model->insert_data_batch('item_stock',$stock_items);
            }
        }
        echo $form_data[1]['value'];
    }

    public function credit_note_print($key_crnote){
        $data['setings'] = $this->Setings_model->get_setings();
        $data['crnote_id'] = $key_crnote;
        $invoice_details = $this->Invoice_model->get_from_table('credit_note','*',array('credit_note_no' => $data['crnote_id']));
        $data['crnote_data'] = (array)$invoice_details[0];
        $data['item_details'] = $this->Invoice_model->get_from_table('credit_note_item_details','*',array('credit_note_id' => $data['crnote_data']['credit_note_id']));
        // $data['payment_done'] = $this->Invoice_model->get_from_table('invoice_payment','*',array('sale_invoice_id' => $data['invoice_data']['sale_invoice_id']));

        $data['is_editable'] = FALSE;
        $data['customer_details'] = $this->User_model->get_user_data($data['crnote_data']['customer_id']);
        $this->load->view('credit_note_print',$data);
    }

}