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

// Enable error reporting for debugging
// ini_set('display_errors', 1);
// error_reporting(E_ALL);

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

// Initialize response array
$response = [
'status' => 'initiated',
'orders_processed' => [],
'summary' => [
'total_orders' => 0,
'success_count' => 0,
'failed_count' => 0,
'amount_mismatch_count' => 0
]
];

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

// Query the `create_orders` table to get all data where txn_status is 'PENDING'
$sql = $pdo->prepare("SELECT * FROM create_orders WHERE txn_status = 'PENDING' AND merchant_name = 'Paytm'");
$sql->execute();

// Fetch all PENDING orders data
$pendingOrders = $sql->fetchAll(PDO::FETCH_ASSOC);
$response['summary']['total_orders'] = count($pendingOrders);

// If no PENDING orders are found, show an error message
if (!$pendingOrders) {
$response['status'] = 'completed';
$response['message'] = 'No PENDING orders found.';
echo json_encode($response, JSON_PRETTY_PRINT);
exit;
}

// Iterate through each PENDING order
foreach ($pendingOrders as $orderData) {
$orderResponse = [
'orderid' => $orderData['orderid'],
'upi_id' => $orderData['upi_id'],
'amount' => $orderData['amount'],
'status' => 'processing',
'message' => ''
];

try {
// Get the 'paytm_mid' from the `add_merchant` table using 'upi_id'
$merchantDataQuery = $pdo->prepare("SELECT paytm_mid FROM add_merchant WHERE upi_id = :upi_id AND merchant_name = 'Paytm'");
$merchantDataQuery->bindParam(':upi_id', $orderData['upi_id']);
$merchantDataQuery->execute();
$merchantData = $merchantDataQuery->fetch(PDO::FETCH_ASSOC);

// Check if merchant data was found
if (!$merchantData) {
throw new Exception('Merchant data not found for UPI ID: ' . $orderData['upi_id']);
}

// Prepare the API URL
$apiUrl = 'https://smartupi.in.net/merchantapi/paytm/payment-status.php';

// Prepare data for API request
$data = [
'mid' => $merchantData['paytm_mid'],
'order_id' => $orderData['orderid']
];

// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$apiResponse = curl_exec($ch);

if ($apiResponse === false) {
throw new Exception('cURL Error: ' . curl_error($ch));
}
curl_close($ch);

// Decode the JSON response
$responseData = json_decode($apiResponse, true);

if (!isset($responseData['status'])) {
throw new Exception('Invalid API response format');
}

$orderResponse['api_response'] = $responseData;

// Process based on API status
if ($responseData['status'] == 'SUCCESS') {
if ($orderData['amount'] == $responseData['amount']) {
// Update database with success details
$stmt = $pdo->prepare("UPDATE create_orders SET 
txn_status = 'SUCCESS', 
amount = :amount, 
utr_number = :utr_number, 
received_from = :received_from, 
created_at = :created_at 
WHERE orderid = :orderid");

$stmt->execute([
':amount' => $responseData['amount'],
':utr_number' => $responseData['UTR'],
':received_from' => $responseData['paymentApp'],
':created_at' => date('Y-m-d H:i:s'),
':orderid' => $orderData['orderid']
]);

$orderResponse['status'] = 'SUCCESS';
$orderResponse['message'] = 'Transaction completed successfully';
$response['summary']['success_count']++;
} else {
// Amount mismatch
$stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'FAILED' WHERE orderid = :orderid");
$stmt->execute([':orderid' => $orderData['orderid']]);

$orderResponse['status'] = 'FAILED';
$orderResponse['message'] = 'Amount mismatch';
$response['summary']['amount_mismatch_count']++;
$response['summary']['failed_count']++;
}
} elseif ($responseData['status'] == 'FAILED') {
$stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'FAILED' WHERE orderid = :orderid");
$stmt->execute([':orderid' => $orderData['orderid']]);

$orderResponse['status'] = 'FAILED';
$orderResponse['message'] = 'Transaction failed as per API response';
$response['summary']['failed_count']++;
} else {
$orderResponse['status'] = 'UNKNOWN';
$orderResponse['message'] = 'Unknown status in API response';
}

} catch (Exception $e) {
$orderResponse['status'] = 'ERROR';
$orderResponse['message'] = $e->getMessage();
$response['summary']['failed_count']++;
}

$response['orders_processed'][] = $orderResponse;
}

$response['status'] = 'completed';
$response['message'] = 'Processing completed for all orders';

} catch (PDOException $e) {
$response['status'] = 'error';
$response['message'] = 'Database connection failed: ' . $e->getMessage();
} catch (Exception $e) {
$response['status'] = 'error';
$response['message'] = $e->getMessage();
}

echo json_encode($response, JSON_PRETTY_PRINT);
?>