<?php

/* 
 * Author       : Jai K
 * Purpose      : Model for Billing Madappalli
 * Created On   : 2016-08-13 12:13
 */

class Madappalli_Model extends CI_Model {
    
    function __construct() {
        parent::__construct();
        
        
        
    }
    
    function get( $tbl_name, $where = array(), $args = array() ) {
        if (!is_array($where)) { $where = array(); }
        $where['status'] = 1;
        if($tbl_name == 'thiru_payment_types') :
            $where['menu_id'] = 0;
        endif;
        
        if( !empty( $args['order_by'] ) ) :
            $this->db->order_by( $args['order_by'] );
        endif;
        
        $q = $this->db->get_where( $tbl_name, $where );
        return $q->result_array();
            
    }
    
    function get_by_id($id) {
        $this->db->where('id',$id);
        return $this->db->get(TBL_BM)->row();
    }
    
    function get_all( $id= '', $where = array() ) {
        if( !empty( $id ) ) :
            $where['self.id'] = $id;
        endif;
        
        #$where['self.status'] = 1;
        $where['self.bm_book_status'] = 1;
        
        
        $this->db->select( 'self.*, self.status AS status, serv.name AS service_name, serv.amount as ser_amount, serv.prefix' );
        
        $this->db->join( TBL_SERVICE . ' AS serv', 'serv.id = self.service_id', 'left' );
        
        $this->db->order_by('self.bm_rec_no','desc');
        
        $q = $this->db->get_where( TBL_BM . ' AS self', $where );
        return $q->result_array();
    }
    
    function get_all_booked_details( $id= '', $where = array() ) {
        if( !empty( $id ) ) :
            $where['self.id'] = $id;
        endif;
        
        $where['self.status'] = 1;        
        
        $this->db->select( 'self.*, self.status AS status, serv.name AS service_name, serv.amount as ser_amount, serv.prefix' );
        
        $this->db->join( TBL_SERVICE . ' AS serv', 'serv.id = self.service_id', 'left' );
        
        $q = $this->db->get_where( TBL_BM . ' AS self', $where );
        return $q->result_array();
    }
    
    function get_items_id($id) {
        $this->db->where('bm_id',$id);
        $this->db->where('status !=',2);
        return $this->db->get(TBL_BMI)->result_array();
    }
    
    function get_items( $bm_id ) {
        $where['self.bm_id'] = $bm_id;
        $where['self.status'] = 1;
        
        $this->db->select( 'self.*, self.id AS id, self.status AS status, god.name AS god_name, pras.name AS prasadam_name');
        
        $this->db->join( TBL_GOD_NAME . ' AS god', 'god.id = self.god_id', 'left' );
        $this->db->join( TBL_PRASADAM . ' AS pras', 'pras.id = self.prasadam_id', 'left' );
        $q = $this->db->get_where( TBL_BMI . ' AS self', $where );
        return $q->result_array();
    }
    
    function get_mad_items( $bm_id ) {
        $where['self.bm_id'] = $bm_id;
        $where['self.status'] = 1;
        
        $this->db->select( 'self.*, self.id AS id, self.status AS status, god.name AS god_name, pras.prasadam_name AS prasadam_name');
        
        $this->db->join( TBL_GOD_NAME . ' AS god', 'god.id = self.god_id', 'left' );
        $this->db->join( TBL_MADAPPALLI . ' AS pras', 'pras.id = self.prasadam_id', 'left' );
        $q = $this->db->get_where( TBL_BMI . ' AS self', $where );
        return $q->result_array();
    }
    
    function get_payments( $bm_id ) {
        $where['self.pay_ref_type'] = 9; // Billing Madappalli
        $where['self.pay_ref_id'] = $bm_id;
        $where['self.status'] = 1;
        
        $this->db->join( TBL_PAY_TYPE . ' AS ptype', 'ptype.id = self.pay_type_id' );
        $q = $this->db->get_where( TBL_PAY . ' AS self', $where );
        return $q->result_array();
    }    
    
