<?php
/**
 * Liqpay Payment Module
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * @category        Liqpay
 * @package         Payment
 * @version         3.0
 * @author          Liqpay
 * @copyright       Copyright (c) 2014 Liqpay
 * @license         http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 *
 * EXTENSION INFORMATION
 *
 * OpenCart         1.5.6
 * LiqPay API       https://www.liqpay.com/ru/doc
 *
 */

/**
 * Payment method liqpay controller (catalog)
 *
 * @author      Liqpay <support@liqpay.com>
 */
class ControllerPaymentLiqpay extends Controller
{
    public function index()
    {
        $this->load->model('checkout/order');
        $json = array();

        if (!isset($this->request->post['order_id']) OR !isset($this->request->post['amount'])) {

            $json['error'] = 'Не все параметры';
            $this->response->setOutput(json_encode($json));

        }elseif (((int)$this->request->post['amount'])<=0){


            $json['error'] = 'Пожалуйста, введите корректно сумму платежа';
            $this->response->setOutput(json_encode($json));
        }else{
            $order_id = (int)$this->request->post['order_id'];
            $payment = (int)$this->request->post['amount'];
            $percent=($payment/100)*2.75;//(1000/100)*2.75=1027.5
            $new_payment=$payment+$percent;
            $product_id = (int)$this->request->post['payment_id'];
            if(isset($this->request->post['user'])){
                $user_id=$this->request->post['user'];
            }else{
                $user_id=0;
            }
            $last_order_id=$order_id;
            //$data['order_id'] = $order_id;

            $order_info = $this->model_checkout_order->getOrder($order_id);
            $today = date('Y-m-d');
            $this->load->model('checkout/order');
            $order_product_id=$this->model_checkout_order->addOrderProducts2($order_id, $payment, $today,$product_id,0,$user_id);

            $description = 'Оплата по заказу №' .  $last_order_id . ' Пользователь: ' . mb_convert_encoding($order_info['firstname'], 'utf-8', mb_detect_encoding($order_info['firstname'])) . ' ' . mb_convert_encoding($order_info['lastname'], 'utf-8', mb_detect_encoding($order_info['lastname']));
            $description_ = '#' .  $last_order_id. '#'. $product_id.'#'.$order_product_id.'#'.$new_payment;

            $order_id .= '#'.time();

            $result_url = $this->url->link('account/order/info&order_id=' . $order_id);


            $server_url = $this->url->link('payment/liqpay/server', '', 'SSL');

            $private_key = $this->config->get('liqpay_private_key');
            $public_key = $this->config->get('liqpay_public_key');
            $type = 'buy';
            $currency = $order_info['currency_code'];
            if ($currency == 'RUR') { $currency = 'RUB'; }
            $amount = $this->currency->format(
                $order_info['total'],
                $order_info['currency_code'],
                $order_info['currency_value'],
                false
            );

            $version  = '3';
            //$language = $this->language->get('code');


            //$language = $language == 'ru' ? 'ru' : 'en';
            $pay_way  = $this->config->get('liqpay_pay_way');
            $language = $this->config->get('liqpay_language');

            $send_data = array('version'    => $version,
                'public_key'  => $public_key,
                'amount'      => $new_payment,
                'action'      => 'pay',
                'currency'    => $currency,
                'real_amount'     => $payment,
                'description' => $description,
                'last_order_id' => $last_order_id,
                'order_id'    => $description_,
                'last_product_id'    => $product_id,
                'last_order_product_id'    => $order_product_id,
                'type'        => $type,
 //               'sandbox'		=> 1,	/* ТЕСТОВЫЙ РЕЖИМ ПЛАТЕЖЕЙ */
                'language'    => $language,
                'server_url'  => $server_url,
                'result_url'  => $result_url);
            if(isset($pay_way)){
                $send_data['pay_way'] = $pay_way;
            }
            $data['data'] = base64_encode(json_encode($send_data));

            $data['signature'] = base64_encode(sha1($private_key.$data['data'].$private_key, 1));

            $data['action']         = $this->config->get('liqpay_action');
            $data['button_confirm'] = 'Оплатить';
            $data['url_confirm']    = $this->url->link('payment/liqpay/confirm');

            $this->template = $this->config->get('config_template').'/template/payment/liqpay.tpl';

            if (!file_exists(DIR_TEMPLATE.$this->template)) {
                $this->template = 'payment/liqpay.tpl';
            }


            $json['success'] = ($this->load->view($this->template, $data));
        }
        //$this->response->setOutput(json_encode($json['success']));

        echo (json_encode($json));
        die;
    }

    public function confirm()
    {
        $this->load->model('checkout/order');
        $order = $this->session->data['order_id'];
        //$this->model_checkout_order->confirm($order, $this->config->get('config_order_status_id'), 'unpaid');
        $this->model_checkout_order->confirm($this->session->data['order_id'], 2);
    }

