<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class General_Settings extends REF_Controller {
    public function __construct() {
        parent::__construct();
        if ((!empty($this->user_data['role'])) && ($this->user_data['role'] != 3)) {
            show_403_error();
        }
        $this->load->library('upload');
        $this->load->model('general_settings_model', '', TRUE);
    }
    
    public function month_list(){
        $month = array(
            '1' => 'January',
            '2' => 'February',
            '3' => 'March',
            '4' => 'April',
            '5' => 'May',
            '6' => 'June',
            '7' => 'July',
            '8' => 'August',
            '9' => 'September',
            '10' => 'October',
            '11' => 'November',
            '12' => 'December'
        );
        return $month;
    }
    
    public function index() {
        $data = array();
        if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        $data['setting'] = $this->general_settings_model->get_by_id();
        $data['months'] = $this->month_list();
        $data['alt_server'] = get_alt_server(true, true);
        
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $data['setting']->id;
        $data['view_link'] = $actions['view'];
        $data['edit_link'] = $actions['index'];
        
        $this->render($data, 'general_settings/edit');
    }
    
    public function update($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $settings = array(
            'year_end_month' => $this->input->post('year_end_month'),
            'gst' => $this->input->post('gst'),
            'prefix' => $this->input->post('prefix'),
            'kiosk_availability' => $this->input->post('kiosk_availability'), // Counter Availability
            'scan_availability' => $this->input->post('scan_availability'), // Kiosk (scan) Availability
            'num_pad' => $this->input->post('num_pad'),
            'is_category' => $this->input->post('archanai_cat'),
            'otp_contact_no' => $this->input->post('otp_contact_no'),
            'sync_url' => $this->input->post('sync_url'),
            'updated_on' => date('Y-m-d H:i:s'),
            'updated_by' => $this->user_data['user_id']
        );
        
        if($this->input->post('gst') == 0 || $this->input->post('gst') == '') {
            $this->general_settings_model->reset_service_gst();
        }
        
        // Update Alt. Server settings
        $this->general_settings_model->manipulate();
        
        if ($this->general_settings_model->update($id, $settings) > 0) {
            $this->session->set_flashdata('success', 'General Settings updated successfully');
            
            /* $actions = $this->actions();
            $service_menu_id = 2; //General Settings      
            add_login_details($args = array( 'page_type_id' => '2', 'service_menu_id' => $service_menu_id, 'menu_type' => '2', 'auto_id' => $id)); */
        }
        else 
            $this->session->set_flashdata('error', 'General Settings not updated!');
        
        redirect('general_settings', 'refresh');
    }
    
    public function view() {
        $data = array();
        $data['setting'] = $this->general_settings_model->get_by_id();
        $months = $this->month_list();
        $year_end_month = (!empty($data['setting']->year_end_month)) ? $data['setting']->year_end_month : 0;
        $data['month_name'] = $months[$year_end_month];
        
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $data['setting']->id;
        $data['view_link'] = $actions['view'];
        $data['edit_link'] = $actions['index'];
        
        $this->render($data, 'general_settings/view');
    }  
 
    function readHTML() {
        $url = $_REQUEST['post_url'];
       //$url = 'http://localhost:8080/thiru_sync/api/index.php';
        if(!function_exists("curl_init")) return "cURL extension is not installed";
        if (trim($url) == "") die("@ERROR@");   
        $fields['cmd'] = 'SYNC';
        
        //Check last logs and Sync
        $history_log = $this->general_settings_model->last_sync_history();
        $fields['last_date']='';
        $fields['last_id']='';         
        //Get Master Details to Sync
        $fields['stars'] = $this->general_settings_model->get_stars(); 
        $fields['gods'] = $this->general_settings_model->get_god_names(); 
        $fields['prasadams'] = $this->general_settings_model->get_prasadam(); 
        $fields['payment_types'] = $this->general_settings_model->get_payment_type(); 
        $fields['services'] = $this->general_settings_model->get_service(); 
        $fields['service_menus'] = $this->general_settings_model->get_service_menus();        
        if(!empty($history_log)){
            //Get Master Details to Sync with latest update
            $fields['last_date']= $history_log->log_date_time;
            $fields['last_id'] = $history_log->auto_id;
            $fields['stars'] = $this->general_settings_model->get_stars($history_log->otp_expire_date_time);
            $fields['gods'] = $this->general_settings_model->get_god_names($history_log->otp_expire_date_time); 
            $fields['prasadams'] = $this->general_settings_model->get_prasadam($history_log->otp_expire_date_time); 
            $fields['payment_types'] = $this->general_settings_model->get_payment_type($history_log->otp_expire_date_time); 
            $fields['services'] = $this->general_settings_model->get_service($history_log->otp_expire_date_time); 
            $fields['service_menus'] = $this->general_settings_model->get_service_menus($history_log->otp_expire_date_time);
        }  
        $ch = curl_init();
        //set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
        echo 'Curl failed: ' . curl_error($ch);
        }        
        $resultStatus = curl_getinfo($ch);
        //close connection
        curl_close($ch);
        $header_link = json_decode($result);          
        if($resultStatus['http_code'] == 200) {
            // All Ok            
            if(!empty($header_link)){
                //error_log(print_r($header_link,1));                
                //error_log(print_r($resultStatus,1));   
                
                foreach($header_link->data AS $key => $results){        
                    if($key==0){
                        $log = array(
                            'ip_address' => $this->input->ip_address(),
                            'user_id' =>$this->user_data['user_id'],    
                            'menu_type' =>8,    
                            'service_menu_id' =>15,    
                            'page_type_id' =>8,    
                            'auto_id' => $results->bill->id,    
                            'log_date_time' =>$results->bill->updated_on,    
                            'otp_expire_date_time' =>date('Y-m-d H:i:s'),    
                            'desc' =>'Sync Operation',    
                            'url' =>$resultStatus['url'],    
                            'status' =>1,    
                        );
                        $insert_log = $this->general_settings_model->insert_logs($log);                        
                    }
                    if(!empty($results)){  
                        $check_exists = $this->general_settings_model->check_id_exists($results->bill->id);
                        if(!empty($check_exists)){
                        //Update Bill Prasadam
                            $update_bill = array(
                                 'service_id' => $results->bill->service_id,
                                 'sync_id' => $results->bill->id,
                                 'star_id_1' => $results->bill->star_id_1,
                                 'star_id_2' => $results->bill->star_id_2,
                                 'bp_rec_no' => $check_exists->bp_rec_no,
                                 'bp_fn_date' => $results->bill->bp_fn_date,
                                 'bp_period' => $results->bill->bp_period,
                                 'bp_dev_name_1' => $results->bill->bp_dev_name_1,
                                 'bp_dev_name_2' => $results->bill->bp_dev_name_2,
                                 'bp_tamil_name_1' => $results->bill->bp_tamil_name_1,
                                 'bp_tamil_name_2' => $results->bill->bp_tamil_name_2,
                                 'bp_contact_no' => $results->bill->bp_contact_no,
                                 'bp_email' => $results->bill->bp_email,
                                 'bp_address_1' => $results->bill->bp_address_1,
                                 'bp_address_2' => $results->bill->bp_address_2,
                                 'bp_desc' => $results->bill->bp_desc,
                                 'bp_amount' => $results->bill->bp_amount,
                                 'bp_paid_amount' => $results->bill->bp_paid_amount,
                                 'gst' => $results->bill->gst,
                                 'gst_value' => $results->bill->gst_value,
                                 'bp_pay_status' => $results->bill->bp_pay_status,
                                 'bp_book_status' => $results->bill->bp_book_status,
                                 'status' => $results->bill->status,
                                 'updated_by' => $this->user_data['user_id'],
                                 'updated_on' => date('Y-m-d H:i:s')
                             );
                            $upd_bill_id = $this->general_settings_model->update_bill_prasadam($check_exists->id,$barr);
                            //Inactive previous Items And Payment
                            $inactive = array(
                                'status' => 2,
                                'updated_by' => $this->user_data['user_id'],
                                'updated_on' => date('Y-m-d H:i:s')  
                            );
                            $set_inactive_items = $this->general_settings_model->set_bill_items_inactive($check_exists->id,$inactive);
                            $set_inactive_payment = $this->general_settings_model->set_bill_payment_inactive($check_exists->id,$inactive);
                            if(!empty($check_exists->id)){
                                //Insert Bill Prasadam Items
                                foreach($results->items AS $items){
                                    $items = array(
                                        'bp_id' => $check_exists->id,
                                        'god_id' => $items->god_id,
                                        'prasadam_id' => $items->prasadam_id,
                                        'bpi_qty' => $items->bpi_qty,
                                        'bpi_price' => $items->bpi_price,
                                        'bpi_sub_total' => $items->bpi_sub_total,
                                        'status' => $items->status,
                                        'created_by' => $this->user_data['user_id'],
                                        'created_on' => date('Y-m-d H:i:s') 
                                    );
//                                    error_log(print_r($items,1)); 
                                    $bil_items = $this->general_settings_model->insert_bill_prasadam_items($items);
                                } 
                                 //Insert Bill Prasadam Bill Payment
                                foreach($results->payment AS $payment){
                                    $payment = array(
                                        'pay_ref_type' => $payment->pay_ref_type,
                                        'pay_ref_id' => $check_exists->id,
                                        'pay_type_id' => $payment->pay_type_id,
                                        'pay_amount' => $payment->pay_amount,
                                        'pay_desc' => $payment->pay_desc,
                                        'pay_details' => $payment->pay_details,
                                        'member_card_details' => $payment->member_card_details,
                                        'status' => $payment->status,
                                        'created_by' => $this->user_data['user_id'],
                                        'created_on' => date('Y-m-d H:i:s') 
                                    );
                                    $bil_items = $this->general_settings_model->insert_bill_payment($payment);
//                                    error_log(print_r($items,1)); 
                                } 
                            }                    
                            
                        }else{
                            $last_receipt = $this->general_settings_model->get_last_receipt_bill($results->bill->service_id);
                            $num = $last_receipt->bp_rec_no + 1;
                            $recept = sprintf("%04d", $num);
                            //Insert Bill Prasadam
                            $barr = array(
                                 'service_id' => $results->bill->service_id,
                                 'sync_id' => $results->bill->id,
                                 'star_id_1' => $results->bill->star_id_1,
                                 'star_id_2' => $results->bill->star_id_2,
                                 'bp_rec_no' => $recept,
                                 'bp_fn_date' => $results->bill->bp_fn_date,
                                 'bp_period' => $results->bill->bp_period,
                                 'bp_dev_name_1' => $results->bill->bp_dev_name_1,
                                 'bp_dev_name_2' => $results->bill->bp_dev_name_2,
                                 'bp_tamil_name_1' => $results->bill->bp_tamil_name_1,
                                 'bp_tamil_name_2' => $results->bill->bp_tamil_name_2,
                                 'bp_contact_no' => $results->bill->bp_contact_no,
                                 'bp_email' => $results->bill->bp_email,
                                 'bp_address_1' => $results->bill->bp_address_1,
                                 'bp_address_2' => $results->bill->bp_address_2,
                                 'bp_desc' => $results->bill->bp_desc,
                                 'bp_amount' => $results->bill->bp_amount,
                                 'bp_paid_amount' => $results->bill->bp_paid_amount,
                                 'gst' => $results->bill->gst,
                                 'gst_value' => $results->bill->gst_value,
                                 'bp_pay_status' => $results->bill->bp_pay_status,
                                 'bp_book_status' => $results->bill->bp_book_status,
                                 'status' => $results->bill->status,
                                 'created_by' => $this->user_data['user_id'],
                                 'created_on' => date('Y-m-d H:i:s')
                             );
                            $bil_id = $this->general_settings_model->insert_bill_prasadam($barr);
                            if(!empty($bil_id)){
                                //Insert Bill Prasadam Items
                                foreach($results->items AS $items){
                                    $items = array(
                                        'bp_id' => $bil_id,
                                        'god_id' => $items->god_id,
                                        'prasadam_id' => $items->prasadam_id,
                                        'bpi_qty' => $items->bpi_qty,
                                        'bpi_price' => $items->bpi_price,
                                        'bpi_sub_total' => $items->bpi_sub_total,
                                        'status' => $items->status,
                                        'created_by' => $this->user_data['user_id'],
                                        'created_on' => date('Y-m-d H:i:s') 
                                    );
//                                    error_log(print_r($items,1)); 
                                    $bil_items = $this->general_settings_model->insert_bill_prasadam_items($items);
                                } 
                                 //Insert Bill Prasadam Bill Payment
                                foreach($results->payment AS $payment){
                                    $payment = array(
                                        'pay_ref_type' => $payment->pay_ref_type,
                                        'pay_ref_id' => $bil_id,
                                        'pay_type_id' => $payment->pay_type_id,
                                        'pay_amount' => $payment->pay_amount,
                                        'pay_desc' => $payment->pay_desc,
                                        'pay_details' => $payment->pay_details,
                                        'member_card_details' => $payment->member_card_details,
                                        'status' => $payment->status,
                                        'created_by' => $this->user_data['user_id'],
                                        'created_on' => date('Y-m-d H:i:s') 
                                    );
                                    $bil_items = $this->general_settings_model->insert_bill_payment($payment);
//                                    error_log(print_r($items,1)); 
                                } 
                            }
                        }
                    }                            
                }
            }
        } else {
            echo 'Call Failed '.print_r($resultStatus);                         
        }
        $curl = null;
        return utf8_encode($response);      
    } 
    
    public function truncate_billing_table() {
        ini_set('max_execution_time', 300);
        $data = $this->general_settings_model->truncate_billing_table();
        echo json_encode($data);
    }
}
?>