    function manipulate() {
        $post   = $this->input->post();
        
        $date_now = date("Y-m-d H:i:s");
        $session_data = $this->session->userdata( TBL_PREFIX . 'user_logged_in' );
        $segments = $this->uri->segments;
        $page   = $segments[2];
        $is_add = $page == 'add' || $page == 'insert' ? TRUE : FALSE;
        $db_id  = $is_add ? '' : $segments[3];
        $service_id = $is_add ? $segments[3] : '';
        
        //echo "<pre>Data: "; print_r( $post ); die;
        
        
        
        $gst_details = $this->get_amount_by_service_id($post['fn_type']);
        $prefix = get_general_setting()->prefix;
        
        if($gst_details->gst == 1) {
            $gst = get_general_setting()->gst; 
            $gst_amount = ($gst / 100) * ($post['amount']);
        } else {
            $gst = '0.00';
            $gst_amount = '0.00';
        }
        
        $q = $this->db->get_where( TBL_SERVICE, array('id' => $post['fn_type']) );
        $service = $q->row_array();
        
        $q = $this->db->get_where( TBL_SERVICE_MENU, array('id' => $service['menu_name']) );
        $main_service = $q->row_array();
        
        $e = explode(( strpos( $post['fn_date'], '/' ) > 0 ? '/' : '-' ), $post['fn_date']); // dd-mm-yyyy
        $fn_date = $e[2] . '-' . $e[1] . '-' .$e[0];
        $args = array(
            'service_id'        => $post['fn_type'],
            
            'bm_fn_date'        => $fn_date,
            'bm_period'         => $post['fn_period'],
            'bm_dev_name'     => $post['dev_name'],
            
            'bm_tamil_name'   => htmlspecialchars( $post['tamil_name'] ),
            'bm_contact_no'     => $post['contact_no'],
            'bm_email'          => $post['email'],
            'bm_desc'           => $post['desc'],
            'gst'               => $gst,
            'gst_value'         => $gst_amount,
            'bm_book_status'    => !empty( $post['book-now'] ) ? 2 : 1,
            
            'bm_amount'         => $post['amount'],
        );
        
        
        if( empty( $post['book-now'] ) ) :
            // Returned | Extra items Added
            $args['bm_paid_amount'] = $post['amount'];
            $args['bm_pay_status']  = $args['bm_paid_amount'] >= $args['bm_amount'] ? '3' : ( $args['bm_paid_amount'] > 0 ? '2' : '1' );
        endif;
        
        $receipt_no = $post['rec_no'];
        $bk_status = $args['bm_book_status'];
        if( empty( $receipt_no ) || ( !$is_add && $bk_status == "1"  && $post['book_status'] == "2" ) ) :
            
            /*
            * Get last Receipt ID
            */
            $wh = array(
                'service_id'    => $service['id'],
                'bm_book_status'=> $bk_status
            );
            
            $receipt_no = generate_rec_no(TBL_BM, $wh);
            $args['bm_rec_no'] = $receipt_no;   
        endif;

        if( $is_add ) :
            // Insert 
            $args['bm_booked_date'] = $date_now;
            $args['created_on'] = $date_now;
            $args['created_by'] = $session_data['user_id'];

            if( $args['bm_book_status'] == "2" ) :
                // Booked Now
                $args['updated_on'] = $date_now;
                $args['updated_by'] = $session_data['user_id'];
            endif;
            
            /*$receipt_no = '0001';
            $services = $this->service_type_exists($post['fn_type']);
            if($services->num_rows() > 0) {
                $last_receipt_no = $services->row()->bm_rec_no;
                $last_no = (int)$last_receipt_no;
                $receipt_no = (($last_no + 1)  > 9999) ? ($last_no + 1)  : sprintf('0%03d', ($last_no + 1) );
            }*/
            
            $this->db->insert( TBL_BM, $args );
            $db_id = $this->db->insert_id();

        elseif( !empty( $db_id ) ):
            // Update
            if($post['book_status'] == 2) :
                $args['created_on'] = $date_now;
            endif;
            $args['updated_on'] = $date_now;
            $args['updated_by'] = $session_data['user_id'];

            $this->db->update( TBL_BM, $args, array( 'id' => $db_id ) );

        endif;

        
        /*
         * Items
         */
        // Set status for removed Items
        if( !empty( $post['removed-items'] ) ) :
            
            $e = explode("-", trim($post['removed-items'], '-'));
            foreach( $e as $k => $rm_id ) :
                $this->db->update( TBL_BMI, array('status' => 2 ), array( 'id' => $rm_id ) );
            endforeach;
            
        endif;
        
        $gods = $prasadams= $print_body = array();
        foreach( $post['pr_deity'] as $k => $god_id ) :
            $sub_total = $post['pr_qty'][$k] * $post['pr_price'][$k];
            
            $args = array(
                'god_id'        => $post['pr_deity'][$k],
                'prasadam_id'   => $post['pr_prasadam'][$k],
                'bmi_qty'       => $post['pr_qty'][$k],
                'bmi_price'     => $post['pr_price'][$k],
                'bmi_sub_total' => $sub_total,
            );
            
            if( !array_key_exists( $args['god_id'], $gods ) ) :
                $q  =$this->db->get_where( TBL_GOD_NAME, array('id' => $args['god_id']) );
                $gods[$args['god_id']] = $q->row_array();
            endif;
            
            if( !array_key_exists( $args['prasadam_id'], $prasadams ) ) :
                $q  =$this->db->get_where( TBL_MADAPPALLI, array('id' => $args['prasadam_id']) );
                $prasadams[$args['prasadam_id']] = $q->row_array();
            endif;
            
            $print_body[] = array(
                (!empty($args['god_id']) ? ($gods[$args['god_id']]['name'] . ((!empty($gods[$args['god_id']]['tamil_name'])) ? ' / <span class="linear-lbl lang-tamil">' . htmlspecialchars( $gods[$args['god_id']]['tamil_name'] ) . '</span>' : '')) : '<center> - </center>'),
                $prasadams[$args['prasadam_id']]['prasadam_name'] . ((!empty($prasadams[$args['prasadam_id']]['prasadam_tamil_name'])) ? ' / <span class="linear-lbl lang-tamil">' . htmlspecialchars( $prasadams[$args['prasadam_id']]['prasadam_tamil_name'] ) . '</span>' : '') ,
                '<div style="text-align: right;">'.$args['bmi_qty'] . ' x ' . $args['bmi_price'] .'</div>',
                '<div style="text-align: right;">'.number_format( $args['bmi_qty']*$args['bmi_price'], 2 ).'</div>',
            );
            
            if( empty( $post['pr_id'][$k] ) ) :
                // Insert
                $args['bm_id']      = $db_id;
                $args['created_on'] = $date_now;
                $args['created_by'] = $session_data['user_id'];

                $this->db->insert( TBL_BMI, $args );
                
            else :
                // Update
                
                $args['updated_on'] = $date_now;
                $args['updated_by'] = $session_data['user_id'];

                $this->db->update( TBL_BMI, $args, array( 'id' => $post['pr_id'][$k], 'bm_id' => $db_id ) );
                
            endif;

        endforeach;
        
        
        $madappalli = $this->get_by_id($db_id);        
        
        /*
         * Payments
         */
        
        // Drop all previous payments
        #$this->db->delete( TBL_PAY, array( 'pay_ref_type'  => 9, 'pay_ref_id'    => $db_id ) );
        
        if(empty(( $post['book-now'] )) && ($is_add || !empty($db_id))) { 
            $paid_hidden_id = $post['paid_hidden_id'];
            if(!empty($paid_hidden_id)) :
                $paidtype = $this->delete_payment_by_paid_id($paid_hidden_id);
            endif;
            
            foreach( $post['pay_type'] as $pay_type_id => $pay_amt ) :
                if( empty( $pay_amt ) ) :
                    // Skip empty amounts ..
                    continue;
                endif;

                $this->db->select('slug');
                $q = $this->db->get_where( TBL_PAY_TYPE, array('id' => $pay_type_id) );
                $prow = $q->row_array();
               
                $pay_details = array();
                if( $prow['slug'] == 'cheque' && !empty($pay_amt) ) :
                   // Cheque
                   $e = explode('-', $post['chq_date']);
                   $pay_details = array(
                       'name'   => $post['chq_bnk_name'],
                       'no'   => $post['chq_no'],
                       'date'   => $e[2].'-'.$e[1].'-'.$e[0],
                   );
                endif;
               
                $pay_details = json_encode( $pay_details );                
                
                $args = array(
                    'pay_ref_type'  => 9, // For Billing Madappalli
                    'pay_ref_id'    => $db_id, // Main ID
                    'pay_type_id'   => $pay_type_id,
                    'pay_amount'    => $pay_amt,
                    'pay_details'   => $pay_details,
                    'created_on'    => ((empty( $receipt_no ) || ( !$is_add && $bk_status == "1"  && $post['book_status'] == "2" ) ) ? date('Y-m-d H:i:s') : $madappalli->created_on),
                    'created_by'    => $session_data['user_id'],
                );
                
                // Insert
                $this->db->insert( TBL_PAY, $args );

            endforeach;
        }
        
        if(empty(( $post['book-now'] )) && ($is_add || (!empty($db_id) && ($post['hidden_amount'] < $post['amount'] || $post['book_status'] == 2)))) {
            /*
             * Print
             */
            
            $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'    => (($prefix == 1) ? $gst_details->prefix : '') . $receipt_no,
                'title'     => $main_service['service_name']. ' - '.$service['name'],
                'amount'    => array($post['paid_amount']), // Currently Paid
                'gst'       => $gst_details->gst,
                'copy'      => TRUE,
                'printType' => TRUE,
                
                'data'      => array( 
                    
                    // Type = 6
                    'fields'  => array(
                        'Name<div class="sub-lbl">பெயர்<div>'          => $post['dev_name'] . ((!empty($post['tamil_name'])) ? '  / <span class="linear-lbl lang-tamil">'. htmlspecialchars( $post['tamil_name'] ) .'</span>' : ''), //. tamil( $post['tamil_name'], 'border: none; font-weight: bold; font-size: 24px;' ),
                        /* 'Tamil Name<div class="sub-lbl">தமிழ் பெயர்<div>'    => tamil( $post['tamil_name'], 'border: none; font-weight: bold; font-size: 24px;' ), */
                        'Date<div class="sub-lbl">தேதி<div>' => str_replace('-', '/', $post['fn_date'] ),
                        'Period<div class="sub-lbl">காலம்<div>'        => $post['fn_period'] == '1' ? 'Morning / காலை' : 'Evening / மாலை',
                        'Contact No<div class="sub-lbl">தொடர்பு எண்<div>'    => $post['contact_no'],
                        'Email ID<div class="sub-lbl">மின்னஞ்சல்<div>'      => $post['email'],
                    ),
                    
                    'tables' => array(
                        
                        'head'  => array('God Name<div class="sub-lbl">கடவுள் பெயர்<div>', 'Prasadam Name<div class="sub-lbl">பிரசாதம்<div>','Qty x Unit Price($)<div class="sub-lbl">எண்ணிக்கை x ஒன்றின் விலை<div>', 'Amount($)<div class="sub-lbl">தொகை<div>'),
                        'body'  => $print_body,
        
                    ),
                    
                ),
                
            );
            
            print_rec($args);
        }
        
        
        /*** To Insert Refund Amount - Start ***/
        /* if(empty(( $post['book-now'] )) && ((!empty($db_id) && $post['hidden_amount'] > $post['amount']))) {
            $insert = array(
                'menu_id' => 9,
                'service_id' => $post['fn_type'],
                'auto_id' => $post['hidden_id'],
                'pay_type_id' => 1,
                'amount' => ($post['hidden_amount'] - $post['amount']),
                'created_on' => date('Y-m-d H:i:s'),
                'created_by' => $this->user_data['user_id']
            );
            $this->insert_refund_amount($insert);            
        } */
    }
    
    public function insert_refund_amount($data){
        $this->db->insert(TBL_REFUND,$data);
        return $this->db->insert_id();
    }
    
    function delete( $id, $hidden_del_reason ) {
        
        $args = array(
            'pay_amount'    => 0, // Deleted
        );
        
        $this->db->update( TBL_PAY, $args, array( 'pay_ref_type' => 9, 'pay_ref_id' => $id ) );
        $this->db->update( TBL_REFUND, array( 'status' => 2), array( 'menu_id' => 9, 'auto_id' => $id ));
        
        $update = array(
            'bmi_sub_total' => 0,
            'status' => 2
        );
        $this->db->update( TBL_BMI, $update, array( 'bm_id' => $id ) );
        
        $update = array(
            'bm_amount' => 0,
            'bm_paid_amount' => 0,
            'del_reason' => $hidden_del_reason,
            'status' => 2
        );
        $this->db->update( TBL_BM, $update, array( 'id' => $id ) );
        
    }
    
    function ajax() {
        $post = $this->input->post();
        
        switch( $post['act'] ) :
            case 'booked' :
                
                /*
                 * Get all booked details
                 */
                $where['self.bm_book_status'] = 2;
                $where['self.status'] = 1;
                
                if( !empty( $post['fromDate'] ) ) :
                    $e = explode("-", $post['fromDate']);
                    $where['DATE(self.bm_fn_date) >= '] = $e[2] . '-' . $e[1] . '-' . $e[0]; 
                endif;
                
                if( !empty( $post['toDate'] ) ) :
                    $e = explode("-", $post['toDate']);
                    $where['DATE(self.bm_fn_date) <= '] = $e[2] . '-' . $e[1] . '-' . $e[0]; 
                endif;
                
                if( !empty( $post['period'] ) ) :
                    $where['self.bm_period'] = $post['period']; 
                endif;

                $results = $this->get_all_booked_details( '', $where );
                
            break;    
            
        endswitch;
        
        return $results;
    }
    
    public function service_type_exists($type) {
        $this->db->where('service_id',$type);
        $this->db->where('status !=',2);
        $this->db->order_by('bm_rec_no','desc');
        return $this->db->get(TBL_BM);
    }
    
    public function get_amount_by_service_id($id) {
        $this->db->where('id',$id);
        return $this->db->get(TBL_SERVICE)->row();
    }
    
    public function get_refund_details_by_ids($menu_id,$service_id,$auto_id) {
        $this->db->select('SUM(amount) as refund_amount');
        $this->db->where('menu_id',$menu_id);
        $this->db->where('service_id',$service_id);
        $this->db->where('auto_id',$auto_id);
        $this->db->where('status !=',2);
        return $this->db->get(TBL_REFUND)->row();
    }
    
    public function total_paid_amount($menu,$type) {
        $this->db->select('SUM(pay_amount) as paidAmount');
        $this->db->where('pay_ref_type',$menu);
        $this->db->where('pay_ref_id',$type);
        $this->db->where('status',1);
        return $this->db->get(TBL_PAY)->row();
    }
    
    public function get_prasadam_price($id){
        $this->db->where('id',$id);
        return $this->db->get(TBL_MADAPPALLI)->row();
    }
    
    public function payment_mode_lists() {
        $this->db->where('status',1);
        $this->db->where('menu_id',0);
        return $this->db->get(TBL_PAY_TYPE)->result();
    }
    
    public function get_paid_type($menu,$type,$id) {
        $this->db->select('*,SUM(pay_amount) as pay_amount');
        $this->db->where('pay_ref_type',$menu);
        $this->db->where('pay_ref_id',$type);
        $this->db->where('pay_type_id',$id);
        $this->db->where('status',1);
        $this->db->group_by('pay_type_id');
        return $this->db->get(TBL_PAY)->row();
    }
    
    public function get_paidID($menu,$type,$id) {
        $this->db->where('pay_ref_type',$menu);
        $this->db->where('pay_ref_id',$type);
        $this->db->where('pay_type_id',$id);
        $this->db->where('status',1);
        return $this->db->get(TBL_PAY)->result();
    }
    
    public function delete_payment_by_paid_id($id) {
        $this->db->where_in('id',$id);
        $this->db->delete(TBL_PAY);
        return $this->db->affected_rows();
    }
}