<?php
session_start();
require __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/cowpay_gateway_helper.php';

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

cowpay_ensure_schema($conn);
$uid = intval($_SESSION['user_id']);
$user = $conn->query("SELECT * FROM users WHERE id=$uid")->fetch_assoc();
$settings = $conn->query("SELECT * FROM settings WHERE id=1")->fetch_assoc();

$cowpay_settings = cowpay_get_settings($conn);
$txn_settings = function_exists('propay_get_site_transaction_settings')
    ? propay_get_site_transaction_settings($conn)
    : array('min_deposit_amount' => 100, 'deposit_bonus_bkash' => 0, 'deposit_bonus_nagad' => 0);

$notice_text = !empty($settings['deposit_notice']) 
    ? $settings['deposit_notice'] 
    : 'ডিপোজিট করার পর আপনার bKash/Nagad ID জমা দিন। সর্বদা সর্বশেষ অ্যাকাউন্ট ব্যবহার করুন।';

$promotions = $conn->query("SELECT id, title FROM promotions WHERE status='active' AND (category IN ('all','deposit') OR category='' OR category IS NULL) AND (start_date IS NULL OR start_date <= CURDATE()) AND (end_date IS NULL OR end_date >= CURDATE()) ORDER BY id DESC")->fetch_all(MYSQLI_ASSOC);

$min_deposit = max(1, (float)($txn_settings['min_deposit_amount'] ?? 100));
$max_deposit = 50000;
$bkash_bonus = max(0, (float)($txn_settings['deposit_bonus_bkash'] ?? 0));
$nagad_bonus = max(0, (float)($txn_settings['deposit_bonus_nagad'] ?? 0));

$fast_amts = [100, 300, 500, 1000, 3000, 5000, 10000, 30000, 50000];
$fast_amts = array_values(array_filter($fast_amts, function($v) use ($min_deposit) {
    return $v >= $min_deposit;
}));

