<?php
/**
 * Universal Payment Redirect Handler
 * Fetch settings from Admin and redirect to any API
 */
require_once 'includes/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

// ১. অ্যাডমিন প্যানেলের সেটিংস ফেচ করা
$stmt_settings = $pdo->query("SELECT * FROM settings LIMIT 1");
$site_settings = $stmt_settings->fetch();

$api_url = $site_settings['api_url'] ?? '';
$brand_key = $site_settings['api_brand_key'] ?? ''; // NanoPay বা অন্য যেকোনো Brand Key
$success_url = "https://" . $_SERVER['HTTP_HOST'] . "/payment_callback.php?status=success";
$fail_url = "https://" . $_SERVER['HTTP_HOST'] . "/payment_callback.php?status=fail";

// ২. চেকআউট থেকে আসা ডাটা
$amount = $_POST['amount'];
$coupon = $_POST['coupon'] ?? '';
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];

// ইউজারের ইমেইল নেওয়া
$stmt_u = $pdo->prepare("SELECT email FROM users WHERE id = ?");
$stmt_u->execute([$user_id]);
$user_email = $stmt_u->fetchColumn();

// ৩. ইউনিক ট্রানজেকশন এবং ইনভয়েস আইডি তৈরি
$invoice_no = 'INV-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -5));
$transaction_id = 'TRX-' . time() . rand(100, 999);

try {
    // ৪. পেমেন্ট গেটওয়েতে পাঠানোর আগে অর্ডারটি 'pending' হিসেবে সেভ করা
    // আপনার কার্টে থাকা প্রোডাক্ট আইডিগুলো সেশন থেকে নেওয়া
    if (!empty($_SESSION['cart'])) {
        foreach ($_SESSION['cart'] as $product_id) {
            $stmt_order = $pdo->prepare("INSERT INTO orders (user_id, product_id, invoice_no, amount, coupon_used, transaction_id, status) VALUES (?, ?, ?, ?, ?, ?, 'pending')");
            $stmt_order->execute([$user_id, $product_id, $invoice_no, $amount, $coupon, $transaction_id]);
        }
    }

    // ৫. অটোমেটিক ফর্ম সাবমিট করে যেকোনো গেটওয়েতে পাঠানো
    ?>
    <!DOCTYPE html>
    <html>
    <head><title>Processing Payment...</title></head>
    <body onload="document.forms['payment_form'].submit();">
        <div style="text-align:center; margin-top:100px; font-family:sans-serif;">
            <h2>Redirecting to Secure Payment Gateway...</h2>
            <p>Please do not refresh or close this page.</p>
        </div>
        <form name="payment_form" action="<?php echo htmlspecialchars($api_url); ?>" method="POST">
            <input type="hidden" name="store_id" value="<?php echo htmlspecialchars($brand_key); ?>">
            <input type="hidden" name="brand_key" value="<?php echo htmlspecialchars($brand_key); ?>">
            <input type="hidden" name="amount" value="<?php echo $amount; ?>">
            <input type="hidden" name="tran_id" value="<?php echo $transaction_id; ?>">
            <input type="hidden" name="trx" value="<?php echo $transaction_id; ?>">
            <input type="hidden" name="success_url" value="<?php echo $success_url . '&trx=' . $transaction_id; ?>">
            <input type="hidden" name="fail_url" value="<?php echo $fail_url . '&trx=' . $transaction_id; ?>">
            <input type="hidden" name="cus_name" value="<?php echo htmlspecialchars($user_name); ?>">
            <input type="hidden" name="cus_email" value="<?php echo htmlspecialchars($user_email); ?>">
            <input type="hidden" name="desc" value="Digital Product Purchase - <?php echo $invoice_no; ?>">
        </form>
    </body>
    </html>
    <?php
    // কার্ট ক্লিয়ার করা
    unset($_SESSION['cart']);
    unset($_SESSION['applied_coupon']);

} catch (PDOException $e) {
    die("Payment Error: " . $e->getMessage());
}