<?php

date_default_timezone_set('Asia/Kolkata');

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

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

// add_merchant table se sabhi merchant_id aur access_token fetch karein
$stmt = $pdo->prepare("SELECT merchant_id, access_token FROM add_merchant WHERE merchant_name = :merchant_name");

// Bind the parameter
$merchant_name = 'Bharatpe';
$stmt->bindParam(':merchant_name', $merchant_name);

// Execute the statement
$stmt->execute();

// Fetch all results as an associative array
$merchants = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through each merchant and process the data
foreach ($merchants as $merchant) {
    $merchant_id = $merchant['merchant_id'];
    $access_token = $merchant['access_token'];

    // API call karein using cURL
    $api_url = "https://smartupi.in.net/merchantapi/bharatpe/transactions.php?merchant_id=$merchant_id&access_token=$access_token";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    // Response ko JSON se array mein convert karein
    $response_data = json_decode($response, true);

    // Debugging: Print API response
    // echo "API Response for Merchant ID $merchant_id: ";
    // print_r($response_data);

    // Check karein agar response me kisi bhi transaction ka status SUCCESS hai
    $success_found = false;
    foreach ($response_data as $transaction) {
        if (isset($transaction['status']) && strtolower($transaction['status']) === 'success') {
            $success_found = true;
            break; // Ek bhi SUCCESS milne par loop se bahar aa jao
        }
    }

    if ($success_found) {
        // Agar kisi bhi transaction ka status SUCCESS hai to last_sync ko current time se update kar dena aur status ko Active kar dena
        $current_time = date('Y-m-d H:i:s');
        $update_stmt = $pdo->prepare("UPDATE add_merchant SET last_sync = :last_sync, status = 'Active' WHERE merchant_id = :merchant_id");

        // Debugging: Check if the update query executed successfully
        try {
            $update_result = $update_stmt->execute([':last_sync' => $current_time, ':merchant_id' => $merchant_id]);
            if ($update_result) {
                echo "Merchant ID $merchant_id updated successfully.\n";
            } else {
                echo "Failed to update Merchant ID $merchant_id.\n";
            }
        } catch (PDOException $e) {
            echo "Database Error: " . $e->getMessage() . "\n";
        }
    } else {
        // Agar kisi bhi transaction ka status SUCCESS nahi hai to yeh message print karein
        echo "No SUCCESS status found for Merchant ID $merchant_id.\n";
    }
}

echo "Cron job executed successfully.";