<?php
header('Content-Type: application/json');

// Database configuration file include 
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) {
$response = [
'status' => 'error',
'message' => 'Database connection failed',
'error' => $e->getMessage()
];
echo json_encode($response, JSON_PRETTY_PRINT);
die();
}

$stmt = $pdo->prepare("SELECT * FROM create_orders WHERE txn_status = 'PENDING'");
$stmt->execute();
$pending_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

$results = [];
$success_count = 0;
$failure_count = 0;

if (count($pending_orders) > 0) {
foreach ($pending_orders as $order) {
$order_id = $order['id'];
$update_stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'FAILED' WHERE id = :order_id");

try {
$update_result = $update_stmt->execute([':order_id' => $order_id]);

$result = [
'order_id' => $order_id,
'txn_status' => 'FAILED',
'message' => $update_result ? "Order updated successfully" : "Failed to update order"
];

if ($update_result) {
$success_count++;
} else {
$failure_count++;
}

$results[] = $result;

} catch (PDOException $e) {
$results[] = [
'order_id' => $order_id,
'txn_status' => 'PENDING',
'message' => 'Database error: ' . $e->getMessage()
];
$failure_count++;
}
}

$response = [
'status' => 'success',
'processed_orders' => $results,
'summary' => [
'total_orders' => count($pending_orders),
'successful_updates' => $success_count,
'failed_updates' => $failure_count
],
'final_message' => 'Cron job executed successfully'
];

} else {
$response = [
'status' => 'success',
'message' => 'No pending orders found',
'processed_orders' => [],
'summary' => [
'total_orders' => 0,
'successful_updates' => 0,
'failed_updates' => 0
]
];
}

echo json_encode($response, JSON_PRETTY_PRINT);
?>