<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('header.php');
$page_title  = WEB_NAME . " | Buy Data";
$page_title2 = "Buy Data";

$user_balance = (float)$user['main_balance'];

// Fetch active data plans
try {
    $plans_stmt = $pdo->query("SELECT * FROM vtu_data_plans WHERE status = 1 ORDER BY network ASC, sell_price ASC");
    $all_plans  = $plans_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $all_plans = []; }

// Group by network
$grouped_plans = [];
foreach ($all_plans as $p) {
    $grouped_plans[$p['network']][] = $p;
}
$networks      = array_keys($grouped_plans);
$first_network = $networks[0] ?? '';
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}
.data-hero{background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 35%,#4D148C 70%,#4D148C 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:16px}
.data-hero::before{content:'';position:absolute;inset:0;background:repeating-linear-gradient(45deg,transparent,transparent 40px,rgba(77,20,140,.012) 40px,rgba(77,20,140,.012) 41px);pointer-events:none}
.vtu-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:16px;padding:20px;margin-bottom:14px}
.net-tab{padding:8px 16px;border-radius:10px;font-size:.78rem;font-weight:700;cursor:pointer;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);transition:all .15s;white-space:nowrap}
.net-tab.active{background:rgba(77,20,140,.1);border-color:rgba(77,20,140,.35);color:#4D148C}
.net-tab:hover:not(.active){border-color:rgba(77,20,140,.2);color:var(--text-primary)}
.plan-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;margin-top:14px}
.plan-card{border:1.5px solid var(--card-border);border-radius:13px;padding:12px;cursor:pointer;transition:all .2s;background:var(--card-bg);text-align:center}
.plan-card:hover{border-color:rgba(77,20,140,.35);transform:translateY(-2px);box-shadow:0 6px 18px rgba(77,20,140,.12)}
.plan-card.selected{border-color:#4D148C;background:rgba(77,20,140,.07);box-shadow:0 0 0 3px rgba(77,20,140,.12)}
.form-label{font-size:.78rem;font-weight:700;color:var(--text-primary);margin-bottom:6px;display:block}
.form-input{width:100%;padding:11px 14px;border-radius:11px;border:1.5px solid var(--card-border);background:var(--input-bg,var(--card-bg));color:var(--text-primary);font-size:.85rem;outline:none;transition:border-color .2s;box-sizing:border-box}
.form-input:focus{border-color:rgba(77,20,140,.45)}
.form-select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%2364748b' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center}
.buy-btn{width:100%;padding:13px;border-radius:12px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:800;font-size:.9rem;border:none;cursor:pointer;transition:all .25s;display:flex;align-items:center;justify-content:center;gap:8px}
.buy-btn:hover{transform:translateY(-1px);box-shadow:0 6px 20px rgba(77,20,140,.3)}
.buy-btn:disabled{opacity:.6;cursor:not-allowed;transform:none}
.summary-row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--card-border);font-size:.8rem}
.summary-row:last-child{border-bottom:none}
</style>

<div class="max-w-xl mx-auto">

<!-- Hero -->
<div class="data-hero anim anim-1">
    <div style="position:absolute;width:150px;height:150px;border-radius:50%;filter:blur(55px);background:radial-gradient(circle,rgba(77,20,140,.3),transparent);top:-40px;right:-40px;pointer-events:none"></div>
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:14px">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;margin-bottom:4px;display:flex;align-items:center;gap:8px">
                <i class="fas fa-wifi text-emerald-300 text-base"></i>Buy Mobile Data
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">Instant data delivery — MTN, GLO, Airtel &amp; 9Mobile.</p>
        </div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
            <div style="background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.15);border-radius:10px;padding:10px 16px;text-align:center">
                <p style="font-size:.6rem;color:rgba(255,255,255,.55);font-weight:700;text-transform:uppercase;letter-spacing:.06em">Balance</p>
                <p id="heroBalance" style="font-weight:800;color:white;font-size:.95rem;font-family:monospace">₦<?php echo number_format($user_balance, 2); ?></p>
            </div>
            <a href="fund-wallet" style="background:white;color:#4D148C;font-weight:700;font-size:.78rem;padding:10px 16px;border-radius:10px;text-decoration:none;display:inline-flex;align-items:center;gap:6px">
                <i class="fas fa-plus text-xs"></i>Add Funds
            </a>
        </div>
    </div>
