<?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(json_encode([
'status' => 'error',
'message' => 'Database connection failed'
], JSON_PRETTY_PRINT));
}

// Initialize output
$output = [
'status' => 'success',
'message' => 'Session updated successfully',
'data' => []
];

try {
// Step 1: Get HDFC merchant details including mobile_number, pin, and device_id
$stmt = $pdo->prepare("SELECT terminal_id, session_id, mobile_number, pin, device_id FROM add_merchant WHERE merchant_name = 'HDFC'");
$stmt->execute();
$merchant = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$merchant) {
throw new Exception("HDFC merchant not found");
}

$terminal_id = $merchant['terminal_id'];
$mobile_number = $merchant['mobile_number'];
$pin = $merchant['pin'];
$device_id = $merchant['device_id'];

// Validate required fields with proper syntax
if (empty($mobile_number)) {
throw new Exception("Mobile number not found in merchant record");
}
if (empty($pin)) {
throw new Exception("PIN not found in merchant record");
}
if (empty($device_id)) {
throw new Exception("Device ID not found in merchant record");
}

// Step 2: First API call to get session ID
$session_url = "https://smartupi.in.net/merchantapi/HDFCSoft/sesion.php?mobile_number=$mobile_number&device=$device_id";
$session_response = file_get_contents($session_url);

if ($session_response === false) {
throw new Exception("Failed to call session API");
}

$session_data = json_decode($session_response, true);

if (!isset($session_data['status']) || $session_data['status'] !== 'Success') {
throw new Exception("Session API failed: " . ($session_data['respMessage'] ?? 'Unknown error'));
}

$new_session_id = $session_data['sessionId'];

// Step 3: Update session_id in database
$update_stmt = $pdo->prepare("UPDATE add_merchant SET session_id = :session_id WHERE terminal_id = :terminal_id");
$update_stmt->execute([
':session_id' => $new_session_id,
':terminal_id' => $terminal_id
]);

// Step 4: Second API call with PIN
$pin_url = "https://smartupi.in.net/merchantapi/HDFCSoft/pin.php?mobile_number=$mobile_number&pin=$pin&sessionid=$new_session_id";
$pin_response = file_get_contents($pin_url);

if ($pin_response === false) {
throw new Exception("Failed to call PIN API");
}

$pin_data = json_decode($pin_response, true);

if (!isset($pin_data['status']) || $pin_data['status'] !== 'Success') {
throw new Exception("PIN API failed: " . ($pin_data['respMessage'] ?? 'Unknown error'));
}

// Step 5: Third API call to get user details
$user_url = "https://smartupi.in.net/merchantapi/HDFCSoft/userdtl.php?sessionid=$new_session_id";
$user_response = file_get_contents($user_url);

if ($user_response === false) {
throw new Exception("Failed to call User Details API");
}

$user_data = json_decode($user_response, true);

if (!isset($user_data['status']) || $user_data['status'] !== 'Success') {
throw new Exception("User Details API failed: " . ($user_data['respMessage'] ?? 'Unknown error'));
}

// Step 6: Update last_sync and status in database
$current_time = date('Y-m-d H:i:s');
$update_stmt = $pdo->prepare("UPDATE add_merchant SET last_sync = :last_sync, status = 'Active' WHERE terminal_id = :terminal_id");
$update_stmt->execute([
':last_sync' => $current_time,
':terminal_id' => $terminal_id
]);

// Prepare final output
$output['data'] = [
'user' => $mobile_number,
'terminal_id' => $terminal_id,
'last_sync' => $current_time,
'status' => 'Active',
'companyName' => $user_data['terminalInfo'][0][$terminal_id]['companyName'] ?? ''
];

} catch (Exception $e) {
$output = [
'status' => 'error',
'message' => $e->getMessage(),
'data' => []
];
}

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