    private function getPosts()
    {
        $success =
            isset($_POST['data']) &&
            isset($_POST['signature']);

        if ($success) {
            return array(
                $_POST['data'],
                $_POST['signature'],
            );
        }
        return array();
    }

    public function getRealOrderID($order_id)
    {
        $real_order_id = explode('#', $order_id);
        return $real_order_id[0];
    }

    public function server()
    {

        if (!$posts = $this->getPosts()) {

            die('Posts error'); }

        list(
            $data,
            $signature
            ) = $posts;

        if(!$data || !$signature) {
            die("No data or signature");}

        $parsed_data = json_decode(base64_decode($data), true);
        $received_public_key = $parsed_data['public_key'];
        $order_id            = $parsed_data['order_id'];
        $status              = $parsed_data['status'];

        $real_order_id = explode('#', $order_id );
        if($real_order_id[1] AND $real_order_id[2] AND $real_order_id[3] AND $real_order_id[4]){
            $real_total = $real_order_id[4];
            $real_order_product_id = $real_order_id[3];
            $real_product_id = $real_order_id[2];
            $real_order_id = $real_order_id[1];
        }
        if ($real_order_id <= 0) {
            die("Order_id real_order_id < 0"); }

        $this->load->model('checkout/order');
        if (!$this->model_checkout_order->getOrder($real_order_id)) {

            die("Order_id fail");}

        $order_info=$this->model_checkout_order->getOrder($real_order_id);

        $private_key = $this->config->get('liqpay_private_key');
        $public_key  = $this->config->get('liqpay_public_key');
        $generated_signature = base64_encode(sha1($private_key.$data.$private_key, 1));

        if ($signature  != $generated_signature) {
            die("Signature secure fail"); }
        if ($public_key != $received_public_key) {
            die("public_key secure fail"); }

        $add=
            '<br>amount '.$parsed_data['amount'].$parsed_data['currency'].
            '<br>transaction_id '.$parsed_data['transaction_id'].
            '<br>description '.$parsed_data['description'].
            '<br>sender_phone '.$parsed_data['sender_phone'];
        if ($status == 'success') {
        //if ($status == 'sandbox') {
            $drs = $this->model_checkout_order->getAllTotalsFromOrder($real_order_id);

            $sub_total = 0;
            $sub_total2 = 0;
            $sub_total3 = 0;
            $total=0;
            foreach ($drs as $dr) {

                if ($dr['code'] == 'sub_total') {
                    $sub_total = $dr['value'];
                } elseif ($dr['code'] == 'sub_total2') {
                    $sub_total2 = $dr['value'];
                } elseif ($dr['code'] == 'sub_total3') {
                    $sub_total3 = abs($dr['value']);
                } elseif ($dr['code']=='total'){
                    $total=abs($dr['value']);
                }

            }

            if($sub_total3>0){

                $s = ($sub_total + $sub_total2) / $sub_total3;

            }else{
                if($real_total>=$total){
                    $s=1;
                }else{
                $s = 0;
                }
            }

           // file_put_contents('liqpay5', chr(13).chr(10).date('Y-m-s H:i:s').chr(9). serialize($s.'-'.$sub_total.'-'.$sub_total2) , FILE_APPEND | LOCK_EX);
            $this->load->model('extension/total/total');
            if(!in_array($order_info['order_status_id'],[1,17,19,20,7,5])){
                $this->model_checkout_order->addOrderHistory($real_order_id,$order_info['order_status_id'],'Гость оплатил через LiqPay.'.$add,1);
                $this->model_checkout_order->confirmStatusProduct($real_order_product_id);
            }elseif($s>=1){
                $this->model_checkout_order->addOrderHistory($real_order_id,20,'Гость оплатил через LiqPay.'.$add,1);
                $this->model_checkout_order->confirmStatusProduct($real_order_product_id);
            }elseif($s>=0.50){
                $this->model_checkout_order->addOrderHistory($real_order_id,19,'Гость оплатил через LiqPay.'.$add,1);
                $this->model_checkout_order->confirmStatusProduct($real_order_product_id);
            }elseif($order_info['order_status_id'] == 5 OR $order_info['order_status_id'] == 7){
                $this->model_checkout_order->addOrderHistory($real_order_id,2,'Гость оплатил через LiqPay.'.$add,1);
                $this->model_checkout_order->confirmStatusProduct($real_order_product_id);
            }else{
                $this->model_checkout_order->addOrderHistory($real_order_id,17,'Гость оплатил через LiqPay.'.$add,1);
                $this->model_checkout_order->confirmStatusProduct($real_order_product_id);
            }

            $this->model_checkout_order->updateDate($real_order_id);

        }else{
            $this->model_checkout_order->addOrderHistory($real_order_id,17,'LiqPay вернула статус '.$status.$add,1);
        }
        $this->session->data['api_id']=1;
        $this->request->get['order_id']=$real_order_id;
        $this->load->controller('api/order/recalc_total');
    }
}

