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

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

// Flat-fee markup in NGN (stored in cdh_airtime_markup)
$air_flat_fee = floatval($site_data['cdh_airtime_markup'] ?? 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}
.air-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}
.air-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-btn{padding:10px 0;border-radius:12px;font-size:.82rem;font-weight:700;cursor:pointer;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);transition:all .15s;flex:1;text-align:center}
.net-btn.active{background:rgba(77,20,140,.1);border-color:rgba(77,20,140,.4);color:#4D148C}
.quick-amt{padding:9px 14px;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}
.quick-amt:hover{border-color:rgba(77,20,140,.3);color:var(--text-primary)}
.quick-amt.active{background:rgba(77,20,140,.08);border-color:rgba(77,20,140,.35);color:#4D148C}
.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)}
.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}

/* ── Toggle switch ── */
.toggle-wrap{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.12);border-radius:11px;margin-bottom:16px}
.toggle-switch{position:relative;display:inline-block;width:46px;height:26px;flex-shrink:0}
.toggle-switch input{opacity:0;width:0;height:0}
.toggle-slider{position:absolute;cursor:pointer;inset:0;background:#cbd5e1;border-radius:34px;transition:.3s}
.toggle-slider:before{content:'';position:absolute;height:20px;width:20px;left:3px;bottom:3px;background:white;border-radius:50%;transition:.3s}
.toggle-switch input:checked + .toggle-slider{background:#4D148C}
.toggle-switch input:checked + .toggle-slider:before{transform:translateX(20px)}
</style>

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

<!-- Hero -->
<div class="air-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-phone text-emerald-300 text-base"></i>Buy Airtime
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">Top up any network — MTN, GLO, Airtel &amp; 9Mobile instantly.</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 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>

<!-- 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-phone" style="font-size:.72rem;color:#4D148C"></i>
        </span>
        Airtime Purchase
    </h3>

    <!-- Network -->
    <div style="margin-bottom:16px">
        <label class="form-label">Select Network</label>
        <div style="display:flex;gap:8px">
            <button class="net-btn active" data-network="MTN">MTN</button>
            <button class="net-btn"        data-network="GLO">GLO</button>
            <button class="net-btn"        data-network="AIRTEL">AIRTEL</button>
            <button class="net-btn"        data-network="9MOBILE">9MOBILE</button>
        </div>
    </div>

    <!-- Phone -->
    <div style="margin-bottom:16px">
        <label class="form-label" for="airtimePhone">Phone Number</label>
        <input type="tel" id="airtimePhone" class="form-input" placeholder="e.g. 08012345678" maxlength="11">
    </div>

    <!-- Amount -->
    <div style="margin-bottom:14px">
        <label class="form-label">Amount (₦)</label>
        <div style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:10px">
            <button class="quick-amt" data-amount="50">₦50</button>
            <button class="quick-amt" data-amount="100">₦100</button>
            <button class="quick-amt" data-amount="200">₦200</button>
            <button class="quick-amt" data-amount="500">₦500</button>
            <button class="quick-amt" data-amount="1000">₦1,000</button>
            <button class="quick-amt" data-amount="2000">₦2,000</button>
        </div>
        <input type="number" id="airtimeAmount" class="form-input" placeholder="Or enter custom amount (min ₦50)" min="50" step="50">
    </div>

    <?php if ($air_flat_fee > 0): ?>
    <!-- Fee notice -->
    <div style="margin-bottom:14px;padding:10px 14px;background:rgba(77,20,140,.06);border:1px solid rgba(77,20,140,.2);border-radius:10px;font-size:.75rem;color:var(--text-muted)">
        <i class="fas fa-info-circle" style="color:#4D148C"></i>
        A service fee of <strong>₦<?php echo number_format($air_flat_fee, 2); ?></strong> is added to the airtime amount.
    </div>
    <?php endif; ?>

    <!-- Summary -->
    <div id="airtimeSummaryBox" style="display:none;background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.15);border-radius:13px;padding:14px;margin-bottom:16px">
        <p style="font-size:.75rem;font-weight:700;color:#4D148C;margin-bottom:10px"><i class="fas fa-receipt"></i> Order Summary</p>
        <div class="summary-row"><span style="color:var(--text-muted)">Network</span><span id="a_sum_net" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Phone</span><span id="a_sum_phone" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Airtime Value</span><span id="a_sum_value" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <?php if ($air_flat_fee > 0): ?>
        <div class="summary-row"><span style="color:var(--text-muted)">Service Fee</span><span id="a_sum_fee" style="color:var(--text-muted)">₦<?php echo number_format($air_flat_fee, 2); ?></span></div>
        <?php endif; ?>
        <div class="summary-row"><span style="color:var(--text-muted)">Total Charged</span><span id="a_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="a_sum_after" style="font-weight:700;font-family:monospace;color:var(--text-primary)">—</span></div>
    </div>

    <input type="hidden" id="selectedAirNetwork" value="MTN">

    <button class="buy-btn" id="airtimeBuyBtn" disabled>
        <i class="fas fa-bolt"></i> <span id="airtimeBtnText">Buy Airtime</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 recharge · Deducted from wallet
    </p>
</div>

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

<!-- Confirmation Modal -->
<div id="airtimeModal" 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-phone" 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 Airtime</h3>
            <p style="font-size:.78rem;color:var(--text-muted)">Review and confirm your airtime purchase</p>
        </div>
        <div id="airtimeModalSummary" 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="airtimeCancelBtn" 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="airtimeConfirmBtn" 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>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
(function() {
    'use strict';

    var airBalance = <?php echo json_encode($user_balance); ?>;
    var flatFee    = <?php echo json_encode($air_flat_fee); ?>;

    // ── Network buttons ───────────────────────────────────────────────────────
    document.querySelectorAll('.net-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.net-btn').forEach(function(b){ b.classList.remove('active'); });
            this.classList.add('active');
            document.getElementById('selectedAirNetwork').value = this.dataset.network;
            updateSummary();
        });
    });

    // ── Quick amounts ─────────────────────────────────────────────────────────
    document.querySelectorAll('.quick-amt').forEach(function(btn) {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.quick-amt').forEach(function(b){ b.classList.remove('active'); });
            this.classList.add('active');
            document.getElementById('airtimeAmount').value = this.dataset.amount;
            updateSummary();
        });
    });

    document.getElementById('airtimeAmount').addEventListener('input', function() {
        document.querySelectorAll('.quick-amt').forEach(function(b){ b.classList.remove('active'); });
        updateSummary();
    });

    document.getElementById('airtimePhone').addEventListener('input', updateSummary);

    // ── Update summary ────────────────────────────────────────────────────────
    function updateSummary() {
        var phone = document.getElementById('airtimePhone').value.trim();
        var raw   = parseFloat(document.getElementById('airtimeAmount').value) || 0;
        var total = raw + flatFee;
        var after = airBalance - total;
        var net   = document.getElementById('selectedAirNetwork').value;

        if (raw >= 50 && phone.length >= 10) {
            document.getElementById('airtimeSummaryBox').style.display = 'block';
            document.getElementById('a_sum_net').textContent     = net;
            document.getElementById('a_sum_phone').textContent   = phone;
            document.getElementById('a_sum_value').textContent   = '₦' + raw.toLocaleString('en-NG', {minimumFractionDigits:2});
            document.getElementById('a_sum_amount').textContent  = '₦' + total.toLocaleString('en-NG', {minimumFractionDigits:2});
            document.getElementById('a_sum_after').textContent   = after >= 0
                ? '₦' + after.toLocaleString('en-NG', {minimumFractionDigits:2})
                : '⚠ Insufficient balance';
            document.getElementById('airtimeBuyBtn').disabled    = after < 0;
            document.getElementById('airtimeBtnText').textContent = 'Buy ₦' + raw.toLocaleString('en-NG') + ' Airtime';
        } else {
            document.getElementById('airtimeSummaryBox').style.display = 'none';
            document.getElementById('airtimeBuyBtn').disabled = true;
            document.getElementById('airtimeBtnText').textContent = 'Buy Airtime';
        }
    }

    // ── Buy button → modal ────────────────────────────────────────────────────
    document.getElementById('airtimeBuyBtn').addEventListener('click', function() {
        var phone = document.getElementById('airtimePhone').value.trim();
        var raw   = parseFloat(document.getElementById('airtimeAmount').value) || 0;
        var total = raw + flatFee;
        var net   = document.getElementById('selectedAirNetwork').value;

        var feeRow = flatFee > 0 ? '<div style="display:flex;justify-content:space-between"><span style="color:var(--text-muted)">Service Fee</span><strong>₦' + flatFee.toLocaleString('en-NG', {minimumFractionDigits:2}) + '</strong></div>' : '';

        document.getElementById('airtimeModalSummary').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>' + net + '</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)">Airtime Value</span><strong>₦' + raw.toLocaleString('en-NG', {minimumFractionDigits:2}) + '</strong></div>' +
            feeRow +
            '<div style="display:flex;justify-content:space-between"><span style="color:var(--text-muted)">Total Charged</span><strong style="color:#4D148C">₦' + total.toLocaleString('en-NG', {minimumFractionDigits:2}) + '</strong></div>' +
            '</div>';
        document.getElementById('airtimeModal').style.display = 'flex';
    });

    document.getElementById('airtimeCancelBtn').addEventListener('click', function() {
        document.getElementById('airtimeModal').style.display = 'none';
    });

    // ── Process purchase ──────────────────────────────────────────────────────
    document.getElementById('airtimeConfirmBtn').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_airtime',
            network: document.getElementById('selectedAirNetwork').value,
            phone:   document.getElementById('airtimePhone').value.trim(),
            amount:  document.getElementById('airtimeAmount').value,
        }, function(res) {
            document.getElementById('airtimeModal').style.display = 'none';
            if (res.status === '1') {
                showAlert(res.msg || 'Airtime sent 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() {
            document.getElementById('airtimeModal').style.display = 'none';
            showAlert('Network error. Please try again.', 'error');
            btn.disabled  = false;
            btn.innerHTML = '<i class="fas fa-check"></i> Confirm';
        });
    });

    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'); ?>