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

$user_balance = (float)$user['main_balance'];
$elec_fee     = (float)($site_data['cdh_electricity_markup'] ?? 0);

// Pre-fill user phone
$user_phone = $user['phone'] ?? '';
if ($user_phone && $user_phone[0] === '+') {
    $user_phone = substr($user_phone, 1);
}

$discos = [
    'AEDC'  => 'Abuja Electric (AEDC)',
    'EKEDC' => 'Eko Electric (EKEDC)',
    'IBEDC' => 'Ibadan Electric (IBEDC)',
    'IKEDC' => 'Ikeja Electric (IKEDC)',
    'KEDC'  => 'Kaduna Electric',
    'PHEDC' => 'Port Harcourt Electric',
    'JEDC'  => 'Jos Electric (JEDC)',
    'EEDC'  => 'Enugu Electric (EEDC)',
    'YEDC'  => 'Yola Electric',
    'BEDC'  => 'Benin Electric (BEDC)',
];

$quick_amounts = [1000, 2000, 5000, 10000, 20000];
?>
<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; }

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

.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,.55); }
.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;
}

.meter-type-btn {
    padding:10px 0; border-radius:11px; font-size:.8rem; 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;
}
.meter-type-btn.active {
    background: rgba(77,20,140,.1);
    border-color: rgba(77,20,140,.45);
    color: #4D148C;
}

