<?php
// File: payu_callback.php
session_start();
require_once 'db.php';
require_once 'payu_config.php';

$response = $_POST;

// It's highly recommended to add the full hash verification logic here for security
// For now, we will proceed based on the status provided by PayU.

$status      = strtolower($response["status"] ?? 'failure');
$txnid       = $response["txnid"] ?? '';
$order_id    = intval($response["udf1"] ?? 0); // Our internal DB order ID

if ($order_id > 0) {
    if ($status === "success") {
        // --- PAYMENT IS SUCCESSFUL ---
        // Update the order status in our database
        $stmt = $conn->prepare("UPDATE orders SET payment_status='completed', payment_gateway_txn_id=? WHERE id=?");
        $stmt->bind_param("si", $txnid, $order_id);
        $stmt->execute();
        
        // Clear the user's shopping cart
        unset($_SESSION['cart']);

        // Redirect to a Thank You page
        header("Location: thank-you.php?order_id=" . $order_id);
        exit();

    } else {
        // --- PAYMENT FAILED ---
        $stmt = $conn->prepare("UPDATE orders SET payment_status='failed' WHERE id=?");
        $stmt->bind_param("i", $order_id);
        $stmt->execute();
        
        $_SESSION['payment_error'] = $response['error_Message'] ?? 'The payment failed. Please try again.';
        header("Location: cart.php?status=payment_failed");
        exit();
    }
}

// If no valid order ID is found, redirect home
header("Location: index.php");
exit();
?>