$cowpay_ready = (intval($cowpay_settings['is_enabled'] ?? 0) === 1)
    && trim($cowpay_settings['merchant_code'] ?? '') !== ''
    && trim($cowpay_settings['secret_code'] ?? '') !== '';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>জমা দিন</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { box-sizing: border-box; }
        body {
            background: #f5f6f8;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            padding-bottom: 100px;
            margin: 0;
        }
        .header-bar {
            background: #0d4a3a;
            color: #fff;
            padding: 14px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 50;
        }
        .header-bar h1 {
            font-size: 17px;
            font-weight: 700;
            margin: 0;
        }
        .section-title {
            font-size: 14px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .section-title::before {
            content: '';
            width: 6px;
            height: 6px;
            background: #f59e0b;
            border-radius: 50%;
            display: inline-block;
        }
        .method-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
        }
        .method-card {
            background: #fff;
            border: 1.5px solid #e5e7eb;
            border-radius: 10px;
            padding: 12px 6px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 88px;
            position: relative;
            cursor: pointer;
            transition: 0.2s;
        }
        .method-card.active {
            border-color: #0d4a3a;
            background: #f0fdf9;
        }
        .method-card.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            width: 0;
            height: 0;
            border-style: solid;
            border-width: 0 0 18px 18px;
            border-color: transparent transparent #0d4a3a transparent;
        }
        .method-card img, .method-icon {
            height: 32px;
            width: auto;
            margin-bottom: 6px;
            object-fit: contain;
        }
        .method-card span {
            font-size: 11px;
            font-weight: 700;
            color: #333;
            text-align: center;
        }
        .bonus-tag {
            position: absolute;
            top: -6px;
            right: -4px;
            background: #ef4444;
            color: #fff;
            font-size: 9px;
            font-weight: 800;
            padding: 1px 5px;
            border-radius: 4px;
        }
        .note-box {
            background: #fff;
            border-radius: 8px;
            padding: 12px 14px;
            margin-top: 14px;
            font-size: 12px;
            color: #dc2626;
            line-height: 1.55;
            border: 1px solid #fecaca;
        }
        .amt-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 8px;
        }
        .amt-btn {
            background: #fff;
            border: 1.5px solid #e5e7eb;
            border-radius: 8px;
            padding: 11px 0;
            font-size: 13px;
            font-weight: 700;
            color: #333;
            text-align: center;
            cursor: pointer;
            transition: 0.15s;
        }
        .amt-btn.active {
            border-color: #0d4a3a;
            background: #0d4a3a;
            color: #fff;
        }
        .amount-input-wrap {
            margin-top: 14px;
            background: #fff;
            border: 1.5px solid #e5e7eb;
            border-radius: 10px;
            padding: 12px 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .amount-input-wrap span {
            font-size: 16px;
            font-weight: 700;
            color: #0d4a3a;
        }
        .amount-input-wrap input {
            border: none;
            outline: none;
            font-size: 16px;
            font-weight: 600;
            width: 100%;
            color: #111;
            background: transparent;
        }
        .next-btn {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #fff;
            padding: 12px 20px 20px;
            box-shadow: 0 -4px 20px rgba(0,0,0,0.06);
            z-index: 40;
        }
        .next-btn button {
            width: 100%;
            background: #2563eb;
            color: #fff;
            border: none;
            border-radius: 50px;
            padding: 14px;
            font-size: 16px;
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            cursor: pointer;
        }
        .next-btn button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .promo-box {
            background: #fff;
            border: 1.5px dashed #a7f3d0;
            border-radius: 10px;
            padding: 12px 14px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
            margin-bottom: 18px;
        }
        .promo-dropdown {
            display: none;
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 0 0 10px 10px;
            margin-top: -6px;
            overflow: hidden;
        }
        .promo-dropdown.show { display: block; }
        .promo-item {
            padding: 12px 14px;
            font-size: 13px;
            font-weight: 600;
            color: #374151;
            border-bottom: 1px solid #f3f4f6;
            cursor: pointer;
        }
        .promo-item:hover { background: #f9fafb; }
        .error-box {
            margin: 12px 16px 0;
            padding: 12px 14px;
            background: #fef2f2;
            border: 1px solid #fecaca;
            border-radius: 10px;
            color: #b91c1c;
            font-size: 13px;
            font-weight: 600;
        }
    </style>
</head>
<body>

    <!-- Header -->
    <div class="header-bar">
        <button onclick="window.history.back()" style="background:none;border:none;color:#fff;font-size:18px;padding:4px 8px;">
            <i class="fas fa-chevron-left"></i>
        </button>
        <h1>জমা দিন</h1>
        <div style="width:36px;"></div>
    </div>

    <?php if (!empty($_SESSION['deposit_error'])): ?>
    <div class="error-box">
        <i class="fas fa-exclamation-circle"></i>
        <?php echo htmlspecialchars($_SESSION['deposit_error']); unset($_SESSION['deposit_error']); ?>
    </div>
    <?php endif; ?>

    <?php if (!$cowpay_ready): ?>
    <div class="error-box">
        <i class="fas fa-exclamation-triangle"></i>
        Payment gateway is currently unavailable. Please contact support.
    </div>
    <?php endif; ?>

    <form id="depositForm" action="cowpay_deposit_start.php" method="POST" onsubmit="return validateDepositForm()" style="padding:16px;">

        <!-- Promotion -->
        <div class="relative" style="margin-bottom:18px;">
            <div class="promo-box" onclick="togglePromo()">
                <span id="selectedPromoLabel" style="font-size:13px;font-weight:600;color:#0d4a3a;">
                    <i class="fas fa-gift" style="margin-right:6px;"></i> Regular Deposit
                </span>
                <i class="fas fa-chevron-down" style="color:#9ca3af;font-size:12px;"></i>
            </div>
            <input type="hidden" name="promo_id" id="promoIdInput" value="0">
            <div id="promoDropdownList" class="promo-dropdown">
                <div class="promo-item" onclick="selectPromo('Regular Deposit', 0)">Regular Deposit</div>
                <?php foreach ($promotions as $p): ?>
                    <div class="promo-item" onclick="selectPromo('<?php echo addslashes($p['title']); ?>', <?php echo intval($p['id']); ?>)">
                        <?php echo htmlspecialchars($p['title'], ENT_QUOTES, 'UTF-8'); ?>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Payment Methods -->
        <div class="section-title">আমানতের মোড</div>
        <div class="method-grid">
            <!-- Nagad -->
            <label>
                <input type="radio" name="method" value="Nagad" class="hidden" onchange="updateUI()">
                <div class="method-card" id="card-nagad">
                    <?php if ($nagad_bonus > 0): ?>
                        <span class="bonus-tag">+<?php echo rtrim(rtrim(number_format($nagad_bonus, 1), '0'), '.'); ?>%</span>
                    <?php endif; ?>
                    <img src="https://freelogopng.com/images/all_img/1679248828Nagad-Logo-PNG.png" alt="Nagad">
                    <span>NAGAD</span>
                </div>
            </label>

            <!-- bKash -->
            <label>
                <input type="radio" name="method" value="bKash" class="hidden" onchange="updateUI()" checked>
                <div class="method-card active" id="card-bkash">
                    <?php if ($bkash_bonus > 0): ?>
                        <span class="bonus-tag">+<?php echo rtrim(rtrim(number_format($bkash_bonus, 1), '0'), '.'); ?>%</span>
                    <?php endif; ?>
                    <img src="https://freelogopng.com/images/all_img/1656234745bkash-app-logo-png.png" alt="bKash">
                    <span>Bkash</span>
                </div>
            </label>
        </div>

        <!-- Note -->
        <div class="note-box">
            ডিপোজিট করার নোট: ডিপোজিট করার পর আপনার bKash/Nagad-ID জমা দিন। সর্বদা সর্বশেষ অ্যাকাউন্ট ব্যবহার করুন। ব্যর্থতা এড়াতে পুরানো অ্যাকাউন্ট তথ্য পুনরায় ব্যবহার করবেন না।
        </div>

        <!-- Amount -->
        <div style="margin-top:22px;">
            <div class="section-title">জমা পরিমাণ</div>
            <div class="amt-grid">
                <?php foreach ($fast_amts as $a): ?>
                    <button type="button" class="amt-btn" data-val="<?php echo $a; ?>" onclick="setAmt(<?php echo $a; ?>, this)">
                        <?php echo number_format($a); ?>
                    </button>
                <?php endforeach; ?>
            </div>

            <div class="amount-input-wrap">
                <span>৳</span>
                <input type="number" name="amount" id="amtInput" 
                       placeholder="<?php echo number_format($min_deposit); ?> - <?php echo number_format($max_deposit); ?>" 
                       min="<?php echo $min_deposit; ?>" 
                       max="<?php echo $max_deposit; ?>"
                       oninput="syncAmtButtons()">
            </div>
        </div>

        <!-- Hidden submit via bottom button -->
        <div class="next-btn">
            <button type="submit" id="submitBtn" <?php echo !$cowpay_ready ? 'disabled' : ''; ?>>
                পরবর্তী <i class="fas fa-arrow-down" style="font-size:14px;"></i>
            </button>
        </div>
    </form>

    

    <script>
    const minDeposit = <?php echo json_encode((float)$min_deposit); ?>;
    const maxDeposit = <?php echo json_encode((float)$max_deposit); ?>;
    const cowpayReady = <?php echo $cowpay_ready ? 'true' : 'false'; ?>;

    // Default select bKash
    document.querySelector('input[value="bKash"]').checked = true;

    function togglePromo() {
        document.getElementById('promoDropdownList').classList.toggle('show');
    }

    function selectPromo(title, id) {
        document.getElementById('selectedPromoLabel').innerHTML = '<i class="fas fa-gift" style="margin-right:6px;"></i> ' + title;
        document.getElementById('promoIdInput').value = id;
        document.getElementById('promoDropdownList').classList.remove('show');
    }

    function setAmt(v, btn) {
        document.getElementById('amtInput').value = v;
        document.querySelectorAll('.amt-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
    }

    function syncAmtButtons() {
        const val = document.getElementById('amtInput').value;
        document.querySelectorAll('.amt-btn').forEach(btn => {
            btn.classList.toggle('active', btn.getAttribute('data-val') == val);
        });
    }

    function updateUI() {
        document.querySelectorAll('.method-card').forEach(c => c.classList.remove('active'));
        const checked = document.querySelector('input[name="method"]:checked');
        if (checked) {
            checked.parentElement.querySelector('.method-card').classList.add('active');
        }
    }

    function validateDepositForm() {
        if (!cowpayReady) {
            alert('Payment gateway is currently unavailable.');
            return false;
        }
        const amount = parseFloat(document.getElementById('amtInput').value || 0);
        const method = document.querySelector('input[name="method"]:checked');
        if (!method) {
            alert('পেমেন্ট মেথড সিলেক্ট করুন');
            return false;
        }
        if (isNaN(amount) || amount < minDeposit) {
            alert('সর্বনিম্ন জমার পরিমাণ ৳' + minDeposit.toLocaleString('en-US'));
            return false;
        }
        if (amount > maxDeposit) {
            alert('সর্বোচ্চ জমার পরিমাণ ৳' + maxDeposit.toLocaleString('en-US'));
            return false;
        }
        return true;
    }
    </script>
</body>
</html>