<?php
require_once 'includes/db_connect.php';
if (!isset($_SESSION["user_id"])) { header("location: login.php"); exit; }
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) { header("location: packages.php"); exit; }

$offer_id = (int)$_GET['id']; $user_id = (int)$_SESSION['user_id']; $message = '';
$user_level_stmt = $conn->prepare("SELECT level_id FROM users WHERE id = ?");
$user_level_stmt->bind_param("i", $user_id); $user_level_stmt->execute();
$user_level_id = $user_level_stmt->get_result()->fetch_assoc()['level_id'];

$offer_stmt = $conn->prepare("SELECT o.*, (o.price - IFNULL(oc.discount, 0)) AS final_price FROM offers o LEFT JOIN offer_commissions oc ON o.id = oc.offer_id AND oc.level_id = ? WHERE o.id = ? AND o.status = 'Active'");
$offer_stmt->bind_param("ii", $user_level_id, $offer_id); $offer_stmt->execute();
$offer = $offer_stmt->get_result()->fetch_assoc();
if (!$offer) { header("location: packages.php"); exit; }

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['transaction_pin'])) {
    $target_mobile = trim($_POST['target_mobile']); $pin = $_POST['transaction_pin'];
    $conn->begin_transaction();
    try {
        $user_stmt = $conn->prepare("SELECT balance, transaction_pin FROM users WHERE id = ? FOR UPDATE");
        $user_stmt->bind_param("i", $user_id); $user_stmt->execute();
        $user = $user_stmt->get_result()->fetch_assoc();
        if (is_null($user['transaction_pin'])) { throw new Exception("অনুগ্রহ করে প্রথমে পিন সেট করুন।"); }
        if (!password_verify($pin, $user['transaction_pin'])) { throw new Exception("আপনার পিন সঠিক নয়।"); }
        if ($user['balance'] < $offer['final_price']) { throw new Exception("আপনার একাউন্টে পর্যাপ্ত ব্যালেন্স নেই।"); }
        
        $final_price = $offer['final_price'];
        $conn->query("UPDATE users SET balance = balance - $final_price WHERE id = $user_id");
        $desc = "Package: " . $offer['offer_name'] . " for " . $target_mobile;
        $conn->query("INSERT INTO transactions (user_id, type, amount, description) VALUES ($user_id, 'Package Purchase', $final_price, '$desc')");
        
        $stmt_order = $conn->prepare("INSERT INTO package_orders (user_id, offer_id, offer_name, target_mobile, price_paid) VALUES (?, ?, ?, ?, ?)");
        $stmt_order->bind_param("iissd", $user_id, $offer_id, $offer['offer_name'], $target_mobile, $final_price);
        $stmt_order->execute();
        
        $conn->commit();
        $message = '<div class="alert alert-success">আপনার অফার রিকুয়েস্টটি সফলভাবে জমা হয়েছে। এডমিন এটি শীঘ্রই সম্পন্ন করবেন।</div>';
    } catch (Exception $e) { $conn->rollback(); $message = '<div class="alert alert-danger">অর্ডার ব্যর্থ হয়েছে: '.$e->getMessage().'</div>'; }
}
?>
<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>অফার কিনুন</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>body{background-color:#f4f7fa;}.number-input-group {position: relative;}.operator-logo {position: absolute; right: 15px; top: 10px; height: 30px;}</style>
</head><body>
<div class="container my-4" style="max-width: 500px;">
    <div class="d-flex align-items-center mb-3"><a href="packages.php" class="text-dark fs-4 me-3 text-decoration-none"><i class="fas fa-arrow-left"></i></a><h3 class="mb-0">অফারটি কিনুন</h3></div>
    <div class="card"><div class="card-body p-4">
        <h5 class="card-title"><?php echo htmlspecialchars($offer['offer_name']); ?></h5><p class="card-text text-muted">অপারেটর: <?php echo htmlspecialchars($offer['operator']); ?></p>
        <div class="my-3"><span class="fs-5">আপনার জন্য মূল্য:</span><span class="fs-2 fw-bold text-primary">৳<?php echo number_format($offer['final_price'], 2); ?></span></div><hr>
        <?php if(!empty($message)) echo $message; ?>
        <form id="packageForm" method="POST">
            <div class="mb-3"><label class="form-label fw-bold">মোবাইল নম্বর</label>
            <div class="number-input-group"><input type="tel" name="target_mobile" id="targetMobile" class="form-control form-control-lg" placeholder="যে নম্বরে অফার পাঠাবেন" required><img src="" id="operatorLogo" class="operator-logo" style="display:none;"></div>
            <small id="operatorError" class="text-danger"></small></div>
            <div class="d-grid mt-4"><button type="button" id="openConfirmModalBtn" class="btn btn-success btn-lg">অফারটি কিনুন</button></div>
        </form>
    </div></div>
</div>

<div class="modal fade" id="confirmationModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
<div class="modal-header"><h5 class="modal-title">ক্রয় নিশ্চিত করুন</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body">
    <p>আপনি কি <strong id="confirmNumber"></strong> নম্বরে অফারটি পাঠাতে চান?</p>
    <div class="mb-3"><label for="transactionPin" class="form-label">আপনার ৪-সংখ্যার লেনদেন পিন দিন</label><input type="password" class="form-control" id="transactionPin" inputmode="numeric" maxlength="4" placeholder="••••" required></div>
</div>
<div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button><button type="button" class="btn btn-success" id="confirmBuyBtn">নিশ্চিত করুন</button></div>
</div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const mobileInput = document.getElementById('targetMobile');
    const operatorLogo = document.getElementById('operatorLogo');
    const openModalBtn = document.getElementById('openConfirmModalBtn');
    const operatorError = document.getElementById('operatorError');
    const packageOperator = '<?php echo $offer['operator']; ?>';

    const operatorPrefixes = { 'Grameenphone': ['017', '013'], 'Robi': ['018', '016'], 'Banglalink': ['019', '014'], 'Airtel': ['011'], 'Teletalk': ['015'] };
    const operatorLogos = { 'Grameenphone': 'gp.png', 'Robi': 'robi.png', 'Banglalink': 'bl.png', 'Airtel': 'airtel.png', 'Teletalk': 'teletalk.png' };

    mobileInput.addEventListener('keyup', function() {
        const number = this.value; let currentOperator = 'unknown';
        for (const [op, prefixes] of Object.entries(operatorPrefixes)) {
            if (prefixes.some(p => number.startsWith(p))) { currentOperator = op; break; }
        }
        if (currentOperator !== 'unknown') {
            operatorLogo.src = `assets/images/operators/${operatorLogos[currentOperator]}`;
            operatorLogo.style.display = 'block';
            if (currentOperator === packageOperator) {
                operatorError.innerText = '';
                openModalBtn.disabled = false;
            } else {
                operatorError.innerText = `এই অফারটি শুধুমাত্র ${packageOperator} নম্বরের জন্য প্রযোজ্য।`;
                openModalBtn.disabled = true;
            }
        } else {
            operatorLogo.style.display = 'none';
            operatorError.innerText = '';
            openModalBtn.disabled = true;
        }
    });

    const confirmationModal = new bootstrap.Modal(document.getElementById('confirmationModal'));
    openModalBtn.addEventListener('click', function() {
        document.getElementById('confirmNumber').innerText = mobileInput.value;
        confirmationModal.show();
    });

    document.getElementById('confirmBuyBtn').addEventListener('click', function() {
        const pin = document.getElementById('transactionPin').value;
        if (!pin || pin.length !== 4) { alert('সঠিক পিন দিন।'); return; }
        const hiddenPinInput = document.createElement('input');
        hiddenPinInput.type = 'hidden'; hiddenPinInput.name = 'transaction_pin'; hiddenPinInput.value = pin;
        document.getElementById('packageForm').appendChild(hiddenPinInput);
        document.getElementById('packageForm').submit();
    });
</script>
</body></html>