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

$user_balance = (float)$user['main_balance'];
$cable_fee    = (float)($site_data['cdh_cable_markup'] ?? 0);

// ── CDH Cable provider name → numeric ID (GOTV=1, DSTV=2, STARTIMES=3)
$cable_provider_ids = ['GOTV' => 1, 'DSTV' => 2, 'STARTIMES' => 3];

// ── Load plans from DB, grouped by provider
try {
    $stmt      = $pdo->query("SELECT * FROM vtu_cable_plans WHERE status = 1 ORDER BY provider ASC, sell_price ASC");
    $all_plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $all_plans = []; }

// Group by provider
$plans_by_provider = [];
foreach ($all_plans as $p) {
    $plans_by_provider[$p['provider']][] = $p;
}

// Ordered provider list (only those that have plans)
$provider_order  = ['DSTV', 'GOTV', 'STARTIMES'];
$providers_avail = [];
foreach ($provider_order as $pv) {
    if (isset($plans_by_provider[$pv])) $providers_avail[] = $pv;
}
// Any extra providers not in the order list
foreach (array_keys($plans_by_provider) as $pv) {
    if (!in_array($pv, $providers_avail)) $providers_avail[] = $pv;
}
$first_provider = $providers_avail[0] ?? 'DSTV';

// Pre-fill user phone
$user_phone = $user['phone'] ?? '';
if ($user_phone && $user_phone[0] === '+') {
    $user_phone = substr($user_phone, 1);
}
?>
<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; }

.cable-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;
}
.cable-hero::before {
    content:''; position:absolute; inset:0; pointer-events:none;
    background: repeating-linear-gradient(45deg,transparent,transparent 40px,rgba(77,20,140,.015) 40px,rgba(77,20,140,.015) 41px);
}

.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;
}

/* Provider tab buttons */
.prov-btn {
    padding: 10px 0; border-radius: 11px; 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;
}
.prov-btn.active {
    background: rgba(77,20,140,.1);
    border-color: rgba(77,20,140,.4);
    color: #4D148C;
}
.prov-btn:hover:not(.active) { border-color: rgba(77,20,140,.25); color: var(--text-primary); }

/* Plan cards grid */
.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,.4);
    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,.5); }

.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; }

.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,.35); }
.buy-btn:disabled { opacity:.6; cursor:not-allowed; transform:none; box-shadow:none; }
</style>

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

<!-- ── Hero ─────────────────────────────────────────────────────────────── -->
<div class="cable-hero anim anim-1">
    <div style="position:absolute;width:160px;height:160px;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-tv" style="color:#c4b5fd"></i> Cable TV
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">Pay your DSTV, GOTV or StarTimes subscription 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" style="font-size:.7rem"></i>Add Funds
            </a>
        </div>
    </div>
</div>

<!-- ── Provider buttons ──────────────────────────────────────────────────── -->
<div class="anim anim-1" style="display:flex;gap:8px;margin-bottom:14px">
    <?php foreach ($providers_avail as $pv): ?>
    <button class="prov-btn <?php echo $pv === $first_provider ? 'active' : ''; ?>"
            data-provider="<?php echo htmlspecialchars($pv); ?>">
        <?php echo htmlspecialchars($pv); ?>
    </button>
    <?php endforeach; ?>
</div>

