<?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());
}

// Mobikwik ka 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 = 'Mobikwik';
$stmt->bindParam(':merchant_name', $merchant_name);

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

// Fetch the access_token and merchant_id
$merchant = $stmt->fetch(PDO::FETCH_ASSOC);

if ($merchant) {
$access_token = $merchant['access_token'];
$merchant_id = $merchant['merchant_id'];

// API call karein using cURL
$api_url = "https://smartupi.in.net/merchantapi/mobikwik/balance.php?authorization=$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: ";
// print_r($response_data);

// Check karein agar response me status SUCCESS ya success hai
if (isset($response_data['status']) && strtolower($response_data['status']) === 'success') {
// Agar status SUCCESS hai to last_sync aur status ko update karein
$current_time = date('Y-m-d H:i:s'); // Current timestamp
$update_stmt = $pdo->prepare("UPDATE add_merchant SET last_sync = :last_sync, status = 'Active' WHERE merchant_id = :merchant_id");

// Execute the update query
try {
$update_stmt->execute([
':last_sync' => $current_time,
':merchant_id' => $merchant_id
]);
echo "Session $merchant_id updated successfully. Last Sync: $current_time, Status: Active\n";
} catch (PDOException $e) {
echo "Database Error: " . $e->getMessage() . "\n";
}
} else {
echo "API call failed or returned an error.\n";
}
} else {
echo "Mobikwik ka access_token nahi mila.\n";
}

echo "Cron job executed successfully.";