</div>

<!-- Network Tabs -->
<div class="anim anim-1" style="display:flex;gap:8px;overflow-x:auto;padding-bottom:4px;margin-bottom:14px;-webkit-overflow-scrolling:touch">
    <?php foreach ($networks as $i => $net): ?>
    <button class="net-tab <?php echo $i === 0 ? 'active' : ''; ?>" data-net="<?php echo htmlspecialchars($net); ?>">
        <?php echo htmlspecialchars($net); ?>
    </button>
    <?php endforeach; ?>
</div>

<!-- Purchase Form -->
<div class="vtu-card anim anim-2">
    <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:18px;display:flex;align-items:center;gap:8px">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(77,20,140,.1);display:inline-flex;align-items:center;justify-content:center">
            <i class="fas fa-wifi" style="font-size:.72rem;color:#4D148C"></i>
        </span>
        Select a Plan
    </h3>

    <!-- Plan type filter — CHANGED: All, Daily, Weekly, Monthly -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="planTypeFilter">Filter by Plan Type</label>
        <select id="planTypeFilter" class="form-input form-select">
            <option value="">All</option>
            <option value="DAILY">Daily</option>
            <option value="WEEKLY">Weekly</option>
            <option value="MONTHLY">Monthly</option>
        </select>
    </div>

    <!-- Plans grids — one per network, PHP renders all, JS shows/hides -->
    <?php foreach ($grouped_plans as $net => $plans): ?>
    <div class="plan-grid"
         id="plans_<?php echo htmlspecialchars($net); ?>"
         style="display:<?php echo $net === $first_network ? 'grid' : 'none'; ?>">
        <?php foreach ($plans as $p): ?>
        <div class="plan-card"
             data-id="<?php echo (int)$p['id']; ?>"
             data-price="<?php echo (float)$p['sell_price']; ?>"
             data-name="<?php echo htmlspecialchars($p['plan_name'], ENT_QUOTES); ?>"
             data-size="<?php echo htmlspecialchars($p['data_size'], ENT_QUOTES); ?>"
             data-validity="<?php echo htmlspecialchars($p['validity'], ENT_QUOTES); ?>"
             data-type="<?php echo htmlspecialchars($p['plan_type'], ENT_QUOTES); ?>"
             data-network="<?php echo htmlspecialchars($net, ENT_QUOTES); ?>">
            <p style="font-weight:800;font-size:1rem;color:var(--text-primary)"><?php echo htmlspecialchars($p['data_size']); ?></p>
            <p style="font-size:.65rem;color:var(--text-muted);margin:2px 0"><?php echo htmlspecialchars($p['validity']); ?></p>
            <p style="font-weight:700;font-size:.82rem;color:#4D148C;margin-top:4px">₦<?php echo number_format($p['sell_price'], 2); ?></p>
            <p style="font-size:.6rem;color:var(--text-muted);margin-top:2px"><?php echo htmlspecialchars($p['plan_type']); ?></p>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endforeach; ?>

    <!-- Phone input (shown after a plan is selected) -->
    <div id="phoneSection" style="display:none;margin-top:20px">
        <label class="form-label" for="phoneNumber">Phone Number</label>
        <input type="tel" id="phoneNumber" class="form-input" placeholder="e.g. 08012345678" maxlength="11">
    </div>

    <!-- Summary box -->
    <div id="summaryBox" style="display:none;background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.15);border-radius:13px;padding:14px;margin-top:16px">
        <p style="font-size:.75rem;font-weight:700;color:#4D148C;margin-bottom:10px;display:flex;align-items:center;gap:6px">
            <i class="fas fa-receipt"></i> Order Summary
        </p>
        <div class="summary-row"><span style="color:var(--text-muted)">Network</span><span id="sum_network" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Plan</span><span id="sum_plan" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Validity</span><span id="sum_validity" style="color:var(--text-muted)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Phone</span><span id="sum_phone" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Amount</span><span id="sum_amount" style="font-weight:800;color:#4D148C;font-family:monospace">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Balance After</span><span id="sum_balance_after" style="font-weight:700;font-family:monospace;color:var(--text-primary)">—</span></div>
    </div>

    <!-- Hidden fields -->
    <input type="hidden" id="selectedPlanId"   value="">
    <input type="hidden" id="selectedNetwork"  value="">
    <input type="hidden" id="selectedPrice"    value="">
    <input type="hidden" id="selectedPlanType" value="">

    <!-- Buy button -->
    <button class="buy-btn" id="buyBtn" style="margin-top:18px" disabled>
        <i class="fas fa-bolt"></i> <span id="buyBtnText">Buy Data</span>
    </button>

    <p style="text-align:center;font-size:.7rem;color:var(--text-muted);margin-top:10px">
        <i class="fas fa-shield-halved text-xs"></i> Instant delivery · Deducted from wallet balance
    </p>
