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

class WithoutAuthPay extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // ($this->verify_min_level(1)) ? '' : redirect('login');
        $this->lang->load("app", "english");
        $this->load->model("examples/Examples_model");
        $this->load->helper('url');
    }

    public function pendingPayment()
    {
        $userId = isset($_GET['id']) ? $_GET['id'] : '';
        if($userId > 0)
        {
            $applicationId = $this->mcommon->specific_row_value('applications', array('user_id' => $userId), 'id');
            if($applicationId != '')
            {
                $paymentmode = $this->mcommon->specific_row_value('accomodation_info', array('application_id' => $applicationId), 'payment_mode');
                if( $paymentmode==1){
        
                    $this->sendPaymentRequest($applicationId);
                }else {    
                    $this->session->set_flashdata('alert_success', ' Application submitted successfully!');
                    redirect('ApplicationController');    
                }
            }
            
        }
    }


    public function sendPaymentRequest($applicationId)
    {

        // $this->db->select('*, applications.id as appid, course.course_name as course_name, applications.status as apstatus');
        // $this->db->from('applications');
        // $this->db->join('course', 'course.id = applications.course_id', 'left');
        // $this->db->join('users', 'users.user_id = applications.user_id');
        // $this->db->join('accomodation_info as ai', 'ai.application_id = applications.id');
        // $this->db->where('applications.id', $applicationId);
        // $query  = $this->db->get();

        // $applicationdatas  = $query->result();

        $applicationdatas = $this->mcommon->specific_row('applications', array('id' => $applicationId));
        $userId = $this->mcommon->specific_row_value('applications', array('id' => $applicationId), 'user_id');

        $mercentData = '';
        $redirecturl = base_url('WithoutAuthPay/getResponse');
        $name = $applicationdatas['first_name'] . ' ' . $applicationdatas['last_name'];
        $pincode = $applicationdatas['pincode']; //$this->input->post('pincode');
        $mobile = $applicationdatas['mobile']; //$this->input->post('mobile');
        $email = $applicationdatas['email']; //$this->input->post('email');
        $address = $applicationdatas['communication_address']; //$this->input->post('address');
        $city = $applicationdatas['city']; //$this->input->post('city');
        $state = $applicationdatas['state']; //$this->input->post('state');
        $country = $applicationdatas['cuntry']; // $this->input->post('country');
        $amount = '2360';

        // echo "<pre>";
        // print_r($country);
        // print_r($applicationdatas);exit;
        $this->input->post('total');
        // $cartData = json_encode($this->cart->contents());
        $orderid =  $this->mcommon->specific_row_value('users', array('user_id' => $userId), 'reference_no');
        $lang = "EN"; // LANGUAGE;
        $currency = "INR"; // CURRENCY;
        $mid = 3263461; // MERCENT_ID;
        $working_key = "BEA0A965C47EBC0FE7C5A6CD95942883"; // WOKRING_KEY;  //Shared by CCAVENUES
        $access_code = "AVVT61LB21BE03TVEB"; //ACCESSCODE;   //Shared by CCAVENUES
        $merchID = '3263461';
        $mercentData .= 'name=' . urlencode($name) . '&amount=' . urlencode($amount) . '&merchant_id=' . urlencode($mid) .
            '&order_id=' . urlencode($orderid) . '&currency=' . urlencode($currency) . '&redirect_url=' . urlencode($redirecturl) .
            '&cancel_url=' . urlencode($redirecturl) . '&language=' . urlencode($lang) . '&billing_name=' . urlencode($name) .
            '&billing_address=' . urlencode($address) . '&billing_country=' . urlencode($country) .
            '&billing_state=' . urlencode($state) . '&billing_city=' . urlencode($city) . '&billing_zip=' . urlencode($pincode) .
            '&billing_tel=' . urlencode($mobile) . '&billing_email=' . urlencode($email) . '&delivery_name=' . urlencode($name) .
            '&delivery_address=' . urlencode($address) . '&delivery_city=' . urlencode($city) .
            '&delivery_state=' . urlencode($state) . '&delivery_zip=' . urlencode($pincode) . '&delivery_country=' . urlencode($country) .
            '&delivery_tel=' . urlencode($mobile) . '&'
            . 'merchant_param1=' . urlencode($applicationId) . '&' . 'merchant_param2=' . urlencode('') . '&' . 'merchant_param3=' . urlencode('') . '&' . 'merchant_param4=' . urlencode($userId) . '&' . 'merchant_param5=' . urlencode('');
        $this->load->library('crypto');
        // echo "<pre>";print_r($mercentData);exit;
        $encrypted_data = $this->crypto->encrypt($mercentData, $working_key); ?>
        <form method="post" name="redirect" action="https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction">
            <?php
            echo "<input type=hidden name=encRequest value=$encrypted_data>";
            echo "<input type=hidden name=access_code value=$access_code>";
            ?>
        </form>
        </center>
        <script language='javascript'>
            document.redirect.submit();
        </script>
        </body>

        </html>

<?php
    }


    public function getResponse()
    {


        $this->load->library('crypto');
        $workingKey = "BEA0A965C47EBC0FE7C5A6CD95942883";
        $encResponse = $_POST["encResp"];
        $rcvdString = $this->crypto->decrypt($encResponse, $workingKey);
        // $order_status = "";
        $decryptValues = explode('&', $rcvdString);
        $dataSize = sizeof($decryptValues);
        $dataArray = $result = [];

        for ($i = 0; $i < $dataSize; $i++) {
            $information = explode('=', $decryptValues[$i]);
            $result[$information[0]] = urldecode($information[1]);
        }


        $view['message'] = $view['alert'] = '';
        if ($result['order_status'] === "Success") {

            $this->storeRecords($result);
            $view['message'] = "Thank you for shopping with us. Your credit card has been charged and your transaction is successful. We will be shipping your order to you soon.";
            $view['alert'] = 'alert_success';
            $redirecturl_success = 'https://asianmedia.org.in/';
            redirect($redirecturl_success);
        } else if ($result['order_status'] === "Aborted") {

            $this->storeRecords($result);
            $view['message'] = "Thank you for shopping with us.We will keep you posted regarding the status of your order through e-mail";
            $view['alert'] = 'alert_warning';
            redirect('logout');
        } else if ($result['order_status'] === "Failure") {
            exit('failure');
            $this->storeRecords($result);
            $view['message'] = "Thank you for shopping with us.However,the transaction has been declined.";
            $view['alert'] = 'alert_danger';
            redirect('login');
        } else {
            $view['message'] = "Security Error. Illegal access detected";
            $view['alert'] = 'alert_danger';
        }
    }

    public function storeRecords($result)
    {
        $userId = $result['merchant_param4'];
        $applicationId = $this->mcommon->specific_row_value('applications', array('user_id' => $userId), 'id');

        $paymentArray = array(
            'user_id' => $result['merchant_param4'],
            'application_id' => $result['merchant_param1'],
            'order_id' => $result['order_id'],
            'currency' => $result['currency'],
            'amount' => $result['mer_amount'],
            'payment_mode' => $result['payment_mode'],
            'card_name' => $result['card_name'],
            'status_message' => $result['status_message'],
            'payment_status' => $result['order_status'],
            'trans_date' => $result['trans_date'],
            'tracking_id' => $result['tracking_id'],
            'transaction_id' => $result['bank_ref_no'],
        );

        $payment_insert =  $this->mcommon->common_insert('payments', $paymentArray);


        if ($result['order_status'] == "Success") {

            $updateArray1 = array(
                'payment_status'    =>  2,
            );

            $update_payment_status = $this->mcommon->common_edit('applications', $updateArray1, array('id' => $applicationId));
            }

        $this->db->select('*, applications.id as appid, course.course_name as course_name, applications.status as apstatus');
        $this->db->from('applications');
        $this->db->join('course', 'course.id = applications.course_id', 'left');
        $this->db->join('users', 'users.user_id = applications.user_id');
        $this->db->join('accomodation_info as ai', 'ai.application_id = applications.id');
        $this->db->where('applications.id', $applicationId);
        $query  = $this->db->get();
        $applicationdatas  = $query->result();

        $view_data['name'] = $applicationdatas[0]->first_name;
        $view_data['course_id'] = $applicationdatas[0]->course_id;
        $view_data['refno'] = $applicationdatas[0]->reference_no;
        $view_data['userId'] = $userId;

        if ($view_data['course_id'] == 1) {
            $subject = 'Application Form – ACJ Postgraduate Diploma in Integrated Multimedia 
                Journalism';
        } else if ($view_data['course_id'] == 2) {
            $subject =  'Application Form – ACJ-Bloomberg Postgraduate Diploma in Business and 
                Financial Multimedia Journalism';
        } else {
            $subject = 'Application Form – ACJ Postgraduate Diploma Programmes';
        }

        $to_email = $applicationdatas[0]->email;

        if ($result['order_status'] == "Success") {

            $mailtemplate = $this->load->view('acknowledgement/with_payment', $view_data, true);
        } else {

            $mailtemplate = $this->load->view('acknowledgement/without_payment', $view_data, true);
        }
        $this->load->library('email');
        $this->email->set_newline("\r\n");
        $from_email_address = 'acjadmissions@asianmedia.org.in';
        $from_email_name = 'Asian College of Journalism';
        $this->email->from($from_email_address, $from_email_name);
        $this->email->to($to_email);
        $this->email->subject($subject);
        $this->email->message($mailtemplate);
        $this->email->send();
    }

}