<?php
// Set timezone
date_default_timezone_set('Asia/Kolkata');

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

try {
// Database connection
$pdo = new PDO("mysql:host=$db_host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Count failed create_orders before deletion
$count_stmt = $pdo->prepare("SELECT COUNT(*) as total FROM create_orders WHERE txn_status = 'FAILED'");
$count_stmt->execute();
$count_result = $count_stmt->fetch(PDO::FETCH_ASSOC);
$total_failed = $count_result['total'];

if ($total_failed > 0) {
// Delete the failed create_orders
$delete_stmt = $pdo->prepare("DELETE FROM create_orders WHERE txn_status = 'FAILED'");
$delete_stmt->execute();
$deleted_rows = $delete_stmt->rowCount();

$response = [
'status' => 'success',
'message' => 'Deleted failed create_orders',
'deleted_count' => $deleted_rows,
'timestamp' => date('Y-m-d H:i:s')
];
} else {
$response = [
'status' => 'success',
'message' => 'No failed create_orders found',
'deleted_count' => 0,
'timestamp' => date('Y-m-d H:i:s')
];
}

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

} catch (PDOException $e) {
$response = [
'status' => 'error',
'message' => "Database error: " . $e->getMessage(),
'timestamp' => date('Y-m-d H:i:s')
];

header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
}
?>