.quick-btn {
    padding:9px 12px; 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-btn:hover { border-color:rgba(77,20,140,.35); color:var(--text-primary); }
.quick-btn.active {
    background: rgba(77,20,140,.08);
    border-color: rgba(77,20,140,.45);
    color: #4D148C;
}

.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="elec-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-bolt" style="color:#c4b5fd"></i> Electricity
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">Buy prepaid or postpaid electricity units across all Nigerian DISCOs.</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>

<!-- ── 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,.12);display:inline-flex;align-items:center;justify-content:center">
            <i class="fas fa-bolt" style="font-size:.72rem;color:#4D148C"></i>
        </span>
        Electricity Purchase
    </h3>

    <!-- DISCO selection -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="discoPicker">Select DISCO (Electricity Provider)</label>
        <select id="discoPicker" class="form-input form-select">
            <option value=""> Choose your DISCO </option>
            <?php foreach ($discos as $code => $label): ?>
            <option value="<?php echo htmlspecialchars($code); ?>"><?php echo htmlspecialchars($label); ?></option>
            <?php endforeach; ?>
        </select>
    </div>

    <!-- Meter type -->
    <div style="margin-bottom:14px">
        <label class="form-label">Meter Type</label>
        <div style="display:flex;gap:8px">
            <button class="meter-type-btn active" data-mtype="prepaid">Prepaid</button>
            <button class="meter-type-btn"        data-mtype="postpaid">Postpaid</button>
        </div>
        <input type="hidden" id="meterType" value="prepaid">
    </div>

    <!-- Meter number -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="meterNumber">Meter Number</label>
        <input type="text" id="meterNumber" class="form-input" placeholder="Enter your meter number" autocomplete="off">
        <p style="font-size:.68rem;color:var(--text-muted);margin-top:4px">
            <i class="fas fa-circle-info" style="font-size:.65rem"></i>
            Double-check your meter number before paying — wrong meter cannot be reversed.
        </p>
    </div>

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

    <!-- Amount -->
    <div style="margin-bottom:14px">
        <label class="form-label">Amount (₦) — Minimum ₦1,000</label>
        <div style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:10px">
            <?php foreach ($quick_amounts as $qa): ?>
            <button class="quick-btn" data-amount="<?php echo $qa; ?>">₦<?php echo number_format($qa); ?></button>
            <?php endforeach; ?>
        </div>
        <input type="number" id="elecAmount" class="form-input" placeholder="Or enter a custom amount (min ₦1,000)" min="1000" step="100">
    </div>

    <?php if ($elec_fee > 0): ?>
    <div style="margin-bottom:14px;padding:10px 14px;background:rgba(77,20,140,.05);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($elec_fee, 2); ?></strong> is added to your electricity amount.
    </div>
    <?php endif; ?>

    <!-- Order summary -->
    <div id="summaryBox" style="display:none;background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.2);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)">DISCO</span><span id="s_disco" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Meter Type</span><span id="s_type" style="color:var(--text-muted)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Meter Number</span><span id="s_meter" 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>
        <div class="summary-row"><span style="color:var(--text-muted)">Units Amount</span><span id="s_raw" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <?php if ($elec_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($elec_fee, 2); ?></span></div>
        <?php endif; ?>
        <div class="summary-row"><span style="color:var(--text-muted)">Total Charged</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>

    <button class="buy-btn" id="buyBtn" disabled>
        <i class="fas fa-bolt"></i>
        <span id="buyBtnText">Buy Electricity Units</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>
        Token delivered via SMS &middot; Deducted from wallet balance
    </p>
</div>

<!-- ── Tips ───────────────────────────────────────────────────────────────── -->
<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><strong>Prepaid</strong> — generates a recharge token (credit) for your meter</li>
            <li><strong>Postpaid</strong> — pays your outstanding electricity bill</li>
            <li>Token is delivered instantly via SMS to your phone number</li>
            <li>Minimum purchase is ₦1,000 — enter the exact amount you want in units</li>
            <li>Always verify your meter number carefully before paying</li>
        </ul>
    </div>
</div>

</div>

<!-- ── 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-bolt" 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 Payment</h3>
            <p style="font-size:.78rem;color:var(--text-muted)">Review and confirm your electricity purchase</p>
        </div>
        <div id="modalBody" style="background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.2);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';

    var userBalance = <?php echo json_encode($user_balance); ?>;
    var elecFee     = <?php echo json_encode($elec_fee); ?>;
    var MIN_AMOUNT  = 1000;

    function fmt(n) {
        return '₦' + parseFloat(n).toLocaleString('en-NG', { minimumFractionDigits: 2 });
    }

    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(); }, 4500);
    }

    document.querySelectorAll('.meter-type-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.querySelectorAll('.meter-type-btn').forEach(function (b) { b.classList.remove('active'); });
            this.classList.add('active');
            document.getElementById('meterType').value = this.dataset.mtype;
            updateSummary();
        });
    });

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

    document.getElementById('discoPicker').addEventListener('change', updateSummary);
    document.getElementById('meterNumber').addEventListener('input', updateSummary);
    document.getElementById('elecPhone').addEventListener('input', updateSummary);
    document.getElementById('elecAmount').addEventListener('input', function () {
        document.querySelectorAll('.quick-btn').forEach(function (b) { b.classList.remove('active'); });
        updateSummary();
    });

    function updateSummary() {
        var disco = document.getElementById('discoPicker').value;
        var type  = document.getElementById('meterType').value;
        var meter = document.getElementById('meterNumber').value.trim();
        var phone = document.getElementById('elecPhone').value.trim();
        var raw   = parseFloat(document.getElementById('elecAmount').value) || 0;
        var total = raw + elecFee;
        var after = userBalance - total;

        var allFilled = disco && meter && phone.length >= 10 && raw >= MIN_AMOUNT;

        if (allFilled) {
            document.getElementById('summaryBox').style.display = 'block';
            document.getElementById('s_disco').textContent = disco;
            document.getElementById('s_type').textContent  = type.charAt(0).toUpperCase() + type.slice(1);
            document.getElementById('s_meter').textContent = meter;
            document.getElementById('s_phone').textContent = phone;
            document.getElementById('s_raw').textContent   = fmt(raw);
            document.getElementById('s_total').textContent = fmt(total);
            document.getElementById('s_after').textContent = after >= 0 ? fmt(after) : '⚠ Insufficient balance';
            document.getElementById('buyBtn').disabled     = after < 0;
            document.getElementById('buyBtnText').textContent = 'Buy ' + fmt(total) + ' Electricity Units';
        } else {
            document.getElementById('summaryBox').style.display = 'none';
            document.getElementById('buyBtn').disabled = true;
            document.getElementById('buyBtnText').textContent = 'Buy Electricity Units';
        }
    }

    document.getElementById('buyBtn').addEventListener('click', function () {
        var disco = document.getElementById('discoPicker').value;
        var type  = document.getElementById('meterType').value;
        var meter = document.getElementById('meterNumber').value.trim();
        var phone = document.getElementById('elecPhone').value.trim();
        var raw   = parseFloat(document.getElementById('elecAmount').value) || 0;
        var total = raw + elecFee;

        if (!disco)           { showAlert('Please select your DISCO', 'error'); return; }
        if (!meter)           { showAlert('Enter your meter number', 'error'); return; }
        if (phone.length < 10){ showAlert('Enter a valid phone number (min 10 digits)', 'error'); return; }
        if (raw < MIN_AMOUNT) { showAlert('Minimum electricity purchase is ₦' + MIN_AMOUNT.toLocaleString(), 'error'); return; }
        if (userBalance < total) { showAlert('Insufficient wallet balance. Please fund your wallet.', 'error'); return; }

        var rows = [
            ['DISCO',        disco],
            ['Meter Type',   type.charAt(0).toUpperCase() + type.slice(1)],
            ['Meter Number', meter],
            ['Phone',        phone],
            ['Units Amount', fmt(raw)]
        ];
        if (elecFee > 0) rows.push(['Service Fee', fmt(elecFee)]);
        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';
    });

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

    document.getElementById('modalConfirmBtn').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_electricity',
            disco:       document.getElementById('discoPicker').value,
            meter_no:    document.getElementById('meterNumber').value.trim(),
            meter_type:  document.getElementById('meterType').value,
            phone:       document.getElementById('elecPhone').value.trim(),
            amount:      parseFloat(document.getElementById('elecAmount').value) || 0
        }, function (res) {
            document.getElementById('confirmModal').style.display = 'none';
            if (res.status === '1') {
                showAlert(res.msg || 'Electricity purchased! Check SMS for token.', 'success');
                if (res.token) {
                    var tokenDiv = document.createElement('div');
                    tokenDiv.style.cssText = [
                        'position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:99999',
                        'padding:16px 24px;border-radius:14px;font-weight:700;color:white',
                        'background:#1a1a1a;box-shadow:0 6px 24px rgba(0,0,0,.35)',
                        'max-width:90vw;text-align:center'
                    ].join(';');
                    tokenDiv.innerHTML = '<p style="font-size:.75rem;color:#c4b5fd;margin-bottom:6px">⚡ Electricity Token</p>'
                                       + '<p style="font-size:1.4rem;letter-spacing:.08em;font-family:monospace">' + res.token + '</p>'
                                       + '<p style="font-size:.7rem;color:#9ca3af;margin-top:6px">Copy this token before it disappears</p>';
                    document.body.appendChild(tokenDiv);
                    setTimeout(function () { tokenDiv.remove(); }, 15000);
                }
                setTimeout(function () { window.location.href = 'vtu-history'; }, 3000);
            } 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'); ?>