<?php

namespace Salesloo\Payment_Method;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use \Salesloo\Abstracts\Payment_Method;
use \PayPalCheckoutSdk\Core\PayPalHttpClient;
use \PayPalCheckoutSdk\Core\SandboxEnvironment;
use \PayPalCheckoutSdk\Core\ProductionEnvironment;
use \PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use \PayPalCheckoutSdk\Orders\OrdersCreateRequest;

/**
 * Paypal payment methods
 */
class Paypal extends Payment_Method
{

    /**
     * construction
     */
    public function __construct()
    {
        $this->id              = 'paypal';
        $this->name            = 'Paypal';
        $this->icon_id         = 'https://www.paypalobjects.com/digitalassets/c/website/logo/full-text/pp_fc_hl.svg';
        $this->title           = __('Paypal', 'salesloo');
        $this->description     = __('Pay via PayPal; you can pay with your credit card if you don\'t have a PayPal account.', 'salesloo');
        $this->currency        = 'USD';
        $this->currency_symbol = '$';
        $this->currency_rate   = '';
        $this->enable          = true;
        $this->unique_number   = false;
        $this->instruction     = __('Click button bellow to pay your invoice with paypal', 'salesloo');
    }

    /**
     * 
     */
    public function print_action()
    {

        ob_start();
        salesloo_template_section('payment/paypal-action.php');

        return ob_get_clean();
    }

    private function paypal()
    {
        $clientId = salesloo_get_option('paypal_client_id');
        $clientSecret = salesloo_get_option('paypal_client_secret');
        if (salesloo_get_option('paypal_is_sanbox')) {
            $environment = new SandboxEnvironment($clientId, $clientSecret);
        } else {
            $environment = new ProductionEnvironment($clientId, $clientSecret);
        }

        return new PayPalHttpClient($environment);
    }

    public function handle_action($invoice)
    {
        global $___salesloo;

        $url = salesloo_url_payment(salesloo_vars('__invoice'));

        $merchant_email = salesloo_get_option('paypal_email');

        $summary = $invoice->summary;
        $invoice_id = $invoice->number;

        $total_amount_value = salesloo_convert_price($summary['total']['converted']['value']);

        $items = [];
        foreach ($summary['products'] as $id => $product) {
            $items[] = [
                'name' => $product['label'],
                'unit_amount' => [
                    'currency_code' => 'USD',
                    'value' => salesloo_convert_price($product['value'])
                ],
                'quantity' => '1',
                'category' => 'DIGITAL_GOODS'
            ];
        }

        if (isset($_GET['pay'])) {

            $input = file_get_contents("php://input");

            $data = json_decode($input, true);

            if (isset($data['__nonce']) && wp_verify_nonce($data['__nonce'], 'paypal-create-order')) {
                $request = new OrdersCreateRequest();
                $request->prefer('return=minimal');
                $request->body = [
                    'intent' => 'CAPTURE',
                    'purchase_units' => [[
                        'reference_id' => salesloo_vars('__invoice'),
                        'amount' => [
                            'value' => $total_amount_value,
                            'currency_code' => 'USD',
                            // 'breakdown' => [
                            //     'item_total' => [
                            //         'currency_code' => 'USD',
                            //         'value' => $total_amount_value,
                            //     ]
                            // ]
                        ],
                        'invoice_id' => $invoice_id,
                        //'items' => $items
                    ]],
                    'application_context' => [
                        'cancel_url' => $url,
                        'return_url' => $url
                    ]
                ];

                try {
                    // Call API with your client and get a response for your call
                    $response = $this->paypal()->execute($request);

                    echo json_encode($response);
                } catch (\HttpException $ex) {
                    echo $ex->getMessage();
                }
                exit;
            }

            echo 'No Access';
            exit;
        }

        if (isset($_GET['token'])) {

            $order_id = sanitize_text_field($_GET['token']);
            $payer_id = sanitize_text_field($_GET['PayerID']);

            $request = new OrdersCaptureRequest($order_id);
            $request->prefer('return=representation');
            try {
                $response = (object) $this->paypal()->execute($request);

                if ($response->statusCode == 201 && $response->result->payer->payer_id == $payer_id) {
                    foreach ($response->result->purchase_units as $purchase_unit) {

                        if ($purchase_unit->payee->email_address == $merchant_email) {
                            foreach ($purchase_unit->payments->captures as $capture) {
                                if ($capture->status == 'COMPLETED' && $capture->amount->value == $total_amount_value && $capture->invoice_id == $invoice_id) {
                                    $updated = salesloo_update_invoice_status($invoice->ID, 'completed');

                                    $encoded_invoice_id = salesloo_encrypt($invoice->ID);
                                    $redirect = salesloo_url_thanks($encoded_invoice_id);
                                    wp_redirect($redirect);
                                    exit;
                                }
                            }
                        }
                    }
                }

                $___salesloo['alert'] = [
                    'type' => 'danger',
                    'message' => __('Error please contact admin', 'salesloo')
                ];
            } catch (\HttpException $ex) {

                $___salesloo['alert'] = [
                    'type' => 'danger',
                    'message' => $ex->getMessage()
                ];
            }
        }
    }

    public function settings()
    {
        \salesloo_field_heading([
            'label' => __('How to get paypal client ID and client secret?'),
            'description' => '<a href="https://developer.paypal.com/developer/applications" target="__blank">' . __('Click here to go to Paypal developer and pick your Paypal Cliend ID and Client secret', 'salesloo') . '</a>',
        ]);

        \salesloo_field_toggle([
            'label'           => __('Enable Testing Sanbox', 'salesloo'),
            'name'            => 'paypal_is_sanbox',
            'value'   => salesloo_get_option('paypal_is_sanbox'),
            'description' => __('Enable sanbox only to test payments with paypal sanbox', 'salesloo')
        ]);

        \salesloo_field_text([
            'label'       => __('Paypal Client ID', 'salesloo'),
            'name'        => 'paypal_client_id',
            'value'       => salesloo_get_option('paypal_client_id'),
            'class' => 'large-text',
        ]);

        \salesloo_field_text([
            'label'       => __('Paypal Client secret', 'salesloo'),
            'name'        => 'paypal_client_secret',
            'value'       => salesloo_get_option('paypal_client_secret'),
            'class' => 'large-text',
        ]);

        \salesloo_field_text([
            'label'       => __('Paypal merchant email', 'salesloo'),
            'name'        => 'paypal_email',
            'value'       => salesloo_get_option('paypal_email'),
        ]);
    }
}
