<?php
require_once 'includes/db_connect.php';
require_once 'includes/gateway_handler.php'; // Include our Gateway Handler

if (!isset($_SESSION["user_id"])) { header("location: login.php"); exit; }

$message = '';
$user_id = $_SESSION['user_id'];

// This block runs after the user confirms the recharge with their PIN in the modal
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['transaction_pin'])) {
    $mobile_to_recharge = trim($_POST['mobile']);
    $amount = (float)$_POST['amount'];
    $pin = $_POST['transaction_pin'];

    if (empty($mobile_to_recharge) || $amount <= 0 || empty($pin)) {
        $message = '<div class="alert alert-danger">অনুগ্রহ করে সব তথ্য সঠিকভাবে পূরণ করুন।</div>';
    } else {
        $conn->begin_transaction();
        try {
            // 1. Fetch user data for verification
            $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();

            // 2. Perform all checks before calling the API
            if (is_null($user['transaction_pin'])) { throw new Exception("অনুগ্রহ করে প্রথমে প্রোফাইল পেজ থেকে আপনার লেনদেনের পিন সেট করুন।"); }
            if (!password_verify($pin, $user['transaction_pin'])) { throw new Exception("আপনার দেওয়া পিনটি সঠিক নয়।"); }
            if ($user['balance'] < $amount) { throw new Exception("আপনার একাউন্টে পর্যাপ্ত ব্যালেন্স নেই।"); }
            
            // 3. Call the dynamic Gateway Handler to process the recharge
            $api_response = processRecharge($conn, $mobile_to_recharge, $amount);

            if ($api_response['status'] !== 'success') {
                // If the API fails, the entire transaction will be rolled back
                throw new Exception("API গেটওয়ে থেকে রিচার্জ ব্যর্থ হয়েছে: " . ($api_response['message'] ?? 'Unknown Error'));
            }

            // 4. If API call was successful, update user's balance and log the transaction
            $stmt_update = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            $stmt_update->bind_param("di", $amount, $user_id);
            $stmt_update->execute();
            
            $description = "Recharge to " . $mobile_to_recharge . " (API Txn: " . ($api_response['transactionId'] ?? 'N/A') . ")";
            $stmt_insert = $conn->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'Recharge', ?, ?)");
            $stmt_insert->bind_param("ids", $user_id, $amount, $description);
            $stmt_insert->execute();
            
            $conn->commit();
            $message = '<div class="alert alert-success">'. htmlspecialchars($mobile_to_recharge) .' নম্বরে '. htmlspecialchars($amount) .' টাকা রিচার্জ সফল হয়েছে।</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; font-family: 'Noto Sans Bengali', sans-serif; }
    .recharge-card { background-color: white; border-radius: 1rem; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
    .header-bar { background-color: #dc3545; color: white; padding: 1rem; border-top-left-radius: 1rem; border-top-right-radius: 1rem; }
    .number-input-group { position: relative; }
    .number-input-group .form-control { padding-left: 45px; height: 50px; border: none; font-size: 1.1rem; }
    .number-input-group .fa-phone { position: absolute; left: 15px; top: 16px; color: #6c757d; }
    .operator-logo { position: absolute; right: 50px; top: 10px; height: 30px; transition: opacity 0.3s; }
    .contacts-icon { position: absolute; right: 15px; top: 12px; font-size: 1.5rem; color: #0d6efd; cursor: pointer; }
    .recharge-type-btn { border-radius: 20px; }
    .amount-input { border: 2px solid #dc3545; border-radius: 0.5rem; text-align: center; font-size: 1.5rem; font-weight: bold; }
    .quick-amount-btn { border: 1px solid #ddd; border-radius: 20px; margin: 0 5px; }
</style>
</head><body>
<div class="container my-4" style="max-width: 450px;">
    <div class="recharge-card">
        <div class="header-bar d-flex justify-content-between align-items-center">
            <a href="index.php" class="text-white fs-4 text-decoration-none"><i class="fas fa-arrow-left"></i></a>
            <h5 class="mb-0">মোবাইল রিচার্জ</h5>
            <div style="width: 24px;"></div>
        </div>
        <div class="p-3">
            <?php if(!empty($message)) echo $message; ?>
            <form id="rechargeForm" method="POST" action="recharge.php">
                <div class="mb-3">
                    <label class="form-label fw-bold">মোবাইল নম্বর</label>
                    <div class="number-input-group bg-light rounded">
                        <i class="fas fa-phone"></i>
                        <input type="tel" name="mobile" id="mobileNumber" class="form-control bg-transparent" placeholder="01XXXXXXXXX" required>
                        <img src="assets/images/operators/unknown.png" id="operatorLogo" class="operator-logo" alt="Operator">
                        <i class="fas fa-address-book contacts-icon"></i>
                    </div>
                </div>
                <div class="text-center my-3">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-danger recharge-type-btn">Prepaid</button>
                        <button type="button" class="btn btn-outline-secondary recharge-type-btn">Postpaid</button>
                        <button type="button" class="btn btn-outline-secondary recharge-type-btn">Skitto</button>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">পরিমাণ</label>
                    <input type="number" name="amount" id="rechargeAmount" class="form-control amount-input p-3" placeholder="0" required>
                </div>
                <div class="text-center my-3">
                    <button type="button" class="btn quick-amount-btn" onclick="setAmount(50)">50</button>
                    <button type="button" class="btn quick-amount-btn" onclick="setAmount(100)">100</button>
                    <button type="button" class="btn quick-amount-btn" onclick="setAmount(200)">200</button>
                    <button type="button" class="btn quick-amount-btn" onclick="setAmount(500)">500</button>
                </div>
                <div class="d-grid mt-4">
                    <button type="button" class="btn btn-primary btn-lg" id="openConfirmModalBtn">রিচার্জ করুন</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> নম্বরে <strong id="confirmAmount"></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="confirmRechargeBtn">নিশ্চিত করুন</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('mobileNumber');
    const operatorLogo = document.getElementById('operatorLogo');
    const amountInput = document.getElementById('rechargeAmount');

    // Operator Detection Logic
    mobileInput.addEventListener('keyup', function() {
        const number = this.value;
        let operator = 'unknown';
        if (number.startsWith('017') || number.startsWith('013')) operator = 'gp';
        else if (number.startsWith('018') || number.startsWith('016')) operator = 'robi';
        else if (number.startsWith('019') || number.startsWith('014')) operator = 'bl';
        else if (number.startsWith('015')) operator = 'teletalk';
        operatorLogo.src = `assets/images/operators/${operator}.png`;
    });

    // Quick Amount Setter
    function setAmount(value) {
        amountInput.value = value;
    }

    // Modal Handling Logic
    const confirmationModal = new bootstrap.Modal(document.getElementById('confirmationModal'));
    const openModalBtn = document.getElementById('openConfirmModalBtn');
    const confirmRechargeBtn = document.getElementById('confirmRechargeBtn');
    const rechargeForm = document.getElementById('rechargeForm');

    openModalBtn.addEventListener('click', function() {
        const mobile = mobileInput.value;
        const amount = amountInput.value;
        if (mobile.length >= 11 && amount > 0) {
            document.getElementById('confirmNumber').innerText = mobile;
            document.getElementById('confirmAmount').innerText = `৳${amount}`;
            confirmationModal.show();
        } else {
            alert('অনুগ্রহ করে সঠিক মোবাইল নম্বর এবং টাকার পরিমাণ দিন।');
        }
    });

    confirmRechargeBtn.addEventListener('click', function() {
        const pin = document.getElementById('transactionPin').value;
        if (!pin || pin.length !== 4) {
            alert('অনুগ্রহ করে আপনার ৪-সংখ্যার সঠিক পিন দিন।');
            return;
        }

        // Create a hidden input for the PIN and append it to the form
        const hiddenPinInput = document.createElement('input');
        hiddenPinInput.type = 'hidden';
        hiddenPinInput.name = 'transaction_pin';
        hiddenPinInput.value = pin;
        rechargeForm.appendChild(hiddenPinInput);

        // Submit the form
        rechargeForm.submit();
    });
</script>
</body></html>