<?php

date_default_timezone_set('Asia/Kolkata');

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

// Database connection establish 
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());
}

// SBI ka access_token fetch
$stmt = $pdo->prepare("SELECT access_token, merchant_username, merchant_id FROM add_merchant WHERE merchant_name = :merchant_name");

// Bind the parameter
$merchant_name = 'sbi';
$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) {
$merchant_session = $merchant['access_token'];
$merchant_username = $merchant['merchant_username'];
$merchant_id = $merchant['merchant_id'];

// API call  using cURL
$api_url = "https://smartupi.in.net/merchantapi/sbi-merchant/profile.php?merchant_username=$merchant_username&merchant_session=$merchant_session";
$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 
$response_data = json_decode($response, true);

// 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
]);

// Get name from API response
$name = $response_data['data'][0]['Name'] ?? 'N/A';

// Prepare JSON response
$output = [
'status' => $response_data['status'],
'Name' => $name,
'merchant_username' => $merchant_username,
'Message' => 'Session updated successfully. Last Sync: ' . $current_time
];

header('Content-Type: application/json');
echo json_encode($output, JSON_PRETTY_PRINT);

} catch (PDOException $e) {
$error = [
'status' => 'error',
'Message' => 'Database Error: ' . $e->getMessage()
];
header('Content-Type: application/json');
echo json_encode($error, JSON_PRETTY_PRINT);
}
} else {
$error = [
'status' => 'error',
'Message' => 'API call failed or returned an error'
];
header('Content-Type: application/json');
echo json_encode($error, JSON_PRETTY_PRINT);
}
} else {
$error = [
'status' => 'error',
'Message' => 'SBI ka access_token Note Found'
];
header('Content-Type: application/json');
echo json_encode($error, JSON_PRETTY_PRINT);
}

// Cron job execution message can be added to the JSON response if needed
// Or you can log it separately