<?php
// ─── Verify Razorpay Payment & Confirm Order ─────────────────────────────────
if (session_status() === PHP_SESSION_NONE) session_start();
include 'config/db.php';
include 'config/razorpay.php';

if (!isset($_SESSION['user_id'], $_SESSION['pending_order_id'])) {
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: payment.php');
    exit;
}

$payment_id   = $_POST['razorpay_payment_id']   ?? '';
$rzp_order_id = $_POST['razorpay_order_id']      ?? '';
$signature    = $_POST['razorpay_signature']     ?? '';
$order_id     = (int)$_SESSION['pending_order_id'];
$user_id      = (int)$_SESSION['user_id'];

// ── Signature Verification ────────────────────────────────────────────────────
$generated = hash_hmac('sha256', $rzp_order_id . '|' . $payment_id, RAZORPAY_KEY_SECRET);

if (!hash_equals($generated, $signature)) {
    // Mark order as Failed
    mysqli_query($conn,
        "UPDATE orders SET payment_status='Failed' WHERE id=$order_id AND user_id=$user_id"
    );
    header('Location: payment.php?error=signature_mismatch');
    exit;
}

// ── Update Order as Paid ──────────────────────────────────────────────────────
$pid_safe = mysqli_real_escape_string($conn, $payment_id);
mysqli_query($conn,
    "UPDATE orders
     SET payment_status='Paid', payment_id='$pid_safe'
     WHERE id=$order_id AND user_id=$user_id"
);

// ── Clear session & redirect ──────────────────────────────────────────────────
unset($_SESSION['cart'], $_SESSION['pending_order_id'], $_SESSION['razorpay_order_id']);
header("Location: order-success.php?order_id=$order_id");
exit;
