<?php
// File: payu_handler.php
// This script securely processes the checkout form, saves the order, and initiates the PayU payment.

session_start();
require_once 'db.php';
require_once 'payu_config.php';

// Security: Ensure user is logged in and the form was submitted via POST
if ($_SERVER["REQUEST_METHOD"] != "POST" || !isset($_SESSION['user_id'])) {
    header("Location: checkout.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$cart_items = $_SESSION['cart'] ?? [];

if (empty($cart_items)) {
    header("Location: cart.php");
    exit();
}

// 1. Sanitize Shipping Information from the form
$shipping_name = filter_var($_POST['shipping_name'], FILTER_SANITIZE_STRING);
$shipping_address = filter_var($_POST['shipping_address'], FILTER_SANITIZE_STRING);
$shipping_phone = filter_var($_POST['shipping_phone'], FILTER_SANITIZE_STRING);

// Fetch user's email from the database for PayU
$user_email = '';
$stmt_email = $conn->prepare("SELECT email FROM users WHERE id = ?");
$stmt_email->bind_param("i", $user_id);
$stmt_email->execute();
$result_email = $stmt_email->get_result();
if($user_row = $result_email->fetch_assoc()) {
    $user_email = $user_row['email'];
}
$stmt_email->close();


// 2. Recalculate Grand Total from SERVER-SIDE data to prevent manipulation
$total_amount = 0;
$painting_ids = array_keys($cart_items);
$id_placeholders = implode(',', array_fill(0, count($painting_ids), '?'));
$types = str_repeat('i', count($painting_ids));

$stmt_total = $conn->prepare("SELECT id, price, sale_price FROM paintings WHERE id IN ($id_placeholders)");
$stmt_total->bind_param($types, ...$painting_ids);
$stmt_total->execute();
$result_total = $stmt_total->get_result();

$paintings_in_db = [];
while($row = $result_total->fetch_assoc()) {
    $paintings_in_db[$row['id']] = $row;
}
$stmt_total->close();

foreach ($cart_items as $id => $item) {
    if (isset($paintings_in_db[$id])) {
        $price = (isset($paintings_in_db[$id]['sale_price']) && $paintings_in_db[$id]['sale_price'] > 0) ? $paintings_in_db[$id]['sale_price'] : $paintings_in_db[$id]['price'];
        $total_amount += $price * $item['quantity'];
    }
}

if ($total_amount <= 0) {
    die("Error: Cannot process an order with a total of zero.");
}


// 3. Save the Order to your `orders` table with 'pending' status
$conn->begin_transaction();
try {
    $stmt_order = $conn->prepare("INSERT INTO orders (user_id, total_amount, payment_status, shipping_name, shipping_address, shipping_phone) VALUES (?, ?, 'pending', ?, ?, ?)");
    $stmt_order->bind_param("idsss", $user_id, $total_amount, $shipping_name, $shipping_address, $shipping_phone);
    $stmt_order->execute();
    $order_id = $conn->insert_id;

    // Save order items
    foreach ($cart_items as $id => $item) {
        $product = $paintings_in_db[$id];
        $price = (isset($product['sale_price']) && $product['sale_price'] > 0) ? $product['sale_price'] : $product['price'];
        $stmt_items = $conn->prepare("INSERT INTO order_items (order_id, painting_id, quantity, price_at_purchase) VALUES (?, ?, ?, ?)");
        $stmt_items->bind_param("iiid", $order_id, $id, $item['quantity'], $price);
        $stmt_items->execute();
    }
    $conn->commit();
} catch (mysqli_sql_exception $exception) {
    $conn->rollback();
    die("Database error while saving your order. Please try again.");
}


// 4. Prepare data and hash for PayU
$key         = trim(PAYU_KEY);
$salt        = trim(PAYU_SALT);
$txnid       = "UCF-" . $order_id . "-" . time(); // Unique transaction ID
$amount      = number_format($total_amount, 2, '.', '');
$productinfo = "UCF Art Order #" . $order_id;
$firstname   = $shipping_name;
$udf1        = $order_id; // Pass our internal order ID to get it back in the callback

$hash_string = $key . '|' . $txnid . '|' . $amount . '|' . $productinfo . '|' . $firstname . '|' . $user_email . '|' . $udf1 . '||||||||||' . $salt;
$hash = strtolower(hash("sha512", $hash_string));
$payu_url = PAYU_BASE_URL . "/_payment";

// 5. Auto-submit form to redirect to PayU
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Redirecting to Payment...</title>
</head>
<body onload="document.forms['payuForm'].submit()">
    <h3>Redirecting to our secure payment gateway... Please wait.</h3>
    <form action="<?php echo htmlspecialchars($payu_url); ?>" method="post" name="payuForm">
        <input type="hidden" name="key" value="<?php echo $key; ?>">
        <input type="hidden" name="txnid" value="<?php echo $txnid; ?>">
        <input type="hidden" name="amount" value="<?php echo $amount; ?>">
        <input type="hidden" name="productinfo" value="<?php echo htmlspecialchars($productinfo); ?>">
        <input type="hidden" name="firstname" value="<?php echo htmlspecialchars($firstname); ?>">
        <input type="hidden" name="email" value="<?php echo htmlspecialchars($user_email); ?>">
        <input type="hidden" name="phone" value="<?php echo htmlspecialchars($shipping_phone); ?>">
        <input type="hidden" name="surl" value="https://unitedculturalforum.com/payu_callback.php">
        <input type="hidden" name="furl" value="https://unitedculturalforum.com/payu_callback.php">
        <input type="hidden" name="udf1" value="<?php echo $udf1; ?>">
        <input type="hidden" name="hash" value="<?php echo $hash; ?>">
    </form>
</body>
</html>
