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

class Order_payment extends MAIN_Controller
{
    /*
     *  //validate change order payment status
        //unpaid
        //paid
        //cash on delivery
        //refunded
     */

    const PAYMENT_STATUS = array(
        "unpaid"=>array(
            'label' => 'unpaid',
            'color' => '#e0b50b'
        ),
        "paid"=>array(
            'label' => 'paid',
            'color' => '#06962e'
        ),
        "cod"=>array(
            'label' => 'cod',
            'color' => '#076bb7'
        ),
        "cod_paid"=>array(
            'label' => 'cod_paid',
            'color' => '#06962e'
        ),
        "refunded"=>array(
            'label' => 'refunded',
            'color' => '#d30000'
        ),
        "transferBankPaid"=>array(
            'label' => 'Transfer Received',
            'color' => '#06962e'
        ),
        "transferBank"=>array(
            'label' => 'Bank Transfer',
            'color' => '#076bb7'
        ),
    );

    public function __construct()
    {
        parent::__construct();
        $this->init('order_payment');
    }


    public function onLoad()
    {
        parent::onLoad(); // TODO: Change the autogenerated stub

        $this->load->model("order_payment/order_payment_model","mOrderPayment");

    }

    public function link_call(){

        $link = RequestInput::get("redirect");
        $token = RequestInput::get("token");

        $token = TokenSetting::get_by_token($token,"logged");

        if($token!=NULL){
            $this->mUserBrowser->refreshData($token->uid);
            redirect(base64_decode($link));
        }

        redirect("order_payment/payment_error");

    }

    public function onCommitted($isEnabled)
    {
       if(!$isEnabled)
           return;

        //setup payment
        if(ModulesChecker::isEnabled("payment")){

            $payment_redirection = site_url("payment/make_payment");
            $payment_callback_success = site_url("order_payment/payment_done");
            $payment_callback_error = site_url("order_payment/payment_error");

            $payments = PaymentsProvider::getDefault();

            PaymentsProvider::provide("order_payment",$payments,
                $payment_redirection,
                $payment_callback_success,
                $payment_callback_error
            );

            //plug new payment method apple pay
            PaymentsProvider::plug_payment_method("order_payment",  array(
                'id'=> PaymentsProvider::APPLE_PAY,
                'payment'=> _lang('Credit Card'),
                'image'=> AdminTemplateManager::assets("payment","img/apple-pay.png"),
                'description'=> 'Pay using credit card'
            ),true);

        }
    }



    public function payment_done(){

        $id = intval(RequestInput::get("invoiceid"));
        $paymentMethodId = intval(RequestInput::get("mp"));
        $method = Text::input(RequestInput::get("method"));
        $transaction = Text::input(RequestInput::get("paymentId"));
        $key = Text::input(RequestInput::get("key"));

        $payerID = Text::input(RequestInput::get("PayerID"));
        $paymentId = Text::input(RequestInput::get("paymentId"));
        $token = Text::input(RequestInput::get("token"));


        if($paymentMethodId == 0){
            $paymentMethodId = PaymentsProvider::findIdByKey($method);
        }


        foreach (PaymentsProvider::getPayments("order_payment") as $payment){

            //check and change paypal status
            if($payment['id'] == $paymentMethodId && $payment['id'] == PaymentsProvider::PAYPAL_ID){
                $params = array(
                    'paymentId' => $paymentId,
                    'payerID' => $payerID,
                    'token' => $token
                );
                $result = Modules::run('payment/paypal/getPaymentStatus',$params);
                if(!$result)
                    break;
            }


            if($payment['id'] == $paymentMethodId && $payment['id'] == PaymentsProvider::COD_ID){
                break;
            }

            if($payment['id'] == $paymentMethodId && $payment['id'] == PaymentsProvider::BANK_TRANSFER){
                break;
            }


            //change status of internal invoice
            if($payment['id'] == $paymentMethodId){

                $this->mPaymentModel->updateInvoice($id,$method,$transaction,$key);
                $data['title'] = _lang("Payment done");
                $this->load->view("payment/client_view/html/success",$data);

                //redirect to alternative callback
                $callbackAltSuccess = Text::input(RequestInput::get("callbackAltSuccess"));
                if($callbackAltSuccess != ""){
                    redirect($callbackAltSuccess);
                }

                return;

            }

        }


        $callbackAltSuccess = Text::input(RequestInput::get("callbackAltSuccess"));
        if($callbackAltSuccess != ""){
            redirect($callbackAltSuccess);
        }else{
            $data['title'] = _lang("Payment done");
            $this->load->view("payment/client_view/html/success",$data);
        }
    }



    public function payment_success($args){

        if(isset($args['invoiceId']) && $args['invoiceId'] > 0){

            $user_id = SessionManager::getData("id_user");

            $this->db->where("user_id",$user_id);
            $this->db->where("module","order_payment");
            $this->db->where("id",intval($args['invoiceId']));

            $invoice = $this->db->get('invoice',1);
            $invoice = $invoice->result();

            if(isset($invoice[0])){
                $method = $invoice[0]->method;

                if($method == PaymentsProvider::COD_ID or $method == "cod"){
                    $this->mOrderPayment->updateOrderPaymentStatus($invoice[0],"cod");
                }else if($method == PaymentsProvider::BANK_TRANSFER or $method == "transferBank"){
                    $this->mOrderPayment->updateOrderPaymentStatus($invoice[0],"transferBank");
                }else{
                    $this->mOrderPayment->updateOrderPaymentStatus($invoice[0],"paid");
                }
                //send notification
                @$this->sendNotification($args['invoiceId']);
            }
            return TRUE;
        }

        return FALSE;
    }



    public function sendNotification($invoiceId){

        $invoice = $this->mPaymentModel->getInvoice($invoiceId);
        $order_id = $invoice->module_id;
        @$this->mOrderModel->sendOderDetailToBO($order_id);

    }

    public function payment_error(){

        $invoice_id = intval(RequestInput::get("invoiceid"));
        $user_id = SessionManager::getData("id_user");

        if( $invoice_id > 0){

            $user_id = SessionManager::getData("id_user");

            $this->db->where("user_id",$user_id);
            $this->db->where("module","order_payment");
            $this->db->where("id",intval($invoice_id));

            $invoice = $this->db->get('invoice',1);
            $invoice = $invoice->result();

            if(isset($invoice[0])){
                $this->mOrderPayment->updateOrderPaymentStatus($invoice[0],"unpaid");
            }

        }

        $this->load->view("payment/client_view/html/error",NULL);
    }

    public function onUpgrade()
    {

        return TRUE;
    }

    public function onInstall()
    {

        return TRUE;
    }


}