<?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 = 'Amazon'");
$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.');
}

// Iterate through each PENDING order
foreach ($pendingOrders as $orderData) {
    // Extract relevant data for each order
    $orderid = $orderData['orderid'];
    $upi_id = $orderData['upi_id']; // Assuming 'upi_id' is the column name in create_orders
    $orderAmount = $orderData['amount']; // Amount stored in create_orders table

    $merchantDataQuery = $pdo->prepare("SELECT ubid_acbin, x_acbin, at_acbin FROM add_merchant WHERE upi_id = :upi_id AND merchant_name = 'Amazon'");
    $merchantDataQuery->bindParam(':upi_id', $upi_id);
    $merchantDataQuery->execute();
    $merchantData = $merchantDataQuery->fetch(PDO::FETCH_ASSOC);

    // Check if merchant data was found
    if (!$merchantData) {
        die('Merchant data not found for UPI ID: ' . $upi_id);
    }

    // Extract the 'ubid_acbin' from the merchant data
    $ubid_acbin = $merchantData['ubid_acbin'];
    $x_acbin = $merchantData['x_acbin'];
    $at_acbin = $merchantData['at_acbin'];

    // Prepare the new API URL
    $apiUrl = "https://smartupi.in.net/merchantapi/amazon/cheak-status-txn.php?txn_id=$orderid&ubid_acbin=$ubid_acbin&x_acbin=$x_acbin&at_acbin=$at_acbin";
    
    // 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) {
        die('cURL Error: ' . curl_error($ch));
    }

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

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

    // Check if the response contains the 'status' field
    if (isset($responseData['status'])) {
        // If the status is 'success', process the transaction
        if ($responseData['status'] == 'success') {
            // Check if transactions array exists and has at least one transaction
            if (isset($responseData['transactions']) && is_array($responseData['transactions']) && count($responseData['transactions']) > 0) {
                $transaction = $responseData['transactions'][0];
                
                // Check if the transaction status is success
                if ($transaction['txn_status'] == 'success') {
                    $apiAmount = $transaction['amount'];
                    
                    // Compare amounts
                    if ($orderAmount == $apiAmount) {
                        // Extract transaction details
                        $utrNumber = $transaction['utr_number'];
                        $receivedFrom = $transaction['received_from'];
                        $txnDate = date('Y-m-d H:i:s'); // Use current timestamp or response timestamp if available

                        // 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, created_at = :created_at WHERE orderid = :orderid");
                        $stmt->bindParam(':amount', $apiAmount);
                        $stmt->bindParam(':utr_number', $utrNumber);
                        $stmt->bindParam(':received_from', $receivedFrom);
                        $stmt->bindParam(':created_at', $txnDate);
                        $stmt->bindParam(':orderid', $orderid);
                        $stmt->execute();

                        // Output the update status
                        echo "Order $orderid successfully updated with transaction details.\n";
                    } else {
                        // If amounts do not match, mark as FAILED
                        $stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'FAILED' WHERE orderid = :orderid");
                        $stmt->bindParam(':orderid', $orderid);
                        $stmt->execute();

                        echo "Order $orderid marked as FAILED due to amount mismatch.\n";
                    }
                } else {
                    // If transaction status is not success, mark as FAILED
                    $stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'FAILED' WHERE orderid = :orderid");
                    $stmt->bindParam(':orderid', $orderid);
                    $stmt->execute();

                    echo "Order $orderid marked as FAILED (transaction not successful).\n";
                }
            } else {
                // No transactions found in response
                echo "No transactions found in API response for order $orderid\n";
            }
        } 
        // If the status is 'ERROR', update the txn_status to 'FAILED'
        elseif ($responseData['status'] == 'ERROR') {
            // Update the database with FAILED status
            $stmt = $pdo->prepare("UPDATE create_orders SET txn_status = 'FAILED' WHERE orderid = :orderid");
            $stmt->bindParam(':orderid', $orderid);
            $stmt->execute();

            // Output the update status
            echo "Order $orderid marked as FAILED.\n";
        } else {
            // Handle other statuses if needed
            echo "API Response: " . $responseData['status'] . "\n";
        }
    } else {
        // Handle case where the API response format is not as expected
        echo "Invalid API response format for order $orderid\n";
        continue;
    }
}

?>