<?php
namespace WpBookingHotel\payments;
use WpBookingHotel\Factory;

/**
 * @package    HikaShop for Woobookingpro!
 * @version    2.6.3
 * @author    hikashop.com
 * @copyright    (C) 2010-2016 HIKARI SOFTWARE. All rights reserved.
 * @license    GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */

use WpBookingHotel\Language\Text;
use WpBookingHotel\payments\WBPayment;
use WpBookingHotel\Registry\Registry;
use WpBookingHotelFrontend\app\helpers\ConfigHelper;

defined('_WPBOOKINGHOTEL_EXEC') or die('Restricted access');
?><?php

class WBPaymentPaypal extends WBPayment
{
    var $accepted_currencies = array(
        'AUD', 'BRL', 'CAD', 'EUR', 'GBP', 'JPY', 'USD', 'NZD', 'CHF', 'HKD', 'SGD', 'SEK',
        'DKK', 'PLN', 'NOK', 'HUF', 'CZK', 'MXN', 'MYR', 'PHP', 'TWD', 'THB', 'ILS', 'TRY',
        'RUB'
    );

    var $multiple = true;
    var $debug = false;
    var $name = 'paypal';
    var $doc_form = 'paypal';
    /**
     * @var array
     */
    public $vars;

    function __construct($config)
    {
        parent::__construct($config);
    }

    function onBeforeOrderCreate(&$order, &$do)
    {
        if (parent::onBeforeOrderCreate($order, $do) === true)
            return true;

        if ((empty($this->payment_params->email) || empty($this->payment_params->url)) && $this->plugin_data->payment_id == $order->order_payment_id) {
            $this->app->enqueueMessage('Please check your &quot;PayPal&quot; plugin configuration');
            $do = false;
        }
    }

    function onAfterOrderConfirm(&$order,&$methods=null, $method_id=0)
    {

        if(!isset($this->payment_params) && !isset($this->payment_params->email)){
            echo "please config payment width paypal account";
            return false;
        }
        if (isset($this->currency) && $this->currency->currency_locale['int_frac_digits'] > 2)
            $this->currency->currency_locale['int_frac_digits'] = 2;
        $page_checkout_default= ConfigHelper::get_page_checkout();
        if($page_checkout_default) {
            $this->page_checkout_default = get_page_link($page_checkout_default);
        }else{
            $this->page_checkout_default="";
        }

        $return_url = $this->page_checkout_default.'?order_id='.$order->id.'&page=thanks';
        $cancel_url = $this->page_checkout_default.'?order_id='.$order->id.'&page=cancel';
        $notify_url = '';
        $tax_total = '';
        $discount_total = '';
        $debug = isset($this->payment_params->debug)?$this->payment_params->debug:'';
        if (!isset($this->payment_params->no_shipping))
            $this->payment_params->no_shipping = 1;
        if (!empty($this->payment_params->rm))
            $this->payment_params->rm = 2;

        $vars = array(
            'cmd' => '_ext-enter',
            'redirect_cmd' => '_cart',
            'upload' => '1',
            'business' => $this->payment_params->email,
            'receiver_email' => $this->payment_params->email,
            'invoice' => $order->id,
            'currency_code' => isset($this->currency->currency_code)?$this->currency->currency_code:'',
            'return' => $return_url,
            'notify_url' => $notify_url,
            'cancel_return' => $cancel_url,
            'undefined_quantity' => '0',
            'test_ipn' => $debug,
            'shipping' => '0',
            'no_shipping' => isset($this->payment_params->no_shipping)?$this->payment_params->no_shipping:'',
            'no_note' => isset($this->payment_params->notes)?!$this->payment_params->notes:'',
            'charset' => 'utf-8',
            'rm' => isset($this->payment_params->rm)?(int)$this->payment_params->rm:'',
            'bn' => 'HikariSoftware_Cart_WPS'
        );

        $list_order_detail=$order->list_order_detail;
        $i=1;
        foreach ($list_order_detail as $order_detail){
            $vars["item_name_$i"]=$order_detail->id;
            $vars["amount_$i"]=$order_detail->total;
            $vars["quantity_$i"]=1;
        }

        if (!empty($this->payment_params->cpp_header_image)) {
            $vars['cpp_header_image'] = $this->payment_params->cpp_header_image;
        }
        if (empty($this->payment_params->url))
            $this->payment_params->url = 'https://www.paypal.com/cgi-bin/webscr';
        $debug=$this->debug;
        if($debug==1){
            $this->payment_params->url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
        }

        $vars['item_name']=$order->id;
        $vars['amount']=$order->total;
        $vars['currency_code']="USD";
        $this->vars = $vars;

        return $this->showPage('end');
    }


    function onPaymentConfiguration(&$element)
    {
        $subtask = JRequest::getCmd('subtask', '');
        if ($subtask == 'ips') {
            $ips = null;
            echo (implode(',', $this->_getIPList($ips)));
            exit;
        }

        parent::onPaymentConfiguration($element);
        $this->address = hikashop_get('type.address');

        if (empty($element->payment_params->email)) {
            $app = JFactory::getApplication();
            $lang = JFactory::getLanguage();
            $locale = strtolower(substr($lang->get('tag'), 0, 2));
            $app->enqueueMessage(Text::sprintf('ENTER_INFO_REGISTER_IF_NEEDED', 'PayPal', Text::_('HIKA_EMAIL'), 'PayPal', 'https://www.paypal.com/' . $locale . '/mrb/pal=SXL9FKNKGAEM8'));
        }
    }

    function onPaymentConfigurationSave(&$element)
    {
        if (!empty($element->payment_params->ips))
            $element->payment_params->ips = explode(',', $element->payment_params->ips);

        if (strpos($element->payment_params->url, 'https://') === false) {
            $app = JFactory::getApplication();
            $app->enqueueMessage('The URL must start with https://');
            return false;
        }

        return true;
    }

    function getPaymentDefaultValues(&$element)
    {
        $element->payment_name = 'PayPal';
        $element->payment_description = 'You can pay by credit card or paypal using this payment method';
        $element->payment_images = 'MasterCard,VISA,Credit_card,PayPal';

        $element->payment_params->url = 'https://www.paypal.com/cgi-bin/webscr';
        $element->payment_params->notification = 1;
        $element->payment_params->ips = '';
        $element->payment_params->details = 0;
        $element->payment_params->invalid_status = 'cancelled';
        $element->payment_params->pending_status = 'created';
        $element->payment_params->verified_status = 'confirmed';
        $element->payment_params->address_override = 1;
    }

    function _getIPList(&$ipList)
    {
        $hosts = array(
            'www.paypal.com',
            'notify.paypal.com',
            'ipn.sandbox.paypal.com'
        );

        $ipList = array();
        foreach ($hosts as $host) {
            $ips = gethostbynamel($host);
            if (!empty($ips)) {
                if (empty($ipList))
                    $ipList = $ips;
                else
                    $ipList = array_merge($ipList, $ips);
            }
        }

        if (empty($ipList))
            return $ipList;

        $newList = array();
        foreach ($ipList as $k => $ip) {
            $ipParts = explode('.', $ip);
            if (count($ipParts) == 4) {
                array_pop($ipParts);
                $ip = implode('.', $ipParts) . '.*';
            }
            if (!in_array($ip, $newList))
                $newList[] = $ip;
        }
        return $newList;
    }
}
