<?php
namespace WpBookingEvent\payments;
use WpBookingEvent\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 WpBookingEvent\Language\Text;
use WpBookingEvent\payments\WBPayment;
use WpBookingEvent\Registry\Registry;
use WpBookingEventFrontend\app\helpers\ConfigHelper;

defined('_WPBOOKINGEVENT_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;
        }
        $return_url = Factory::getRootUrl()."/wpbookingevent/?view=payment-return&order_id=".$order->id;
        $cancel_url = Factory::getRootUrl()."/wpbookingevent/?view=payment-cancel&order_id=".$order->id;
        $notify_url = Factory::getRootUrl()."/wpbookingevent/?view=payment-notify&order_id=".$order->id;
        $tax_total = '';
        $discount_total = '';
        $this->payment_params->debug=true;
        $debug = $this->payment_params->debug;
        $this->currency=new \stdClass();
        $this->currency->currency_code="USD";
        $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' => $this->currency->currency_code,
            'return' => $return_url,
            'notify_url' => $notify_url,
            'cancel_return' => $cancel_url,
            'undefined_quantity' => '0',
            'test_ipn' => $debug,
            'shipping' => '0',
            'charset' => 'utf-8',
            '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"]=$order_detail->quantity;
        }

        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;
    }
}