</div>

<!-- Tips — CHANGED: Updated to reflect Daily/Weekly/Monthly types -->
<div class="anim anim-3" style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:13px;padding:14px;margin-bottom:16px;display:flex;gap:12px;align-items:flex-start">
    <div style="width:36px;height:36px;border-radius:10px;background:rgba(77,20,140,.08);border:1px solid rgba(77,20,140,.15);display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <i class="fas fa-circle-info" style="color:#4D148C;font-size:.85rem"></i>
    </div>
    <div>
        <p style="font-weight:700;font-size:.8rem;color:var(--text-primary);margin-bottom:4px">Quick Tips</p>
        <ul style="font-size:.73rem;color:var(--text-muted);line-height:1.8;padding-left:14px">
            <li><strong>Daily</strong> plans are ideal for short-term, one-day usage</li>
            <li><strong>Weekly</strong> plans last up to 7–14 days — great for moderate use</li>
            <li><strong>Monthly</strong> plans give you data for 30 days — best value</li>
            <li>Data is delivered within seconds of payment</li>
            <li>Contact support if delivery takes more than 5 minutes</li>
        </ul>
    </div>
</div>

</div><!-- /max-w -->

<!-- Confirmation Modal -->
<div id="confirmModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;align-items:center;justify-content:center;padding:16px">
    <div style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:20px;padding:24px;max-width:360px;width:100%">
        <div style="text-align:center;margin-bottom:20px">
            <div style="width:56px;height:56px;border-radius:50%;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;margin:0 auto 12px">
                <i class="fas fa-wifi" style="font-size:1.3rem;color:#4D148C"></i>
            </div>
            <h3 style="font-weight:800;font-size:1rem;color:var(--text-primary);margin-bottom:4px">Confirm Purchase</h3>
            <p style="font-size:.78rem;color:var(--text-muted)">Please confirm your data purchase below</p>
        </div>
        <div id="modalSummary" style="background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.15);border-radius:12px;padding:14px;margin-bottom:20px;font-size:.8rem"></div>
        <div style="display:flex;gap:10px">
            <button id="cancelBtn" style="flex:1;padding:11px;border-radius:10px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);font-weight:700;cursor:pointer">Cancel</button>
            <button id="confirmBtn" style="flex:2;padding:11px;border-radius:10px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:800;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">
                <i class="fas fa-check"></i> Confirm
            </button>
        </div>
    </div>
</div>

