<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Billing_temple_shop_sales extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('billing/temple_shop_sales_model', '', TRUE);
        $this->load->model('login_details_model', '', TRUE);
        $this->uri_key_index = 0;
        
        //$this->print_list(1);
    }
    
    public function index($id = 19) {
        $data = array();
        $data['results'] = $this->temple_shop_sales_model->list_all();
        if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        $actions = $this->actions();
        $data['add_btn']    = 'Create New Temple Shop Sales';
        $data['view_link']  = $actions['view'] . '/';
        $data['add_link']   = $actions['add'] . '/' . $id ;
        $data['edit_link']  = $actions['edit'] . '/';
        $data['delete_link']= $actions['delete'] . '/';
        $data['print'] = base_url() . 'billing_temple_shop_sales/print_list/';
        $data['title'] = 'Temple Shop Sales';
        
        $data['menu_id'] = $id;
        $service_menu = get_billing_controller($actions['controller']);
        $data['title'] = $service_menu->service_name;
        $data['service_menu_id'] = array('service_menu_id' => $service_menu->id, 'menu_type' => '4');
        $this->render($data, 'billing/temple_shop_sales/list');
    }
    
    public function add($type_id= '') {
        $data = array();
        $actions = $this->actions();
        
        $where['is_statue_item'] = 1;
        $data['inventory_item'] = $this->temple_shop_sales_model->get_sb_item();
        $data['fn_types'] = $this->temple_shop_sales_model->get( TBL_SERVICE, array( 'menu_name' => $type_id ) );
        
        $data['service_type_id'] = $type_id;
        $data['ptypes'] = $this->temple_shop_sales_model->get( TBL_PAY_TYPE );
        
        $data['form_action'] = $actions['insert'];
        $data['title'] = 'Temple Shop Sales';
        $this->render($data, 'billing/temple_shop_sales/add');
    }
    
    private function get_festival_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->temple_shop_sales_model->festival_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_festival_url_key($name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    public function insert() {
        
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($this->input->post('cs_amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        
        $insert = array(
            'type_id' => $this->input->post('type_id'),
            'service_id' => $this->input->post('fn_type'),
            'date' => date('Y-m-d'),
            'devotee_name1' => $this->input->post('ct_dev_name_1'),
            'contact_no' => $this->input->post('ct_contact_no'),
            'email' => $this->input->post('ct_email'),
            'address' => $this->input->post('ct_address'),
            'desc' => $this->input->post('cs_desc'),
            'amount' => $this->input->post('cs_amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'url_key' => $this->get_festival_url_key($this->input->post('ct_dev_name_1')),
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        /*
        * Get last Receipt ID
        */
        $wh = array(
            'service_id'    => $insert['service_id'] 
        );

        $receipt_no = generate_rec_no(TBL_BILL_TEMPLESHOP_SALES, $wh);
        $insert['receipt_no'] = $receipt_no;   
        
        $insert_id = $this->temple_shop_sales_model->insert($insert);
        
        if ($insert_id > 0) {
            $this->session->set_flashdata('success', 'Billing for Temple Shop Sales is added successfully');
           
            $inv_item = $this->input->post('pr_item');
            $qty = $this->input->post('pr_qty');
            $price = $this->input->post('pr_price');
            
            if(!empty($inv_item)) {
                foreach( $inv_item as $k => $item_id ) {
                    $sub_total = $qty[$k] * $price[$k];
                    $insert = array(
                        'temple_shop_id'         => $insert_id,
                        'inventory_item_id'      => $item_id,
                        'quantity'               => $qty[$k],
                        'price'                  => $price[$k],
                        'sub_total'              => $sub_total,
                        'status'                 => 1,
                        'url_key'                => $this->get_festival_url_key($item_id),
                        'created_by'             => $this->user_data['user_id'],
                        'created_on'             => date('Y-m-d H:i:s')
                    );
                    $this->temple_shop_sales_model->insert_prasadam($insert);
                    
                    $update_data = array(
                        'updated_by' => $this->user_data['user_id'],
                        'updated_on' => date('Y-m-d H:i:s')
                    );
                    
                    $this->temple_shop_sales_model->update_sb_item_qty($item_id, $update_data, $qty[$k], '-');
                }
            }
            
            
                $pay_type = $this->input->post('pay_type');
                
                foreach( $pay_type as $key => $value ) {
                    if($value != '') {
                        
                        $this->db->select('slug');
                        $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $key) );
                        $prow = $q->row_array();
                   
                        $pay_details = array();
                        if( $prow['slug'] == 'cheque' && !empty($value) ) :
                            // Cheque
                            $e = explode('-', $this->input->post('chq_date'));
                            $pay_details = array(
                                'name'   => $this->input->post('chq_bnk_name'),
                                'no'   => $this->input->post('chq_no'),
                                'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                            );
                        endif;
                   
                        $pay_details = json_encode( $pay_details );
                   
                        $insert = array(
                            'pay_ref_type'  => 19,
                            'pay_ref_id'    => $insert_id,
                            'pay_type_id'   => $key,
                            'pay_amount'    => $value,
                            'pay_details'   => $pay_details,
                            'status'        => 1,
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => date('Y-m-d H:i:s')
                        );
                        
                        $this->temple_shop_sales_model->insert_payment($insert);
                        
                    }
                }
                $this->session->set_flashdata('success', 'Billing for Temple Shop Sales is added successfully');
                
                if( !empty( $pay_type ) ) :
                    /*
                     * Print Receipt
                     */
                   $this-> print_list( $insert_id );
                endif;
                
                /*** To Print Receipt - Start ***/
//                $service_menu = $this->login_details_model->get_service_menu_by_id($this->input->post('type_id'));
//                $prefix = get_general_setting()->prefix;
//                $festival = $this->temple_shop_sales_model->get_by_id($insert_id);
//                
//                $args = array(
//                    'type'      => '1', // Default = 1 // Normal (Double print), '2' => Archanai,   '3' = Hall Booking | Wedding Hall
//                    'rec_no'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
//                    'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
//                    'amount'    => array($this->input->post('cs_amount')),
//                    'gst'       => $gst_details->gst,
//                    
//                    'data'      => array(
//                        // Type = 1 && 3 
//                        'name'      => array($this->input->post('ct_dev_name_1') .','. $festival->devotee_name1),
//                        'contact_no'=> $this->input->post('ct_contact_no'),
//                        'email'     => $this->input->post('ct_email'),
//                        'address'   => $this->input->post('ct_address'),
//                        'desc'      => $this->input->post('cs_desc'),
//                        
//                        'section'  => array(
//                            array(
//                                'Date<div class="sub-lbl"> தேதி</div>' => date('d/m/Y',strtotime($this->input->post('fn_date'))),
//                                'Time<div class="linear-lbl"> நேரம�?</div>'      => date('H:i',strtotime($this->input->post('fn_from_time'))) . ' - ' . date('H:i',strtotime($this->input->post('fn_to_time'))),
//                                'Period<div class="linear-lbl"> காலம�?</div>'    => ($this->input->post('fn_period') == 1) ? 'Morning / காலை' : 'Evening / மாலை',
//                                'Deity<div class="linear-lbl"> தெய�?வம�?</div>'     => $festival->god_name,
//                            ),
//                        ),
//                    ),
//                    
//                );
//                
//                print_rec($args);      
                /*** End ***/
            
        }
        else
            $this->session->set_flashdata('error', 'Billing for Temple Shop Sales is not added!');   
        
        if(empty($this->input->post('book-now')))
            redirect('billing_temple_shop_sales', 'refresh');

        else
            redirect('billing_temple_shop_sales/add/' . $this->input->post('type_id'), 'refresh');
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $id;
        
        $data['templeshopsale'] = $this->temple_shop_sales_model->get_by_id($id);
        $data['paid_amount'] = $this->temple_shop_sales_model->total_paid_amount($data['templeshopsale']->type_id,$data['templeshopsale']->id);
        $data['inventory_item'] = $this->temple_shop_sales_model->get_sb_item();
        $data['fn_types'] = $this->temple_shop_sales_model->get( TBL_SERVICE, array( 'menu_name' => $data['templeshopsale']->type_id ) );
        $data['ptypes'] = $this->temple_shop_sales_model->get( TBL_PAY_TYPE );
        $data['items'] = $this->temple_shop_sales_model->get_prasadam_json($id);
        $data['title'] = 'Temple Shop Sales';
        $this->render($data, 'billing/temple_shop_sales/edit');
    }
    
    public  function update($id){
        if (empty($id)) {
            show_400_error();
        }
        
        $page_id = $id;
        $festival = $this->temple_shop_sales_model->get_by_id($id);
        $gst_details = $this->login_details_model->get_amount_by_service_id($this->input->post('fn_type'));
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($this->input->post('cs_amount'));
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        
        $update = array(
            'type_id' => $this->input->post('type_id'),
            'service_id' => $this->input->post('fn_type'),
            'devotee_name1' => $this->input->post('ct_dev_name_1'),
            'contact_no' => $this->input->post('ct_contact_no'),
            'email' => $this->input->post('ct_email'),
            'address' => $this->input->post('ct_address'),
            'desc' => $this->input->post('cs_desc'),
            'amount' => $this->input->post('cs_amount'),
            'gst' => $gst,
            'gst_value' => $gst_amount,
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        $receipt_no = $festival->receipt_no;
        
        
        if( empty( $receipt_no )) :
            /*
            * Get last Receipt ID
            */
            $wh = array(
                'service_id'    => $update['service_id']
            );
            
            $receipt_no = generate_rec_no(TBL_BILL_TEMPLESHOP_SALES, $wh);
            $update['receipt_no'] = $receipt_no;   
            
        else :
            $update['created_on'] =  date('Y-m-d H:i:s');
        endif;
        
        $affected_rows = $this->temple_shop_sales_model->update($update,$id);
        
        if($affected_rows > 0) {
            
            $update_data = array(
                            'updated_by' => $this->user_data['user_id'],
                            'updated_on' => date('Y-m-d H:i:s')
            );
            
            $inv_item = $this->input->post('pr_item');
            $qty = $this->input->post('pr_qty');
            $price = $this->input->post('pr_price');
            $pr_id = $this->input->post('pr_id');
            
            if(!empty($inv_item)) {
                foreach( $inv_item as $k => $item_id ) {
                    $sub_total = $qty[$k] * $price[$k];
                    
                    if(empty($pr_id[$k])) {
                        $insert = array(
                            'temple_shop_id'   => $id,
                            'inventory_item_id'      => $item_id,
                            'quantity'      => $qty[$k],
                            'price'         => $price[$k],
                            'sub_total'     => $sub_total,
                            'status'        => 1,
                            'url_key'       => $this->get_festival_url_key($item_id),
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => date('Y-m-d H:i:s')
                        );
                        $this->temple_shop_sales_model->insert_prasadam($insert);
                        $this->temple_shop_sales_model->update_sb_item_qty($item_id, $update_data, $qty[$k], '-');
                        
                    } else {
                        $old_item = $this->temple_shop_sales_model->get_prasadam_by_itemid($pr_id[$k]);
                        $quantity_txt = $old_item[0]['quantity'];
                        $this->temple_shop_sales_model->update_sb_item_qty($old_item[0]['inventory_item_id'], $update_data, $quantity_txt, '+');
                       
                        $update = array(
                            'temple_shop_id'   => $id,
                            'inventory_item_id'      => $item_id,
                            'quantity'      => $qty[$k],
                            'price'         => $price[$k],
                            'sub_total'     => $sub_total,
                            'status'        => 1,
                            'url_key'       => $this->get_festival_url_key($item_id),
                            'created_by'    => $this->user_data['user_id'],
                            'created_on'    => date('Y-m-d H:i:s')
                        );
                        $this->temple_shop_sales_model->update_prasadam_by_id($update,$pr_id[$k]);
                        
                        $this->temple_shop_sales_model->update_sb_item_qty($item_id, $update_data, $qty[$k], '-');
                        
                         
                    }
                    
                }
            }
            
            
                $this->session->set_flashdata('success', 'Billing for Temple Shop Sales is updated successfully');
              
                    $paid_hidden_id = $this->input->post('paid_hidden_id');
                    if(!empty($paid_hidden_id)) {
                        foreach($paid_hidden_id as $k=>$value) :
                            $paidtype = $this->temple_shop_sales_model->delete_payment_by_paid_id($value);
                        endforeach;
                    }
                
                    $pay_type = $this->input->post('pay_type');
                    foreach( $pay_type as $key => $value ) {
                        if($value > 0 && $value != '') {
                            $this->db->select('slug');
                            $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $key) );
                            $prow = $q->row_array();
                           
                            $pay_details = array();
                            if( $prow['slug'] == 'cheque' && !empty($value) ) :
                               // Cheque
                               $e = explode('-', $this->input->post('chq_date'));
                               $pay_details = array(
                                   'name'   => $this->input->post('chq_bnk_name'),
                                   'no'   => $this->input->post('chq_no'),
                                   'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                               );
                            endif;
                           
                            $pay_details = json_encode( $pay_details );
                            
                            $insert = array(
                                'pay_ref_type'  => 19,
                                'pay_ref_id'    => $id,
                                'pay_type_id'   => $key,
                                'pay_amount'    => trim($value),
                                'pay_details'   => $pay_details,
                                'status'        => 1,
                                'created_by'    => $this->user_data['user_id'],
                                'created_on'    => $festival->created_on
                            );
                            $this->temple_shop_sales_model->insert_payment($insert);
                        }
                    }
                    
              
                    
                    if( !empty($pay_type) && $this->input->post('prev_paid_amount') != $this->input->post('paid_amount') ) :
                       /*
                        * Print Receipt
                        */
                        $this->print_list( $page_id );
                    endif;
                    
                    
                  #echo '<pre>'; print_r( $this->input->post() );  die;
            /*
             * Items
             */
            // Set status for removed Items
            if( !empty($this->input->post('removed-items')) ) :
                $e = explode("-", trim($this->input->post('removed-items'), '-'));
                foreach( $e as $k => $rm_id ) :
                    
                    $old_item = $this->temple_shop_sales_model->get_prasadam_by_itemid($rm_id);
                    $quantity_txt = $old_item[0]['quantity'];
                    $this->temple_shop_sales_model->update_sb_item_qty($old_item[0]['inventory_item_id'], $update_data, $quantity_txt, '+');
                    
                    $update = array('status' => 2);
                    $this->temple_shop_sales_model->update_prasadam_by_id($update,$rm_id);
                endforeach;
            endif;
            
        } else 
            $this->session->set_flashdata('error', 'Billing for Temple Shop Sales is not updated!');
        
        if(empty($this->input->post('book-now')))
            redirect('billing_temple_shop_sales', 'refresh');

        else
            redirect('billing_temple_shop_sales/add/' . $this->input->post('type_id'), 'refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['templeshopsale'] = $this->temple_shop_sales_model->get_by_id($id);
        $data['paid_amount'] = $this->temple_shop_sales_model->total_paid_amount($data['templeshopsale']->type_id,$data['templeshopsale']->id);
        $data['prasadams'] = $this->temple_shop_sales_model->get_prasadam_by_id($id);
        $data['ptypes'] = $this->temple_shop_sales_model->get_paid_type_by_id($data['templeshopsale']->type_id,$id);
        $data['title'] = 'Temple Shop Sales';
        $this->render($data, 'billing/temple_shop_sales/view');
    }
    
    public function delete($id = '', $menu_id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $update = array ( 
            'amount' => 0,
            'del_reason' => $this->input->post('hidden_del_reason'),
            'status' => 2,
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );

        if ($this->temple_shop_sales_model->update($update,$id) > 0) {
            $this->session->set_flashdata('success', 'Billing for Temple Shop Sales is deleted successfully');
            
            $update_data = array(
                            'updated_by' => $this->user_data['user_id'],
                            'updated_on' => date('Y-m-d H:i:s')
                    );
            $item_data = $this->temple_shop_sales_model->get_prasadam_by_id($id);
            foreach($item_data as $key=> $prasadam) {
                $quantity_txt = $prasadam->quantity;
                $this->temple_shop_sales_model->update_sb_item_qty($prasadam->inventory_item_id, $update_data, $quantity_txt, '+');
            }
            
            $festival = $this->temple_shop_sales_model->get_by_id($id);
            
            $update = array ( 
                'pay_amount' => 0,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            $this->temple_shop_sales_model->update_paid_type($update,$festival->type_id,$id);
//            $this->temple_shop_sales_model->update_refund(array('status' => 2),$festival->type_id,$id);
            
            $update = array ( 
                'sub_total' => 0,
                'status' => 2,
                'updated_by' => $this->user_data['user_id'],
                'updated_on' => date('Y-m-d H:i:s')
            );
            $this->temple_shop_sales_model->update_prasadam($update,$id);
        }
           
        else 
            $this->session->set_flashdata('error', 'Billing for Temple Shop Sales is not deleted!');
        
        redirect( 'billing_temple_shop_sales/index/' . $menu_id, 'refresh');
    }
    
    public function get_data_by_service_type(){
        $data['get_data'] =  $this->temple_shop_sales_model->get_data_by_service_type($_POST['service_type']);
        $data['get_contact'] =  $this->temple_shop_sales_model->get_contact_by_service_type($_POST['service_type']);
        echo json_encode($data);
        exit(0);
    }
    
    public function ajax() {
        $results =  $this->temple_shop_sales_model->ajax();
        echo json_encode( $results );
    }
    
    public function get_prasadam_price() {
        $data = $this->temple_shop_sales_model->get_prasadam_price($_POST['id']);
        echo json_encode($data);
        exit(0);
    }
    
    function print_list($id,$menu_id) {
        $res = $this->temple_shop_sales_model->get_by_id($id);
        
        /*** To Print Receipt - Start ***/
        $service_menu = $this->login_details_model->get_service_menu_by_id($res->type_id);
        $menu_id = !empty( $menu_id ) ? $menu_id : $service_menu->id;
        
        $this->db->select('pt.name, p.pay_details');
        $this->db->group_by('p.pay_type_id');
        $this->db->select('pt.name');
        $this->db->join( TBL_PAY_TYPE . ' AS pt', 'pt.id = p.pay_type_id' );
        $q = $this->db->get_where( TBL_PAY . ' AS p', array('p.pay_ref_type' => $menu_id, 'p.pay_ref_id' => $id));
        $pay_results = $q->result_array();
        
        if( !empty( $pay_results ) ) :
        
            $gst_details = $this->login_details_model->get_amount_by_service_id($res->service_id);
            $prefix = get_general_setting()->prefix;

            //echo '<pre>'; print_r($service_menu); die;
            $this->db->select('ii.item_name AS name, ti.quantity, ti.price');
            $this->db->join( TBL_INV_ITEM . ' AS ii', 'ii.id = ti.inventory_item_id' );
            $q = $this->db->get_where(TBL_BILL_TEMPLESHOP_ITEM . ' AS ti', array('ti.temple_shop_id' => $id, 'ti.status' => 1));
            $items = $q->result_array();
            
            $rec_no = ($prefix == 1 ? $gst_details->prefix : '') . $res->receipt_no;
            $args = array(
               'type'      => '6', // Default = 1 // Normal (Double print), '2' => Kattalai Archanai,   '3' = Hall Booking | Wedding Hall, '4' => 'Madapalli', '5' => Archanai, '6' => Common
               'rec_no'    => $rec_no,
               //'title'     => $service_menu->service_name . ' - ' . $gst_details->name,
               //'amount'    => array($res->amount),
               'gst'       => $gst_details->gst,
               'short'     => TRUE,
               'copy'      => TRUE,
               'html'      => '<style>#items-table td:nth-child(2), #items-table td:last-child{text-align: right;}</style>', 

               'data'      => array( 

                   // Type = 6
                   'fields'  => array(
                       'Receipt No'    => $rec_no,
                       'Date'          => !empty( $res->date ) ? date("d/m/Y", strtotime($res->date)) : '-',
                       'Type'          => $gst_details->name,
                       'Name'          => $res->devotee_name1,
                       'Contact No'    => $res->contact_no,
                       'Payment Mode'  => pay_mode_str($pay_results),
                       'Total'         => '<span style="font-weight: bold;">S$ '.$res->amount.'</span>',
                   ),

                   'tables' => array(
                       
                       'attr'  => 'id="items-table"', // <table>  attributes
                       'head'  => array('Name','Qty', 'Price (S$)'),
                       'body'  => $items, /*array(
                           array('Parvathi','2','10.00'),
                           array('Lakshmi','6','20.00'),
                           array('Lakshmi','6','20.00'),
                       ),*/

                   ),



               ),

           );

             //echo '<pre>'; print_r($args); die;
            $rec = print_rec( $args ); 

            $seg = $this->uri->segments;
            if( $seg[2] == 'index' ) :
                if( $rec ) :
                    $this->session->set_flashdata('success', 'Receipt has been printed successfully');
                else : 
                    $this->session->set_flashdata('error', 'Receipt has not been printed!');
                endif;
            endif;
        
            redirect( 'billing_temple_shop_sales/index/' . $menu_id, 'refresh');
            
        endif; // !Empty Pay Results    
        
        //die;
            
        /*** End ***/
        
        
    }
} ?>