<!-- ── Main Form Card ────────────────────────────────────────────────────── -->
<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-tv" style="font-size:.72rem;color:#4D148C"></i>
        </span>
        Select a Plan
    </h3>

    <!-- Plan grids — one per provider, JS shows/hides -->
    <?php foreach ($providers_avail as $pv): ?>
    <div id="grid_<?php echo $pv; ?>" class="plan-grid" style="display:<?php echo $pv === $first_provider ? 'grid' : 'none'; ?>">
        <?php if (!empty($plans_by_provider[$pv])): ?>
            <?php foreach ($plans_by_provider[$pv] as $pl): ?>
            <div class="plan-card"
                 data-id="<?php echo (int)$pl['id']; ?>"
                 data-provider="<?php echo htmlspecialchars($pv, ENT_QUOTES); ?>"
                 data-name="<?php echo htmlspecialchars($pl['plan_name'], ENT_QUOTES); ?>"
                 data-code="<?php echo htmlspecialchars($pl['plan_code'], ENT_QUOTES); ?>"
                 data-price="<?php echo (float)$pl['sell_price']; ?>">
                <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);line-height:1.3"><?php echo htmlspecialchars($pl['plan_name']); ?></p>
                <p style="font-weight:800;font-size:1rem;color:#4D148C;margin-top:6px;font-family:monospace">₦<?php echo number_format($pl['sell_price'], 2); ?></p>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p style="font-size:.78rem;color:var(--text-muted);grid-column:1/-1">No plans available for <?php echo htmlspecialchars($pv); ?>.</p>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>

    <!-- Fields shown after plan selected -->
    <div id="fieldsSection" style="display:none;margin-top:20px">

        <!-- SmartCard number -->
        <div style="margin-bottom:14px">
            <label class="form-label" for="cableCardNo">SmartCard / IUC Number</label>
            <input type="text" id="cableCardNo" class="form-input" placeholder="Enter your decoder SmartCard number" autocomplete="off">
        </div>

        <!-- Phone number -->
        <div style="margin-bottom:14px">
            <label class="form-label" for="cablePhone">Phone Number</label>
            <input type="tel" id="cablePhone" class="form-input" placeholder="e.g. 08012345678" maxlength="11"
                   value="<?php echo htmlspecialchars($user_phone); ?>">
        </div>

        <?php if ($cable_fee > 0): ?>
        <div style="margin-bottom:14px;padding:10px 14px;background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.15);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($cable_fee, 2); ?></strong> is added to the plan price.
        </div>
        <?php endif; ?>

        <!-- Order summary -->
        <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-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)">Provider</span><span id="s_provider" style="font-weight:700;color:var(--text-primary)">—</span></div>
            <div class="summary-row"><span style="color:var(--text-muted)">Plan</span><span id="s_plan" style="font-weight:700;color:var(--text-primary)">—</span></div>
            <div class="summary-row"><span style="color:var(--text-muted)">SmartCard</span><span id="s_card" style="font-weight:700;color:var(--text-primary)">—</span></div>
            <div class="summary-row"><span style="color:var(--text-muted)">Phone</span><span id="s_phone" style="font-weight:700;color:var(--text-primary)">—</span></div>
            <?php if ($cable_fee > 0): ?>
            <div class="summary-row"><span style="color:var(--text-muted)">Service Fee</span><span style="color:var(--text-muted)">₦<?php echo number_format($cable_fee, 2); ?></span></div>
            <?php endif; ?>
            <div class="summary-row"><span style="color:var(--text-muted)">Total</span><span id="s_total" 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="s_after" style="font-weight:700;font-family:monospace;color:var(--text-primary)">—</span></div>
        </div>

        <!-- Hidden state fields -->
        <input type="hidden" id="selPlanId"       value="">
        <input type="hidden" id="selProvider"     value="">
        <input type="hidden" id="selPlanName"     value="">
        <input type="hidden" id="selPlanCode"     value="">
        <input type="hidden" id="selPlanPrice"    value="">

        <button class="buy-btn" id="buyBtn" disabled>
            <i class="fas fa-tv"></i>
            <span id="buyBtnText">Pay Subscription</span>
        </button>

        <p style="text-align:center;font-size:.7rem;color:var(--text-muted);margin-top:10px">
            <i class="fas fa-shield-halved" style="font-size:.7rem"></i>
            Instant activation &middot; Deducted from wallet balance
        </p>
    </div><!-- /fieldsSection -->
</div><!-- /vtu-card -->

