<?php
date_default_timezone_set('Asia/Kolkata');

// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Database configuration file include 
require_once('../database/dbconfig.php');

// Database connection establish karein
try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Function to keep Amazon session alive
function keepAmazonSessionAlive($cookieFile, $cookies) {
    // Define the Amazon URL (e.g., the homepage) to simulate activity
    $url = 'https://www.amazon.in/pay/history';

    // Convert cookies array into a string format required by cURL
    $cookieString = '';
    foreach ($cookies as $key => $value) {
        $cookieString .= "{$key}={$value}; ";
    }

    // Initialize cURL session
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIE, rtrim($cookieString)); // Send the cookies as a single string
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Use the cookies file
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);  // Save cookies to the file
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL verification
    curl_setopt($ch, CURLOPT_ENCODING, ''); // Handle all encodings
    
    // Execute the cURL request and capture the response
    $response = curl_exec($ch);
    //echo $response;
    // Check for errors
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        return ['success' => false, 'message' => "cURL Error: " . $error];
    }

    // Get the HTTP response code to validate the request
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // If HTTP response code is not 200, return an error
    if ($http_code != 200) {
        return ['success' => false, 'message' => "Failed to keep the session alive. HTTP Code: " . $http_code];
    }

    return ['success' => true, 'message' => "Successfully kept the session alive!"];
}

// Define the cookie file to store and read session cookies
$cookieFile = 'cookies.txt'; // Make sure this file exists and is writable

// Query to fetch data where merchant_name is 'Amazon'
$query = "SELECT ubid_acbin, x_acbin, at_acbin FROM add_merchant WHERE merchant_name = 'Amazon'";

try {
    // Execute the query
    $stmt = $pdo->query($query);

    // Check if any rows were returned
    if ($stmt->rowCount() == 0) {
        header('Content-Type: application/json');
        echo json_encode([
            'status' => 'ERROR',
            'message' => 'No any merchant'
        ], JSON_PRETTY_PRINT);
        exit();
    }

    // Initialize an array to store the results
    $results = [];

    // Loop through all the records and make the API call one by one
    while ($userdata = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $ubid_acbin = $userdata['ubid_acbin'];
        $x_acbin = $userdata['x_acbin'];
        $at_acbin = $userdata['at_acbin'];
        
        // Prepare cookies for the current merchant
        $cookies = [
            'ubid-acbin' => $ubid_acbin,
            'at-acbin'   => $at_acbin,
            'x-acbin'    => $x_acbin
        ];
        
        // Call the function to keep the Amazon session alive
        $result = keepAmazonSessionAlive($cookieFile, $cookies);
        
        if ($result['success']) {
            // Get current datetime in Asia/Kolkata timezone
            $currentDateTime = date('Y-m-d H:i:s');
            
            // Update the status to "ACTIVE" and last_sync to current datetime for the current record
            $updateQuery = "UPDATE add_merchant SET status = 'Active', last_sync = :last_sync WHERE ubid_acbin = :ubid_acbin";
            
            // Prepare and execute the update query using PDO
            $updateStmt = $pdo->prepare($updateQuery);
            $updateStmt->bindParam(':ubid_acbin', $ubid_acbin, PDO::PARAM_STR);
            $updateStmt->bindParam(':last_sync', $currentDateTime, PDO::PARAM_STR);
            
            if ($updateStmt->execute()) {
                $results[] = [
                    'ubid_acbin' => $ubid_acbin,
                    'status' => 'ACTIVE',
                    'message' => 'Cookie run success',
                    'last_sync' => $currentDateTime
                ];
            } else {
                $results[] = [
                    'ubid_acbin' => $ubid_acbin,
                    'status' => 'ERROR',
                    'message' => 'Database update failed'
                ];
            }
        } else {
            $results[] = [
                'ubid_acbin' => $ubid_acbin,
                'status' => 'ERROR',
                'message' => $result['message']
            ];
        }
    }
    
    // Output the results
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'SUCCESS',
        'results' => $results
    ], JSON_PRETTY_PRINT);
    
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'ERROR',
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_PRETTY_PRINT);
}
?>