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

// 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) {
    die("Database connection failed: " . $e->getMessage());
}

// 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 = 'HDFC'");
$sql->execute();

// Fetch all PENDING orders data
$pendingOrders = $sql->fetchAll(PDO::FETCH_ASSOC);

// If no PENDING orders are found, show an error message
if (!$pendingOrders) {
    die('No PENDING orders found for HDFC.');
}

// Iterate through each PENDING order
foreach ($pendingOrders as $orderData) {
    // Extract relevant data for each order
    $orderid = $orderData['orderid'];
    $user_id = $orderData['user']; // Using user_id instead of upi_id for HDFC
    $orderAmount = $orderData['amount'];

    // Now we will get the merchant credentials from the `add_merchant` table
    $merchantDataQuery = $pdo->prepare("SELECT terminal_id, session_id FROM add_merchant WHERE user = :user_id AND merchant_name = 'HDFC'");
    $merchantDataQuery->bindParam(':user_id', $user_id);
    $merchantDataQuery->execute();
    $merchantData = $merchantDataQuery->fetch(PDO::FETCH_ASSOC);

    // Check if merchant data was found
    if (!$merchantData) {
        echo 'Merchant credentials not found for user: ' . $user_id . "\n";
        continue; // Skip to next order if merchant not found
    }

    // Extract the terminal_id and session_id for HDFC
    $terminal_id = $merchantData['terminal_id'];
    $session_id = $merchantData['session_id'];

    // Prepare the HDFC API URL
    $apiUrl = "https://smartupi.in.net/merchantapi/HDFCSoft/merchant-txn.php?tidList=$terminal_id&sessionid=$session_id&count=100&description=$orderid";

    // Initialize cURL
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Execute cURL request
    $response = curl_exec($ch);
    
    // Check if cURL executed successfully
    if ($response === false) {
        echo 'cURL Error: ' . curl_error($ch) . "\n";
        curl_close($ch);
        continue; // Skip to next order if API call failed
    }

    // Close the cURL session
    curl_close($ch);

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

    // Check if the response contains the 'status_code' field (HDFC specific)
    if (isset($responseData['status_code'])) {
        // If the status is SUCCESS (3)
        if ($responseData['status_code'] == 3 && isset($responseData['data']['txn_status']) && $responseData['data']['txn_status'] == 'SUCCESS') {
            $apiData = $responseData['data'];

            // Verify orderid and amount
            if ($apiData['orderid'] != $orderid) {
                echo "Order ID mismatch for $orderid\n";
                continue;
            }

            if ((float)$apiData['amount'] != (float)$orderAmount) {
                echo "Amount mismatch for order $orderid\n";
                continue;
            }

            // Extract transaction details
            $utrNumber = $apiData['utr_number'] ?? '';
            $receivedFrom = $apiData['received_from'] ?? ($apiData['TID'] ?? '');
            $txnId = $apiData['txnid'] ?? '';

            // Update the database with transaction details
            $stmt = $pdo->prepare("UPDATE create_orders SET 
                txn_status = 'SUCCESS', 
                amount = :amount, 
                utr_number = :utr_number, 
                received_from = :received_from,
                transactions_id = :txn_id
                WHERE orderid = :orderid");

            $stmt->bindParam(':amount', $apiData['amount']);
            $stmt->bindParam(':utr_number', $utrNumber);
            $stmt->bindParam(':received_from', $receivedFrom);
            $stmt->bindParam(':txn_id', $txnId);
            $stmt->bindParam(':orderid', $orderid);

            if ($stmt->execute()) {
                echo "Order $orderid successfully updated with transaction details.\n";
            } else {
                echo "Failed to update order $orderid\n";
            }
        } 
        // If the status is FAILED (4)
        elseif ($responseData['status_code'] == 4) {
            // Update only txn_status to FAILED
            $stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'FAILED' WHERE orderid = :orderid");
            $stmt->bindParam(':orderid', $orderid);
            
            if ($stmt->execute()) {
                echo "Order $orderid status updated to FAILED.\n";
            } else {
                echo "Failed to update order $orderid status to FAILED\n";
            }
        }
        // If the status is PENDING (2)
        elseif ($responseData['status_code'] == 2) {
            // Update only txn_status to PENDING (though it's already PENDING, this ensures we track the latest status)
            $stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'PENDING' WHERE orderid = :orderid");
            $stmt->bindParam(':orderid', $orderid);
            
            if ($stmt->execute()) {
                echo "Order $orderid is still PENDING\n";
            } else {
                echo "Failed to update order $orderid status to PENDING\n";
            }
        }
        // Other status codes
        else {
            echo "Order $orderid received unknown status code: " . $responseData['status_code'] . "\n";
        }
    } else {
        // Handle case where the API response format is not as expected
        echo "Invalid API response format for order $orderid\n";
        echo "Response: " . print_r($responseData, true) . "\n";
    }
}
?>