<!-- jQuery (load after HTML so it's definitely available) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
(function() {
    'use strict';

    // ── State ─────────────────────────────────────────────────────────────────
    var userBalance  = <?php echo json_encode($user_balance); ?>;
    var selectedPlan = null;

    // ── DOM refs ──────────────────────────────────────────────────────────────
    var $planTypeFilter  = document.getElementById('planTypeFilter');
    var $phoneNumber     = document.getElementById('phoneNumber');
    var $phoneSection    = document.getElementById('phoneSection');
    var $summaryBox      = document.getElementById('summaryBox');
    var $buyBtn          = document.getElementById('buyBtn');
    var $buyBtnText      = document.getElementById('buyBtnText');
    var $confirmModal    = document.getElementById('confirmModal');
    var $confirmBtn      = document.getElementById('confirmBtn');
    var $cancelBtn       = document.getElementById('cancelBtn');

    // ── Network tab switching ─────────────────────────────────────────────────
    document.querySelectorAll('.net-tab').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var net = this.dataset.net;
            document.querySelectorAll('.net-tab').forEach(function(b){ b.classList.remove('active'); });
            this.classList.add('active');
            document.querySelectorAll('[id^="plans_"]').forEach(function(el){ el.style.display = 'none'; });
            var grid = document.getElementById('plans_' + net);
            if (grid) grid.style.display = 'grid';
            clearSelection();
        });
    });

    // ── Plan type filter ──────────────────────────────────────────────────────
    $planTypeFilter.addEventListener('change', function() {
        var type = this.value;
        document.querySelectorAll('.plan-card').forEach(function(card) {
            card.style.display = (!type || card.dataset.type === type) ? 'block' : 'none';
        });
        clearSelection();
    });

    // ── Plan card selection ───────────────────────────────────────────────────
    document.querySelectorAll('.plan-card').forEach(function(card) {
        card.addEventListener('click', function() {
            document.querySelectorAll('.plan-card').forEach(function(c){ c.classList.remove('selected'); });
            this.classList.add('selected');
            selectedPlan = {
                id:       this.dataset.id,
                name:     this.dataset.name,
                size:     this.dataset.size,
                validity: this.dataset.validity,
                price:    parseFloat(this.dataset.price),
                network:  this.dataset.network,
                type:     this.dataset.type,
            };
            document.getElementById('selectedPlanId').value    = selectedPlan.id;
            document.getElementById('selectedNetwork').value   = selectedPlan.network;
            document.getElementById('selectedPrice').value     = selectedPlan.price;
            document.getElementById('selectedPlanType').value  = selectedPlan.type;
            $phoneSection.style.display = 'block';
            updateSummary();
        });
    });

    // ── Phone input listener ──────────────────────────────────────────────────
    $phoneNumber.addEventListener('input', updateSummary);

    // ── Clear selection ───────────────────────────────────────────────────────
    function clearSelection() {
        selectedPlan = null;
        document.querySelectorAll('.plan-card').forEach(function(c){ c.classList.remove('selected'); });
        $phoneSection.style.display = 'none';
        $summaryBox.style.display   = 'none';
        $buyBtn.disabled            = true;
        $buyBtnText.textContent     = 'Buy Data';
    }

    // ── Update summary ────────────────────────────────────────────────────────
    function updateSummary() {
        if (!selectedPlan) return;
        var phone = $phoneNumber.value.trim();
        var after = userBalance - selectedPlan.price;

        document.getElementById('sum_network').textContent      = selectedPlan.network;
        document.getElementById('sum_plan').textContent         = selectedPlan.name;
        document.getElementById('sum_validity').textContent     = selectedPlan.validity;
        document.getElementById('sum_phone').textContent        = phone || '—';
        document.getElementById('sum_amount').textContent       = '₦' + selectedPlan.price.toLocaleString('en-NG', {minimumFractionDigits:2});
        document.getElementById('sum_balance_after').textContent = after >= 0
            ? '₦' + after.toLocaleString('en-NG', {minimumFractionDigits:2})
            : '⚠ Insufficient balance';
        $summaryBox.style.display = 'block';

        var ok = phone.length >= 10 && after >= 0;
        $buyBtn.disabled        = !ok;
        $buyBtnText.textContent = ok
            ? 'Buy ' + selectedPlan.size + ' — ₦' + selectedPlan.price.toLocaleString('en-NG', {minimumFractionDigits:2})
            : 'Buy Data';
    }

    // ── Buy button → show modal ───────────────────────────────────────────────
    $buyBtn.addEventListener('click', function() {
        var phone = $phoneNumber.value.trim();
        if (!selectedPlan)          { showAlert('Please select a plan', 'error'); return; }
        if (phone.length < 10)      { showAlert('Enter a valid phone number', 'error'); return; }
        if (userBalance < selectedPlan.price) { showAlert('Insufficient wallet balance. Please fund your wallet.', 'error'); return; }

        document.getElementById('modalSummary').innerHTML =
            '<div style="display:flex;flex-direction:column;gap:8px">' +
            '<div style="display:flex;justify-content:space-between"><span style="color:var(--text-muted)">Network</span><strong>' + selectedPlan.network + '</strong></div>' +
            '<div style="display:flex;justify-content:space-between"><span style="color:var(--text-muted)">Plan</span><strong>' + selectedPlan.name + '</strong></div>' +
            '<div style="display:flex;justify-content:space-between"><span style="color:var(--text-muted)">Phone</span><strong>' + phone + '</strong></div>' +
            '<div style="display:flex;justify-content:space-between"><span style="color:var(--text-muted)">Amount</span><strong style="color:#4D148C">₦' + selectedPlan.price.toLocaleString('en-NG', {minimumFractionDigits:2}) + '</strong></div>' +
            '</div>';
        $confirmModal.style.display = 'flex';
    });

    // ── Cancel modal ──────────────────────────────────────────────────────────
    $cancelBtn.addEventListener('click', function() {
        $confirmModal.style.display = 'none';
    });

    // ── Process purchase ──────────────────────────────────────────────────────
    $confirmBtn.addEventListener('click', function() {
        var btn = this;
        btn.disabled   = true;
        btn.innerHTML  = '<i class="fas fa-spinner fa-spin"></i> Processing...';

        $.post('ajax/vtu-purchase.php', {
            action:    'buy_data',
            plan_id:   document.getElementById('selectedPlanId').value,
            phone:     $phoneNumber.value.trim(),
            network:   document.getElementById('selectedNetwork').value,
            amount:    document.getElementById('selectedPrice').value,
            plan_type: document.getElementById('selectedPlanType').value,
        }, function(res) {
            $confirmModal.style.display = 'none';
            if (res.status === '1') {
                showAlert(res.msg || 'Data purchased successfully!', 'success');
                setTimeout(function(){ window.location.href = 'vtu-history'; }, 2000);
            } else {
                showAlert(res.msg || 'Purchase failed. Please try again.', 'error');
                btn.disabled  = false;
                btn.innerHTML = '<i class="fas fa-check"></i> Confirm';
            }
        }, 'json').fail(function() {
            $confirmModal.style.display = 'none';
            showAlert('Network error. Please try again.', 'error');
            btn.disabled  = false;
            btn.innerHTML = '<i class="fas fa-check"></i> Confirm';
        });
    });

    // ── Alert helper ──────────────────────────────────────────────────────────
    function showAlert(msg, type) {
        var el = document.createElement('div');
        el.style.cssText = 'position:fixed;top:20px;left:50%;transform:translateX(-50%);z-index:99999;padding:12px 20px;border-radius:12px;font-size:.82rem;font-weight:700;color:white;background:' + (type === 'success' ? '#4D148C' : '#ef4444') + ';box-shadow:0 4px 16px rgba(0,0,0,.2);max-width:90vw;text-align:center';
        el.textContent = msg;
        document.body.appendChild(el);
        setTimeout(function(){ el.remove(); }, 3500);
    }

})();
</script>

<?php include('footer.php'); ?>