<?php
session_start();
require 'config/db.php';
require 'config/paytm_config.php';
require_once 'includes/PaytmChecksum.php';

$paytmChecksum = "";
$paramList = array();

// 1. Read Response
$isValidChecksum = "FALSE";
if (isset($_POST["CHECKSUMHASH"])) {
    $paytmChecksum = $_POST["CHECKSUMHASH"];
    unset($_POST["CHECKSUMHASH"]); // Remove checksum from params for verification
}

// 2. Verify Signature
$isValidChecksum = PaytmChecksum::verifySignature($_POST, PAYTM_MERCHANT_KEY, $paytmChecksum);

if ($isValidChecksum == "TRUE") {
    
    // 3. Check Status
    if ($_POST["STATUS"] == "TXN_SUCCESS") {
        
        $order_id = $_POST['ORDERID'];
        $txn_id = $_POST['TXNID'];
        $amount = $_POST['TXNAMOUNT'];
        
        // --- SUCCESS LOGIC ---
        
        // A. Auto-Assign Key Logic (Vending Machine)
        $key_message = "";
        
        // Get items in this order
        $stmtItems = $pdo->prepare("SELECT product_id FROM order_items WHERE order_id = ?");
        $stmtItems->execute([$order_id]);
        $items = $stmtItems->fetchAll();

        foreach ($items as $item) {
            // Find available key
            $kStmt = $pdo->prepare("SELECT id, license_key FROM license_keys WHERE product_id = ? AND status = 'available' LIMIT 1");
            $kStmt->execute([$item['product_id']]);
            $keyData = $kStmt->fetch();

            if ($keyData) {
                // Mark key used
                $pdo->prepare("UPDATE license_keys SET status = 'used', order_id = ? WHERE id = ?")->execute([$order_id, $keyData['id']]);
                $key_message .= "\nKey: " . $keyData['license_key'];
            }
        }

        // B. Update Order Status
        $note = "Paid via Paytm (TXN: $txn_id). " . $key_message;
        
        $stmt = $pdo->prepare("UPDATE orders SET status = 'completed', payment_method = 'Paytm', user_note = ? WHERE id = ?");
        $stmt->execute([$note, $order_id]);

        // C. Redirect to Thank You
        header("Location: thank_you.php?order_id=" . $order_id . "&status=success");

    } else {
        // Payment Failed
        echo "<h2>Payment Failed.</h2><p>Reason: " . $_POST['RESPMSG'] . "</p>";
        echo "<a href='checkout.php'>Try Again</a>";
    }
} else {
    echo "<h2>Security Error</h2><p>Checksum mismatch.</p>";
}
?>