<?php
require_once('includes/load.php');
// Define your parameters

function getAuthShopee($shop_id, $code)
{
    global $db;
    $baseUrl = SHOPEE_API_URL;
    $partner_id = SHOPEE_API_PARTNER_ID;
    $partner_key = SHOPEE_API_PARTNER_KEY;

    $timestamp = time();

    // Define the API path
    $api_path = '/api/v2/auth/token/get';

    // Create the base string for signing
    $base_string = "{$partner_id}{$api_path}{$timestamp}";

    // Generate HMAC-SHA256 signature
    $sign = urlencode(hash_hmac('sha256', $base_string, $partner_key));

    // API URL
    $url = "{$baseUrl}{$api_path}?partner_id={$partner_id}&sign={$sign}&timestamp={$timestamp}";

    // Data to be sent in the request body
    $data = json_encode([
        "shop_id" => $shop_id,
        "code" => $code,
        "partner_id" => $partner_id
    ]);

    // Initialize cURL
    $ch = curl_init($url);

    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Cookie: SPC_SI=8Q4lZwAAAAAyd3B2VzR6anezDgAAAAAAeFA2R3JnUnQ=' // Set the cookie
    ]);
    curl_setopt($ch, CURLOPT_POST, true); // Use POST method
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the JSON data

    // Execute the request
    $response = curl_exec($ch);

    // Close cURL session
    curl_close($ch);

    // Check for errors
    if (curl_errno($ch)) {

        echo 'Error:' . curl_error($ch);
    } else {
        // Print the response
        $data = json_decode($response, true);
        // Check if the response contains the expected fields
        if (isset($data['refresh_token'])) {
            $refresh_token = $data['refresh_token'];
            $access_token = $data['access_token'];
            $expire_in = $data['expire_in'];
            $platform_id = 1;

            // Prepare the SQL statement to insert or update the tokens
            $sql = "UPDATE shop SET refresh_token = ?, access_token = ?, expire_in = ? WHERE shop_id = ? and platform_id = ?";
            $stmt = $db->prepare($sql);

            // Bind parameters
            $stmt->bind_param("ssiii", $refresh_token, $access_token, $expire_in, $shop_id, $platform_id);

            // Execute the statement
            if ($stmt->execute()) {
                // echo json_encode(["message" => "Tokens saved successfully"]);
                return [$access_token, $refresh_token, true];
            } else {
                // echo json_encode(["message" => "Tokens saved Failed", "data" => $data]);
                return ["", "", false];
            }
        } else {
            return ["", "", false];
        }
    }
}