<!-- ── Quick links ────────────────────────────────────────────────────────── -->
<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.9;padding-left:14px;margin:0">
            <li>Select your provider (DSTV, GOTV or StarTimes) then pick a plan</li>
            <li>Enter the SmartCard / IUC number printed on your decoder</li>
            <li>Your phone number receives a confirmation SMS after payment</li>
            <li>Activation is usually instant — contact support if it takes over 5 minutes</li>
        </ul>
    </div>
</div>

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

<!-- ── Confirmation Modal ─────────────────────────────────────────────────── -->
<div id="confirmModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);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-tv" 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 Subscription</h3>
            <p style="font-size:.78rem;color:var(--text-muted)">Review and confirm your cable TV payment</p>
        </div>
        <div id="modalBody" 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="modalCancelBtn" 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="modalConfirmBtn" 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 &amp; Pay
            </button>
        </div>
    </div>
</div>

<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 cableFee     = <?php echo json_encode($cable_fee); ?>;
    var selectedPlan = null; // { id, provider, name, code, price }

    /* ── Helper: format currency ────────────────────────────────────────── */
    function fmt(n) {
        return '₦' + parseFloat(n).toLocaleString('en-NG', { minimumFractionDigits: 2 });
    }

    /* ── Helper: show toast alert ───────────────────────────────────────── */
    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 22px;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'
        ].join(';');
        el.textContent = msg;
        document.body.appendChild(el);
        setTimeout(function () { el.remove(); }, 4000);
    }

    /* ── Provider tab switching ─────────────────────────────────────────── */
    document.querySelectorAll('.prov-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var pv = this.dataset.provider;
            document.querySelectorAll('.prov-btn').forEach(function (b) { b.classList.remove('active'); });
            this.classList.add('active');
            document.querySelectorAll('[id^="grid_"]').forEach(function (g) { g.style.display = 'none'; });
            var grid = document.getElementById('grid_' + pv);
            if (grid) grid.style.display = 'grid';
            clearSelection();
        });
    });

    /* ── Plan card click ────────────────────────────────────────────────── */
    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,
                provider: this.dataset.provider,
                name:     this.dataset.name,
                code:     this.dataset.code,
                price:    parseFloat(this.dataset.price)
            };

            document.getElementById('selPlanId').value    = selectedPlan.id;
            document.getElementById('selProvider').value  = selectedPlan.provider;
            document.getElementById('selPlanName').value  = selectedPlan.name;
            document.getElementById('selPlanCode').value  = selectedPlan.code;
            document.getElementById('selPlanPrice').value = selectedPlan.price;

            document.getElementById('fieldsSection').style.display = 'block';
            updateSummary();
        });
    });

    /* ── Live updates when user types ───────────────────────────────────── */
    document.getElementById('cableCardNo').addEventListener('input', updateSummary);
    document.getElementById('cablePhone').addEventListener('input', updateSummary);

    /* ── Update order summary & buy button state ────────────────────────── */
    function updateSummary() {
        if (!selectedPlan) return;

        var card  = document.getElementById('cableCardNo').value.trim();
        var phone = document.getElementById('cablePhone').value.trim();
        var total = selectedPlan.price + cableFee;
        var after = userBalance - total;

        document.getElementById('s_provider').textContent = selectedPlan.provider;
        document.getElementById('s_plan').textContent     = selectedPlan.name;
        document.getElementById('s_card').textContent     = card  || '—';
        document.getElementById('s_phone').textContent    = phone || '—';
        document.getElementById('s_total').textContent    = fmt(total);
        document.getElementById('s_after').textContent    = after >= 0 ? fmt(after) : '⚠ Insufficient balance';

        document.getElementById('summaryBox').style.display = 'block';

        var ready = card.length >= 5 && phone.length >= 10 && after >= 0;
        var buyBtn = document.getElementById('buyBtn');
        buyBtn.disabled = !ready;
        document.getElementById('buyBtnText').textContent = ready
            ? 'Pay ' + selectedPlan.name + ' — ' + fmt(total)
            : 'Pay Subscription';
    }

    /* ── Clear selection ────────────────────────────────────────────────── */
    function clearSelection() {
        selectedPlan = null;
        document.querySelectorAll('.plan-card').forEach(function (c) { c.classList.remove('selected'); });
        document.getElementById('fieldsSection').style.display = 'none';
        document.getElementById('summaryBox').style.display    = 'none';
        document.getElementById('buyBtn').disabled             = true;
        document.getElementById('buyBtnText').textContent      = 'Pay Subscription';
    }

    /* ── Buy button → open confirmation modal ───────────────────────────── */
    document.getElementById('buyBtn').addEventListener('click', function () {
        var card  = document.getElementById('cableCardNo').value.trim();
        var phone = document.getElementById('cablePhone').value.trim();

        if (!selectedPlan)       { showAlert('Please select a plan first', 'error'); return; }
        if (card.length < 5)     { showAlert('Enter a valid SmartCard / IUC number', 'error'); return; }
        if (phone.length < 10)   { showAlert('Enter a valid phone number (min 10 digits)', 'error'); return; }
        if (userBalance < selectedPlan.price + cableFee) {
            showAlert('Insufficient wallet balance. Please fund your wallet.', 'error'); return;
        }

        var total = selectedPlan.price + cableFee;

        var rows = [
            ['Provider',  selectedPlan.provider],
            ['Plan',      selectedPlan.name],
            ['SmartCard', card],
            ['Phone',     phone],
            ['Plan Price', fmt(selectedPlan.price)]
        ];
        if (cableFee > 0) rows.push(['Service Fee', fmt(cableFee)]);
        rows.push(['Total Charged', '<strong style="color:#4D148C">' + fmt(total) + '</strong>']);

        var html = '<div style="display:flex;flex-direction:column;gap:8px">';
        rows.forEach(function (r) {
            html += '<div style="display:flex;justify-content:space-between;align-items:center">'
                  + '<span style="color:var(--text-muted)">' + r[0] + '</span>'
                  + '<span>' + r[1] + '</span></div>';
        });
        html += '</div>';

        document.getElementById('modalBody').innerHTML = html;
        document.getElementById('confirmModal').style.display = 'flex';
    });

    /* ── Cancel modal ───────────────────────────────────────────────────── */
    document.getElementById('modalCancelBtn').addEventListener('click', function () {
        document.getElementById('confirmModal').style.display = 'none';
    });

    /* ── Confirm & POST to AJAX handler ─────────────────────────────────── */
    document.getElementById('modalConfirmBtn').addEventListener('click', function () {
        var btn = this;
        btn.disabled  = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';

        var card  = document.getElementById('cableCardNo').value.trim();
        var phone = document.getElementById('cablePhone').value.trim();

        $.post('ajax/vtu-purchase.php', {
            action:    'buy_cable',
            provider:  document.getElementById('selProvider').value,
            plan_id:   document.getElementById('selPlanId').value,
            card_no:   card,
            phone:     phone
        }, function (res) {
            document.getElementById('confirmModal').style.display = 'none';
            if (res.status === '1') {
                showAlert(res.msg || 'Cable TV subscription activated!', 'success');
                setTimeout(function () { window.location.href = 'vtu-history'; }, 2200);
            } else {
                showAlert(res.msg || 'Payment failed. Please try again.', 'error');
                btn.disabled  = false;
                btn.innerHTML = '<i class="fas fa-check"></i> Confirm &amp; Pay';
            }
        }, 'json').fail(function () {
            document.getElementById('confirmModal').style.display = 'none';
            showAlert('Network error. Please try again.', 'error');
            btn.disabled  = false;
            btn.innerHTML = '<i class="fas fa-check"></i> Confirm &amp; Pay';
        });
    });

}());
</script>

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