<?php

if (! defined('ABSPATH')) exit;

require_once plugin_dir_path(__FILE__) . './minicomerce_process_checkout.php';

function minicomerce_getToken()
{
    echo wp_json_encode(minicomerce_request_token());
    wp_die();
}


function minicomerce_request_token()
{

    if (
        !isset($_POST['currency']) ||
        !isset($_POST['price']) ||
        !isset($_POST['product_name']) ||
        !isset($_POST['variation']) ||
        !isset($_POST['id']) ||
        !isset($_POST['description']) ||
        !isset($_POST['urlSucess']) ||
        !isset($_POST['urlError']) ||
        empty($_POST['currency']) ||
        empty($_POST['price']) ||
        empty($_POST['product_name']) ||
        empty($_POST['variation']) ||
        empty($_POST['id']) ||
        empty($_POST['description']) ||
        empty($_POST['urlSucess']) ||
        empty($_POST['urlError'])
    ) {
        return array("status" => 404, "message" => "Error: data necesary to process the request not found");
    }

    if (!isset($_POST['nonce']) || wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'], 'getTokenNonce')))) {
        return array("status" => 404, "message" => "Error: nonce validation failed");
    }


    $currency = sanitize_text_field(wp_unslash($_POST['currency']));
    $price = sanitize_text_field(wp_unslash($_POST['price']));
    $product_name = sanitize_text_field(wp_unslash($_POST['product_name']));
    $variation = sanitize_text_field(wp_unslash($_POST['variation']));
    $id = sanitize_text_field(wp_unslash($_POST['id']));
    $description = sanitize_text_field(wp_unslash($_POST['description']));
    $urlSucess = sanitize_url(wp_unslash($_POST['urlSucess']));
    $urlError = sanitize_url(wp_unslash($_POST['urlError']));

    $userData = array(
        "currency" => $currency,
        "price" => $price,
        "product_name" => $product_name,
        "variation" => $variation,
        "id" => $id,
        "description" => $description,
        "urlSucess" => $urlSucess,
        "urlError" => $urlError,
    );

    if (null === get_option(MINICOMERCE_PAYPAL_URLS)) {
        return array("status" => 404, "message" => "Error: data necesary to process the request not found");
    }

    $essential_data = (null !==  get_option(MINICOMERCE_ESSENTIAL)) ? unserialize(get_option(MINICOMERCE_ESSENTIAL)) : null;

    $minicomerce_paypal_urls = unserialize(get_option(MINICOMERCE_PAYPAL_URLS));

    if ($essential_data[12] == 'on') {
        $token_url = $minicomerce_paypal_urls[1];
        $checkout_url = $minicomerce_paypal_urls[0];
    } else {
        $token_url = $minicomerce_paypal_urls[4];
        $checkout_url = $minicomerce_paypal_urls[3];
    }



    if (null !== $essential_data && isset($essential_data[9])) {
        $id = $essential_data[9];
        $secret = $essential_data[10];
        $paypa_data = base64_encode($id . ":" . $secret);
    } else {
        return array("status" => 404, "message" => "Error: Token not found");
    }

    $args = array(
        "method"      => "POST",
        "timeout"     => 45,
        "headers" => array(
            "Content-Type" => "application/x-www-form-urlencoded",
            "Authorization" => 'Basic ' .  $paypa_data,
        ),
        "body"        => array(
            "grant_type" => "client_credentials",
        ),
    );

    $token_response = wp_remote_post($token_url, $args);

    if (is_wp_error($token_response)) {
        return array("status" => 404, "message" => "Error: " . $token_response->get_error_message());
    }
    $response_code = wp_remote_retrieve_response_code($token_response);
    if ($response_code != 200) {
        return array("status" => 404, "message" => "Error: " . $response_code);
    }
    $response_body = wp_remote_retrieve_body($token_response);
    $response_data = json_decode($response_body, true);
    if (isset($response_data['access_token'])) {

        return minicomerce_process_checkout($response_data['access_token'], $userData, $checkout_url);
    } else {
        return array("status" => 404, "message" => "Error: No access token found in response");
    }
}