<?php
function minicomerce_customers_verify_action()
{
    try { 
   

    if (! current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'minicomerce'));
    }
    if (null ==  get_option(MINICOMERCE_ESSENTIAL) || null ==  get_option(MINICOMERCE_PAYPAL_URLS)) {
        wp_die(esc_html__('Something went wrong wich data required to verify orders.', 'minicomerce'));
    }

    global $wpdb;

    $table_name = esc_sql($wpdb->prefix . MINICOMERCE_REPORTS); 

    $noVerified = $wpdb->get_results($wpdb->prepare("SELECT `id`, `id_salePaypal` FROM %i WHERE verified = 0", $table_name));

    $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') {
        $checkout_url = $minicomerce_paypal_urls[0];
    } else {
        $checkout_url = $minicomerce_paypal_urls[3];
    }

    if ( isset($essential_data[8]) && isset($essential_data[9])) {
        $id = $essential_data[9];
        $secret = $essential_data[10];
        $paypa_data = base64_encode($id . ":" . $secret);
    } else {
        wp_die(esc_html__('Data of paypal not found', 'minicomerce'));
    }
   
    foreach ($noVerified as $key => $value) {

     $checkStatus = minicomerce_customers_verify_action_process($value->id_salePaypal, $paypa_data, $checkout_url);

     if ($checkStatus != null) {
        $wpdb->update($table_name, array('verified' => 1, 'payerid' => $checkStatus, 'payReceived' => 1), array('id' => $value->id));
       } else {
        $wpdb->update($table_name, array('verified' => 1,  'payReceived' => 0), array('id' => $value->id));
       }
    }

    wp_redirect( admin_url( 'admin.php?page=minicomerce_customers' ) );

     } catch (\Throwable $th) {
        $error = $th->getMessage();
        wp_die( esc_html( $error , 'minicomerce' ) );
    }
}

function minicomerce_customers_verify_action_process($id_paypal, $paypa_data, $checkout_url)
{
    $args = array(
        "method"      => "GET",
        "timeout"     => 45,
        "headers" => array(
            "Content-Type" => "application/json",
            "Authorization" => 'Basic ' .  $paypa_data,
        ), 
    );

    $token_response = wp_remote_get($checkout_url .'/'. $id_paypal, $args);

    if (is_wp_error($token_response)) {
        $error_response = $token_response->get_error_message();
        wp_die(esc_html(  $error_response , 'minicomerce' ) );
    }

    $response_body = wp_remote_retrieve_body($token_response);
    $response_data = json_decode($response_body, true);
    if (isset($response_data['status']) == "APPROVED" && isset($response_data["payer"]["payer_id"])) { 
          return $response_data["payer"]["payer_id"];  
    }

    return null;

 
}
