<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Payment extends MY_Controller {

    var $thispage;
    var $payment_method;

    public function __construct() {
        parent::__construct();

        if (!get_system_status()) {
            echo $this->load->view('site/system_off', '', TRUE);
            die();
        }
        $this->thispage = "payment";
        $this->operator_id = $this->session->userdata('operator_id');
        $this->load->model('admin/Payment_model');
    }

    public function pay($order_id, $pay_order = 0) {
        $sett = $this->Payment_model->get_payment_sett();
        if (!$sett || !$sett->status) {
            echo '<h2 style="text-align:center;margin-top:20px">' . $this->lang->line('payment_sett_not_set') . '<h2/>';
            die;
        }
        if ($sett->status) {

            redirect(base_url('Payment/prepay/' . $order_id . '/' . $pay_order));
        }
    }

    public function prepay($order_id, $pay_order = 0) {

        $order_id = base64_decode(urldecode($order_id));
        if ($pay_order) {
            $pay_order = base64_decode(urldecode($pay_order));
        }
        $data['order_id'] = $order_id;
        if ($pay_order == 0) {
            $data['order'] = $this->Payment_model->get_order($order_id);
            if ($data['order']->paid == 1) {
                echo 'This order is already Paid';
                return;
            }
            if ($data['order']->order_status == 5) {
                echo 'This order is canceled';
                return;
            }
            $data['order_details'] = $this->Payment_model->get_order_details($order_id);
        } else {
            $data['order'] = $this->Payment_model->get_payment_order($order_id);
            if (!$data['order']) {
                echo "Can't find this pay order";
                return;
            }
            if ($data['order']->payment_time != NULL) {
                echo 'This order is already Paid';
                return;
            }
        }

        $data['sett'] = get_setting();
        $data['payment_sett'] = $this->Payment_model->get_payment_sett();
        if ($data['payment_sett']->type == 1) {
            $this->payment_method = 'tap';
        }
        if ($data['payment_sett']->type == 2) {
            $this->payment_method = 'knet';
        }
        $this->load->view('site/prepay', $data);
    }

    // ========= Start knet payment gateway ==========
    function get_knet_config() {
        $sett = $this->Payment_model->get_payment_sett();
        $config = array(
            "TRANSPORTAL_ID" => $sett->knet_transportal_id, // Transportal ID
            "TRANSPORTAL_PASSWORD" => $sett->knet_transportal_password, // Transportal password
            "TERMINAL_RESOURCE_KEY" => $sett->knet_terminal_resource_key, // Terminal resource key
            "TERMINAL_URI" => $sett->knet_testing_env ? "https://kpaytest.com.kw" : "https://kpay.com.kw", // Terminal URI, "https://kpaytest.com.kw" for testing, "https://kpay.com.kw" for production
            "CURRENCY" => "414", // "414" for KWD
            "DECIMALS" => "3", // "3" decimals as 0.000
            "LISTEN_URI" => base_url() . "payment/listen", // LISTEN_URI
            "COMPLETE_URI" => base_url() . "payment/complate", // COMPLETE_URI
            "ACTION" => "1", // Keep 1
            "DEBUG" => FALSE, // TRUE for debugging, FALSE for live. Better to start with a DEBUG MODE, set it to TRUE.
        );
        return $config;
    }

    function knet_pay($amount, $order_id, $pay_order) {
        $config = $this->get_knet_config();
        $this->load->library('KNET', $config);
        $this->knet->init();

        // Confirm valid setup
        if (!$this->knet->valid()) {
            // Setup is invalid
            echo "Error: Configurations are not valid.";
        } else {
            $t = array(
                "AMOUNT" => $amount,
                "LANGUAGE" => "ARA",
                "USER_DEFINED_VAR_1" => $order_id,
                "USER_DEFINED_VAR_2" => $pay_order,
//                "USER_DEFINED_VAR_3" => "User_defined_variable_3",
//                "USER_DEFINED_VAR_4" => "User_defined_variable_4"
            );

            // Create a payment
            $p = $this->knet->create($t);

            // Confirm valid payment creation
            if ($p["STATUS"] != "success") {
                // Creation is invalid
                echo "Error: " . $p["DESCRIPTION"];
            } else {
//                // Creation is valid
                if ($pay_order == 0) {
                    $this->db->update('orders', array('TRACKING_ID' => $p["TRACKING_ID"]), array('id' => $order_id));
                } else {
                    $this->db->update('payment_orders', array('TRACKING_ID' => $p["TRACKING_ID"]), array('id' => $order_id));
                }

                if ($this->knet->start()) {
                    // Payee is sent to payment gateway
                    // Do not add any code here!
                } else {
                    // Payment URI is invalid
                    echo "Error: Payment URI is invalid.";
                }
            }
        }
    }

    public function listen() {

        $config = $this->get_knet_config();

        // Define
        $k = $this->load->library('KNET', $config);
        // Initialize
        $this->knet->init();
        // Confirm valid setup
        if (!$this->knet->valid()) {
            // Setup is invalid
            //echo "Error: Configurations are not valid.";	
        } else {
            // Setup is valid
            // Listen to gateway
            $r = $this->knet->listen();
            $order_id = $r['USER_DEFINED_VAR_1'];
            // update payment details in case of fail or success
            if ($r['USER_DEFINED_VAR_2'] == 0) {
                $order = $this->db->get_where('orders', array('id' => $order_id))->row();
                if (!$order) {
                    echo 'ERROR! Order not found';
                    return;
                }
                $this->db->update('orders', array('payment_details' => $order->payment_details . '/' . json_encode($r)), array('id' => $order_id));
            } else {
                $order = $this->db->get_where('payment_orders', array('id' => $order_id))->row();
                if (!$order) {
                    echo 'ERROR! Order not found';
                    return;
                }
                $this->db->update('payment_orders', array('payment_details' => $order->payment_details . '/' . json_encode($r)), array('id' => $order_id));
            }
            // if success update as paid
            if ($r["PAYMENT_STATUS"] == 'successful') {

                $update = array('payment_time' => date('Y-m-d H:i:s'), 'payment_method' => 'Knet');

                if ($r['USER_DEFINED_VAR_2'] == 0) {
                    $update['payment_method'] = 3;
                    $this->db->update('orders', $update, array('id' => $order_id));
                    $this->db->update('bills_orders', array('paid' => 1), array('id_orders' => $order_id));
                } else {
                    $this->db->update('payment_orders', $update, array('id' => $order_id));
                }
            }
            $this->session->set_userdata('response', $r);
            // $edit_data = array(
            //'PAYMENT_STATUS' => $r["PAYMENT_STATUS"],
//                'TRANSACTION_ID' => $r["TRANSACTION_ID"],
//                'REFERENCE_ID' => $r["REFERENCE_ID"],
//                'payment_time' => $r["PAYMENT_TIME"],
//                'AUTHORIZATION_ID' => $r["AUTHORIZATION_ID"],
            // );
            // Responding to gateway
            $this->knet->respond();
        }
    }

    public function complate() {

        $data['response'] = $this->session->userdata('response');
        // print_R($data['response']);die;
        $data['knet_gateway'] = 1;
        $order_id = $data['response']['USER_DEFINED_VAR_1'];
        if ($data['response']['USER_DEFINED_VAR_2'] == 0) {
            $data['order'] = $this->Payment_model->get_order($order_id);
        } else {
            $data['order'] = $this->Payment_model->get_payment_order($order_id);
        }
        $data['date'] = date('Y-m-d H:i:s');
//        $this->load->library('email');
//        $to = 'sara.aboelyazied@gmail.com';
//        $subject = $this->config->item('company_title') . '|Payment ' . $data['response']['PAYMENT_STATUS'];
//        $message = '<h1>Payment ' . $data['response']['PAYMENT_STATUS'] . '</h1>'
//                . '<p>Transaction ID: ' . $data['response']['TRANSACTION_ID'] . '</p><br/>'
//                . '<p>Reference num: ' . $data['response']['REFERENCE_ID'] . '</p><br/>'
//                . '<p>Amount: ' . $data['response']['AMOUNT'] . ' KWD</p><br/>'
//                . '<p>Order #: ' . str_pad($data['response']['USER_DEFINED_VAR_1'], 6, "0", STR_PAD_LEFT) . '</p><br/>'
//                . '<p>Payment Time: ' . $data['date'] . '</p><br/>'
//                . 'Thank You';
//
//        $this->email->from('rayid@rayid.org');
//        $this->email->to($to);
//        $this->email->subject($subject);
//        $this->email->message($message);
//        $this->email->set_mailtype("html");
//        $this->email->send();
//            $this->session->set_userdata("email_sent","Congragulation Email Send Successfully.");
//        else
//            $this->session->set_userdata("email_sent","You have encountered an error");
//        $this->load->view('contact_email_form');
//    }

        $this->load->view('site/postpay', $data);
    }

    // ===== END Knet gateway
    // Start tap payment gateway
    function post_pay() {
        $data = array();
        if ($this->session->userdata('response')) {

            $data['response'] = json_decode($this->session->userdata('response'));


            $order_id = $data['response']->callback->reference->order;
            // update payment details in case of fail or success
            if ($data['response']->callback->description == 'Invoice') {
                $order = $this->db->get_where('orders', array('id' => $order_id))->row();
                if (!$order) {
                    echo 'ERROR! Order not found';
                    return;
                }
                $this->db->update('orders', array('payment_details' => $order->payment_details . '/' . json_encode($r)), array('id' => $order_id));
            } else {
                $order = $this->db->get_where('payment_orders', array('id' => $order_id))->row();
                if (!$order) {
                    echo 'ERROR! Order not found';
                    return;
                }
                $this->db->update('payment_orders', array('payment_details' => $order->payment_details . '/' . json_encode($r)), array('id' => $order_id));
            }


            if ($data['response']->callback->acquirer->response->message == 'Approved') {
                $order_id = $data['response']->callback->reference->order;
                $data['pay_time'] = date('Y-m-d H:i:s');
                $update = array('payment_time' => $data['pay_time'], 'payment_method' => $data['response']->callback->source->payment_method,
                    'payment_details' => $this->session->userdata('response'));
                if ($data['response']->callback->description == 'Invoice') {
                    $update['payment_method'] = 3;
                    $this->db->update('orders', $update, array('id' => $order_id));
                    $this->db->update('bills_orders', array('paid' => 1), array('id_orders' => $order_id));
                } else {
                    $this->db->update('payment_orders', $update, array('id' => $order_id));
                }
            }
        }
        $this->load->view('site/postpay', $data);
    }

    function save_response() {
        $this->session->set_userdata('response', json_encode($this->input->post('response')));
    }

    // End tap Payment gateway 

    public function pay_orders() {
        if (!$this->session->has_userdata('is_admin_login')) {
            redirect('auth/login');
        }
        if (!get_ap('pay_orders_module', $this->operator_id) == 1) {
            redirect('', 'refresh');
        }
        $data['sett'] = get_setting();
        $data['title'] = $this->lang->line('pay_orders');
        if ($this->input->post('start_expiry')) {
            $date_arr = explode(' - ', $this->input->post('start_expiry'));
            $from = date('Y-m-d', strtotime($date_arr[0]));
            $to = date('Y-m-d', strtotime($date_arr[1]));
            $this->db->where(array('created_at >=' => $from, 'created_at <=' => $to));
        }
        $data['pay_orders'] = $this->Payment_model->get_pay_orders();
        $data['payment_sett'] = $this->Payment_model->get_payment_sett();

        $this->load->view('site/payment/pay_orders', $data);
    }

    public function add_pay_order() {
        if (!$this->session->has_userdata('is_admin_login')) {
            redirect('auth/login');
        }

        if (!get_ap('add_pay_order', $this->operator_id) == 1) {
            redirect('', 'refresh');
        }
        $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required|numeric');
        $this->form_validation->set_rules('amount', $this->lang->line('phone'), 'trim|required|numeric');

        if ($this->form_validation->run() !== FALSE) {
            $arr = $this->input->post();
            $arr['phone'] = $arr['phone']; //$arr['phone_code'] .
            unset($arr['phone_code']);
            unset($arr['submit']);
            $arr['created_at'] = date('Y-m-d H:i:s');
            $this->db->insert('payment_orders', $arr);
            $pay_id = $this->db->insert_id();
            $this->load->model('admin/User_model');
            $this->User_model->send_sms($pay_id, 'pay_orders');
            redirect(base_url('payment/pay_orders'));
        }

        $data['sett'] = get_setting();
        $data['title'] = $this->lang->line('pay_order');
        $this->load->view('site/payment/add_pay_order', $data);
    }

    function edit_pay_order($id) {
        if (!$this->session->has_userdata('is_admin_login')) {
            redirect('auth/login');
        }
        $data['order'] = $this->Payment_model->get_pay_order($id);
        if (!get_ap('edit_pay_order', $this->operator_id) == 1 || $data['order']->payment_time) {
            redirect('', 'refresh');
        }

        $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required|numeric');
        $this->form_validation->set_rules('amount', $this->lang->line('phone'), 'trim|required|numeric');

        if ($this->form_validation->run() !== FALSE) {
            $arr = $this->input->post();
            unset($arr['submit']);
            $this->db->update('payment_orders', $arr, array('id' => $id));
            $this->load->model('admin/User_model');
            $this->User_model->send_sms($id, 'pay_orders');
            redirect(base_url('payment/pay_orders'));
        }
        $data['sett'] = get_setting();
        $data['title'] = $this->lang->line('pay_order');

        $this->load->view('site/payment/edit_pay_order', $data);
    }

    public function show_pay_order($pay_id) {
        if (!$this->session->has_userdata('is_admin_login')) {
            redirect('auth/login');
        }

        if (!get_ap('pay_orders_module', $this->operator_id) == 1) {
            redirect('', 'refresh');
        }
        $data['title'] = $this->lang->line('pay_order');
        $data['pay_order'] = $this->Payment_model->get_pay_order($pay_id);
        if (!$data['pay_order']) {
            $this->session->set_userdata('error', $this->lang->line('data_not_found'));
            redirect('payment/pay_orders');
        }
        $data['sett'] = get_setting();
        $this->load->view('site/payment/show_pay_order', $data);
    }

    public function del($pay_id) {
        if (!$this->session->has_userdata('is_admin_login')) {
            redirect('auth/login');
        }

        if (!get_ap('delete_pay_order', $this->operator_id) == 1) {
            redirect('', 'refresh');
        }
        $this->db->delete('payment_orders', array('id' => $pay_id));
        redirect('payment/pay_orders');
    }

    public function perform_payment() {
        $this->load->view('site/pay');
    }

    function get_payment_details($order_id) {
        $this->db->select('payment_details');
        $data['order'] = $this->db->get_where('payment_orders', array('id' => $order_id))->row();
        $data['title'] = $this->lang->line('payment_details');
        $data['thispage'] = $this->thispage;
        $this->load->view('site/' . $this->thispage . '/payment_details', $data);
    }

    function show_receipt($order_id) {
        $data['sett'] = get_setting();
        $data['order'] = $this->Payment_model->get_payment_order_details($order_id);
        $data['title'] = $this->lang->line('payment_receipt');
        if (!$data['order']) {
            $this->session->set_flashdata('error', $this->lang->line('data_not_found'));
            redirect(base_url('Payment/pay_orders'));
        }
        $this->load->view('site/orders/receipt', $data);
    }
}
