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

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

// Fetch all cable plans
try {
    $cable_stmt = $pdo->query("SELECT * FROM vtu_cable_plans ORDER BY provider ASC, sell_price ASC");
    $cable_plans = $cable_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $cable_plans = []; }

// CheapDataHub settings
$cdh_key     = $site_data['cdh_api_key']  ?? '';
$cdh_url     = $site_data['cdh_api_url']  ?? 'https://www.cheapdatahub.ng/api/v1/resellers';
$cdh_enabled = $site_data['cdh_enabled']  ?? 0;
?>
<title><?php echo $page_title; ?></title>

<div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">VTU & Bills Management</h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">VTU Plans</li>
        </ol>
    </div>

    <!-- API Settings Card -->
    <div class="row mb-4">
        <div class="col-xl-6 col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header py-3 bg-primary text-white d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold">CheapDataHub API Settings</h6>
                    <span class="badge badge-<?php echo $cdh_enabled ? 'success' : 'danger'; ?>">
                        <?php echo $cdh_enabled ? 'Enabled' : 'Disabled'; ?>
                    </span>
                </div>
                <div class="card-body">
                    <form id="cdhSettingsForm">
                        <div class="form-group">
                            <label><strong>API Key</strong></label>
                            <input type="text" name="cdh_api_key" class="form-control" value="<?php echo htmlspecialchars($cdh_key); ?>" placeholder="Enter CheapDataHub API key">
                        </div>
                        <div class="form-group">
                            <label><strong>API URL</strong></label>
                            <input type="url" name="cdh_api_url" class="form-control" value="<?php echo htmlspecialchars($cdh_url); ?>">
                        </div>
                        <p class="text-muted small mb-2"><i class="fas fa-info-circle"></i> Service fees are <strong>flat NGN amounts</strong> added on top of the plan/airtime price (e.g. enter <code>50</code> to charge ₦50 extra). Set to <code>0</code> for no fee.</p>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label><strong>Airtime Service Fee (₦)</strong></label>
                                    <input type="number" name="cdh_airtime_markup" class="form-control" value="<?php echo $site_data['cdh_airtime_markup'] ?? 0; ?>" step="1" min="0" placeholder="e.g. 0">
                                    <small class="text-muted">Added to every airtime purchase</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label><strong>Cable TV Service Fee (₦)</strong></label>
                                    <input type="number" name="cdh_cable_markup" class="form-control" value="<?php echo $site_data['cdh_cable_markup'] ?? 0; ?>" step="1" min="0" placeholder="e.g. 100">
                                    <small class="text-muted">Added on top of cable plan price</small>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label><strong>Electricity Service Fee (₦)</strong></label>
                                    <input type="number" name="cdh_electricity_markup" class="form-control" value="<?php echo $site_data['cdh_electricity_markup'] ?? 0; ?>" step="1" min="0" placeholder="e.g. 100">
                                    <small class="text-muted">Added on top of electricity amount</small>
                                </div>
                            </div>
                        </div>
                        <div class="alert alert-info py-2 small mt-1">
                            <strong>Note:</strong> Data plan pricing is managed per-plan in the table below — set your sell price there directly.
                        </div>
                        <div class="form-group">
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="cdhEnabledSwitch" name="cdh_enabled" value="1" <?php echo $cdh_enabled ? 'checked' : ''; ?>>
                                <label class="custom-control-label" for="cdhEnabledSwitch">Enable CheapDataHub Service</label>
                            </div>
                        </div>
                        <button type="button" onclick="saveCdhSettings()" class="btn btn-primary btn-sm">
                            <i class="fas fa-save mr-1"></i>Save API Settings
                        </button>
                        <button type="button" onclick="testCdhApi()" class="btn btn-outline-secondary btn-sm ml-2">
                            <i class="fas fa-plug mr-1"></i>Test Connection
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-4" id="vtuTabs">
        <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#tabDataPlans">Data Plans</a></li>
        <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#tabCablePlans">Cable TV Plans</a></li>
        <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#tabTransactions">Recent Transactions</a></li>
    </ul>

    <div class="tab-content">

        <!-- ── DATA PLANS TAB ───────────────────────────── -->
        <div class="tab-pane fade show active" id="tabDataPlans">
            <div class="card shadow-sm mb-4">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">Data Plans</h6>
                    <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addPlanModal">
                        <i class="fas fa-plus mr-1"></i>Add Plan
                    </button>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="thead-light">
                                <tr>
                                    <th>Network</th>
                                    <th>Plan Name</th>
                                    <th>Size</th>
                                    <th>Validity</th>
                                    <th>Type</th>
                                    <th>Plan ID</th>
                                    <th>Cost Price</th>
                                    <th>Sell Price</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($plans)): ?>
                                <tr><td colspan="10" class="text-center text-muted py-4">No plans added yet.</td></tr>
                                <?php else: ?>
                                <?php foreach ($plans as $p): ?>
                                <tr>
                                    <td><span class="badge badge-secondary"><?php echo htmlspecialchars($p['network']); ?></span></td>
                                    <td><?php echo htmlspecialchars($p['plan_name']); ?></td>
                                    <td><strong><?php echo htmlspecialchars($p['data_size']); ?></strong></td>
                                    <td><?php echo htmlspecialchars($p['validity']); ?></td>
                                    <td><small class="text-muted"><?php echo htmlspecialchars($p['plan_type']); ?></small></td>
                                    <td><code style="font-size:.75rem"><?php echo htmlspecialchars($p['plan_id']); ?></code></td>
                                    <td>₦<?php echo number_format($p['cost_price'], 2); ?></td>
                                    <td><strong class="text-success">₦<?php echo number_format($p['sell_price'], 2); ?></strong></td>
                                    <td>
                                        <span class="badge badge-<?php echo $p['status'] ? 'success' : 'danger'; ?>">
                                            <?php echo $p['status'] ? 'Active' : 'Disabled'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary mr-1"
                                                onclick="editPlan(<?php echo htmlspecialchars(json_encode($p)); ?>)"
                                                data-toggle="modal" data-target="#editPlanModal">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger"
                                                onclick="deletePlan(<?php echo $p['id']; ?>, '<?php echo addslashes($p['plan_name']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- ── CABLE PLANS TAB ─────────────────────────── -->
        <div class="tab-pane fade" id="tabCablePlans">
            <div class="card shadow-sm mb-4">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">Cable TV Plans</h6>
                    <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addCableModal">
                        <i class="fas fa-plus mr-1"></i>Add Plan
                    </button>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="thead-light">
                                <tr><th>Provider</th><th>Plan Name</th><th>Plan Code</th><th>Price</th><th>Status</th><th>Actions</th></tr>
                            </thead>
                            <tbody>
                                <?php if (empty($cable_plans)): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No cable plans added yet.</td></tr>
                                <?php else: ?>
                                <?php foreach ($cable_plans as $cp): ?>
                                <tr>
                                    <td><span class="badge badge-info"><?php echo htmlspecialchars($cp['provider']); ?></span></td>
                                    <td><?php echo htmlspecialchars($cp['plan_name']); ?></td>
                                    <td><code><?php echo htmlspecialchars($cp['plan_code']); ?></code></td>
                                    <td><strong class="text-success">₦<?php echo number_format($cp['sell_price'], 2); ?></strong></td>
                                    <td><span class="badge badge-<?php echo $cp['status'] ? 'success' : 'danger'; ?>"><?php echo $cp['status'] ? 'Active' : 'Disabled'; ?></span></td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary mr-1" onclick="editCablePlan(<?php echo htmlspecialchars(json_encode($cp)); ?>)" data-toggle="modal" data-target="#editCableModal"><i class="fas fa-edit"></i></button>
                                        <button class="btn btn-sm btn-outline-danger" onclick="deleteCablePlan(<?php echo $cp['id']; ?>, '<?php echo addslashes($cp['plan_name']); ?>')"><i class="fas fa-trash"></i></button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

<!-- ── TRANSACTIONS TAB ────────────────────────── -->
<div class="tab-pane fade" id="tabTransactions">
    <div class="card shadow-sm mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
            <h6 class="m-0 font-weight-bold text-primary">Recent VTU Transactions</h6>
            <div class="d-flex align-items-center gap-2" style="gap:8px;">
                <select id="txnFilterStatus" class="form-control form-control-sm" style="width:auto;">
                    <option value="">All Status</option>
                    <option value="success">Success</option>
                    <option value="failed">Failed</option>
                    <option value="pending">Pending</option>
                </select>
                <select id="txnFilterType" class="form-control form-control-sm" style="width:auto;">
                    <option value="">All Types</option>
                    <option value="data">Data</option>
                    <option value="airtime">Airtime</option>
                    <option value="cable">Cable</option>
                    <option value="electricity">Electricity</option>
                </select>
                <button class="btn btn-sm btn-outline-secondary" onclick="loadTransactions(1)">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>#</th>
                            <th>Date</th>
                            <th>User</th>
                            <th>Type</th>
                            <th>Details</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody id="txnTableBody">
                        <tr>
                            <td colspan="7" class="text-center text-muted py-3">
                                Click the <strong>Recent Transactions</strong> tab to load data.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- Pagination -->
        <div class="card-footer d-flex justify-content-between align-items-center flex-wrap" style="gap:8px;" id="txnPaginationWrapper" style="display:none!important;">
            <small class="text-muted" id="txnPageInfo">—</small>
            <nav>
                <ul class="pagination pagination-sm mb-0" id="txnPagination"></ul>
            </nav>
        </div>
    </div>
</div>
    </div>
</div>

<!-- Add Data Plan Modal -->
<div class="modal fade" id="addPlanModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Add Data Plan</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
            <div class="modal-body">
                <form id="addPlanForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Network *</label>
                                <select name="network" class="form-control" required>
                                    <option value="MTN">MTN</option><option value="GLO">GLO</option>
                                    <option value="AIRTEL">AIRTEL</option><option value="9MOBILE">9MOBILE</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Plan Type *</label>
                                <select name="plan_type" class="form-control" required>
                                    <option value="DAILY">Daily</option>
                                    <option value="WEEKLY">Weekly</option>
                                    <option value="MONTHLY">Monthly</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group"><label>Plan Name *</label><input type="text" name="plan_name" class="form-control" placeholder="e.g. 1GB Daily" required></div>
                    <div class="row">
                        <div class="col-md-6"><div class="form-group"><label>Data Size *</label><input type="text" name="data_size" class="form-control" placeholder="e.g. 1GB" required></div></div>
                        <div class="col-md-6"><div class="form-group"><label>Validity *</label><input type="text" name="validity" class="form-control" placeholder="e.g. 1 Day" required></div></div>
                    </div>
                    <div class="form-group"><label>CheapDataHub Plan ID *</label><input type="text" name="plan_id" class="form-control" placeholder="Provider plan code/ID" required></div>
                    <div class="row">
                        <div class="col-md-6"><div class="form-group"><label>Cost Price (₦)</label><input type="number" name="cost_price" class="form-control" placeholder="0.00" step="0.01" min="0"></div></div>
                        <div class="col-md-6"><div class="form-group"><label>Sell Price (₦) *</label><input type="number" name="sell_price" class="form-control" placeholder="0.00" step="0.01" min="0" required></div></div>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="addPlanStatus" name="status" value="1" checked>
                            <label class="custom-control-label" for="addPlanStatus">Active (visible to users)</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitAddPlan()"><i class="fas fa-save mr-1"></i>Add Plan</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Data Plan Modal -->
<div class="modal fade" id="editPlanModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Edit Data Plan</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
            <div class="modal-body">
                <form id="editPlanForm">
                    <input type="hidden" name="id" id="edit_plan_id">
                    <div class="row">
                        <div class="col-md-6"><div class="form-group"><label>Network</label><select name="network" id="edit_plan_network" class="form-control"><option value="MTN">MTN</option><option value="GLO">GLO</option><option value="AIRTEL">AIRTEL</option><option value="9MOBILE">9MOBILE</option></select></div></div>
                        <div class="col-md-6"><div class="form-group"><label>Plan Type</label><select name="plan_type" id="edit_plan_type" class="form-control"><option value="DAILY">Daily</option><option value="WEEKLY">Weekly</option><option value="MONTHLY">Monthly</option></select></div></div>
                    </div>
                    <div class="form-group"><label>Plan Name</label><input type="text" name="plan_name" id="edit_plan_name" class="form-control"></div>
                    <div class="row">
                        <div class="col-md-6"><div class="form-group"><label>Data Size</label><input type="text" name="data_size" id="edit_plan_size" class="form-control"></div></div>
                        <div class="col-md-6"><div class="form-group"><label>Validity</label><input type="text" name="validity" id="edit_plan_validity" class="form-control"></div></div>
                    </div>
                    <div class="form-group"><label>CheapDataHub Plan ID</label><input type="text" name="plan_id" id="edit_plan_pid" class="form-control"></div>
                    <div class="row">
                        <div class="col-md-6"><div class="form-group"><label>Cost Price (₦)</label><input type="number" name="cost_price" id="edit_plan_cost" class="form-control" step="0.01" min="0"></div></div>
                        <div class="col-md-6"><div class="form-group"><label>Sell Price (₦)</label><input type="number" name="sell_price" id="edit_plan_sell" class="form-control" step="0.01" min="0"></div></div>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="edit_plan_status_sw" name="status" value="1">
                            <label class="custom-control-label" for="edit_plan_status_sw">Active</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitEditPlan()"><i class="fas fa-save mr-1"></i>Save Changes</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Cable Plan Modal -->
<div class="modal fade" id="addCableModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Add Cable TV Plan</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
            <div class="modal-body">
                <form id="addCableForm">
                    <div class="form-group"><label>Provider *</label><select name="provider" class="form-control" required><option value="DSTV">DSTV</option><option value="GOTV">GOTV</option><option value="STARTIMES">STARTIMES</option></select></div>
                    <div class="form-group"><label>Plan Name *</label><input type="text" name="plan_name" class="form-control" placeholder="e.g. DStv Premium" required></div>
                    <div class="form-group"><label>Plan Code *</label><input type="text" name="plan_code" class="form-control" placeholder="Bouquet code from CheapDataHub" required></div>
                    <div class="form-group"><label>Sell Price (₦) *</label><input type="number" name="sell_price" class="form-control" step="0.01" min="0" required></div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="addCableStatus" name="status" value="1" checked>
                            <label class="custom-control-label" for="addCableStatus">Active</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitAddCable()">Add Plan</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Cable Plan Modal -->
<div class="modal fade" id="editCableModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Edit Cable TV Plan</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
            <div class="modal-body">
                <form id="editCableForm">
                    <input type="hidden" name="id" id="ec_id">
                    <div class="form-group"><label>Provider</label><select name="provider" id="ec_provider" class="form-control"><option value="DSTV">DSTV</option><option value="GOTV">GOTV</option><option value="STARTIMES">STARTIMES</option></select></div>
                    <div class="form-group"><label>Plan Name</label><input type="text" name="plan_name" id="ec_name" class="form-control"></div>
                    <div class="form-group"><label>Plan Code</label><input type="text" name="plan_code" id="ec_code" class="form-control"></div>
                    <div class="form-group"><label>Sell Price (₦)</label><input type="number" name="sell_price" id="ec_price" class="form-control" step="0.01" min="0"></div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="ec_status_sw" name="status" value="1">
                            <label class="custom-control-label" for="ec_status_sw">Active</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitEditCable()">Save Changes</button>
            </div>
        </div>
    </div>
</div>

<script>
// ── Toast helper ─────────────────────────────────────────────────────────────
function showToast(msg, type = 'success') {
    const el = document.createElement('div');
    el.style.cssText = `position:fixed;top:20px;right:20px;z-index:9999;padding:12px 20px;border-radius:8px;font-weight:600;color:white;background:${type === 'success' ? '#28a745' : '#dc3545'};box-shadow:0 4px 16px rgba(0,0,0,.2)`;
    el.textContent = msg;
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 3500);
}

// ── API Settings ──────────────────────────────────────────────────────────────
function saveCdhSettings() {
    const formData = new FormData(document.getElementById('cdhSettingsForm'));
    formData.append('action', 'save_cdh_settings');
    if (!document.getElementById('cdhEnabledSwitch').checked) formData.set('cdh_enabled', '0');
    fetch('ajax/vtu-admin.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(res => showToast(res.msg, res.status === '1' ? 'success' : 'error'));
}

function testCdhApi() {
    fetch('ajax/vtu-admin.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=test_cdh',
    }).then(r => r.json()).then(res => showToast(res.msg, res.status === '1' ? 'success' : 'error'));
}

// ── Data Plans ────────────────────────────────────────────────────────────────
function submitAddPlan() {
    const formData = new FormData(document.getElementById('addPlanForm'));
    formData.append('action', 'add_data_plan');
    if (!document.getElementById('addPlanStatus').checked) formData.set('status', '0');
    fetch('ajax/vtu-admin.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(res => {
            showToast(res.msg, res.status === '1' ? 'success' : 'error');
            if (res.status === '1') { $('#addPlanModal').modal('hide'); setTimeout(() => location.reload(), 800); }
        });
}

function editPlan(plan) {
    document.getElementById('edit_plan_id').value       = plan.id;
    document.getElementById('edit_plan_network').value  = plan.network;
    document.getElementById('edit_plan_type').value     = plan.plan_type;
    document.getElementById('edit_plan_name').value     = plan.plan_name;
    document.getElementById('edit_plan_size').value     = plan.data_size;
    document.getElementById('edit_plan_validity').value = plan.validity;
    document.getElementById('edit_plan_pid').value      = plan.plan_id;
    document.getElementById('edit_plan_cost').value     = plan.cost_price;
    document.getElementById('edit_plan_sell').value     = plan.sell_price;
    document.getElementById('edit_plan_status_sw').checked = plan.status == 1;
}

function submitEditPlan() {
    const formData = new FormData(document.getElementById('editPlanForm'));
    formData.append('action', 'edit_data_plan');
    if (!document.getElementById('edit_plan_status_sw').checked) formData.set('status', '0');
    fetch('ajax/vtu-admin.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(res => {
            showToast(res.msg, res.status === '1' ? 'success' : 'error');
            if (res.status === '1') { $('#editPlanModal').modal('hide'); setTimeout(() => location.reload(), 800); }
        });
}

function deletePlan(id, name) {
    if (!confirm(`Delete plan "${name}"? This cannot be undone.`)) return;
    fetch('ajax/vtu-admin.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=delete_data_plan&id=${id}`,
    }).then(r => r.json()).then(res => {
        showToast(res.msg, res.status === '1' ? 'success' : 'error');
        if (res.status === '1') setTimeout(() => location.reload(), 800);
    });
}

// ── Cable Plans ───────────────────────────────────────────────────────────────
function submitAddCable() {
    const formData = new FormData(document.getElementById('addCableForm'));
    formData.append('action', 'add_cable_plan');
    if (!document.getElementById('addCableStatus').checked) formData.set('status', '0');
    fetch('ajax/vtu-admin.php', { method: 'POST', body: formData })
        .then(r => r.json()).then(res => {
            showToast(res.msg, res.status === '1' ? 'success' : 'error');
            if (res.status === '1') { $('#addCableModal').modal('hide'); setTimeout(() => location.reload(), 800); }
        });
}

function editCablePlan(p) {
    document.getElementById('ec_id').value       = p.id;
    document.getElementById('ec_provider').value = p.provider;
    document.getElementById('ec_name').value     = p.plan_name;
    document.getElementById('ec_code').value     = p.plan_code;
    document.getElementById('ec_price').value    = p.sell_price;
    document.getElementById('ec_status_sw').checked = p.status == 1;
}

function submitEditCable() {
    const formData = new FormData(document.getElementById('editCableForm'));
    formData.append('action', 'edit_cable_plan');
    if (!document.getElementById('ec_status_sw').checked) formData.set('status', '0');
    fetch('ajax/vtu-admin.php', { method: 'POST', body: formData })
        .then(r => r.json()).then(res => {
            showToast(res.msg, res.status === '1' ? 'success' : 'error');
            if (res.status === '1') { $('#editCableModal').modal('hide'); setTimeout(() => location.reload(), 800); }
        });
}

function deleteCablePlan(id, name) {
    if (!confirm(`Delete cable plan "${name}"?`)) return;
    fetch('ajax/vtu-admin.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=delete_cable_plan&id=${id}`,
    }).then(r => r.json()).then(res => {
        showToast(res.msg, res.status === '1' ? 'success' : 'error');
        if (res.status === '1') setTimeout(() => location.reload(), 800);
    });
}

// ── Transactions with Pagination ──────────────────────────────────────────────
let txnCurrentPage  = 1;
let txnTotalPages   = 1;
const TXN_PER_PAGE  = 20;

function loadTransactions(page) {
    page = page || 1;
    txnCurrentPage = page;

    const status  = document.getElementById('txnFilterStatus').value;
    const svcType = document.getElementById('txnFilterType').value;

    // Show loading state
    document.getElementById('txnTableBody').innerHTML =
        '<tr><td colspan="7" class="text-center text-muted py-3"><i class="fas fa-spinner fa-spin mr-1"></i>Loading...</td></tr>';
    document.getElementById('txnPaginationWrapper').style.display = 'none';

    const params = new URLSearchParams({
        action   : 'get_transactions',
        page     : page,
        per_page : TXN_PER_PAGE,
        status   : status,
        svc_type : svcType,
    });

    fetch('ajax/vtu-admin.php', {
        method  : 'POST',
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
        body    : params.toString(),
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== '1') {
            document.getElementById('txnTableBody').innerHTML =
                `<tr><td colspan="7" class="text-center text-danger py-3"><i class="fas fa-exclamation-triangle mr-1"></i>${res.msg || 'Failed to load transactions.'}</td></tr>`;
            return;
        }

        const rows = res.data;
        txnTotalPages = res.total_pages || 1;
        const total   = res.total || rows.length;
        const from    = (page - 1) * TXN_PER_PAGE + 1;
        const to      = Math.min(from + rows.length - 1, total);

        if (rows.length === 0) {
            document.getElementById('txnTableBody').innerHTML =
                '<tr><td colspan="7" class="text-center text-muted py-3">No transactions found.</td></tr>';
            document.getElementById('txnPaginationWrapper').style.display = 'none';
            return;
        }

        // Build table rows
        let html = '';
        rows.forEach(t => {
            const sColor = t.status === 'success' ? 'success' : t.status === 'pending' ? 'warning' : 'danger';
            const typeColor = { data: 'primary', airtime: 'info', cable: 'secondary', electricity: 'warning' }[t.service_type] || 'secondary';
            const amount = parseFloat(t.amount).toLocaleString('en-NG', { minimumFractionDigits: 2 });
            html += `<tr>
                <td><small class="text-muted">${t.id}</small></td>
                <td><small>${t.created_at}</small></td>
                <td><span class="font-weight-bold">${t.username || ('User #' + t.user_id)}</span></td>
                <td><span class="badge badge-${typeColor} text-uppercase">${t.service_type}</span></td>
                <td>
                    <span class="d-block font-weight-bold" style="font-size:.82rem;">${t.plan_name || '—'}</span>
                    <small class="text-muted">${t.network || ''} ${t.phone ? '· ' + t.phone : ''}</small>
                </td>
                <td class="font-weight-bold text-danger">₦${amount}</td>
                <td><span class="badge badge-${sColor} text-capitalize">${t.status}</span></td>
            </tr>`;
        });
        document.getElementById('txnTableBody').innerHTML = html;

        // Update info text
        document.getElementById('txnPageInfo').textContent =
            `Showing ${from}–${to} of ${total} transactions`;

        // Build pagination
        renderTxnPagination(page, txnTotalPages);
        document.getElementById('txnPaginationWrapper').style.display = 'flex';
    })
    .catch(err => {
        document.getElementById('txnTableBody').innerHTML =
            `<tr><td colspan="7" class="text-center text-danger py-3"><i class="fas fa-exclamation-triangle mr-1"></i>Network error. Please try again.</td></tr>`;
        console.error('Transaction fetch error:', err);
    });
}

function renderTxnPagination(current, total) {
    const ul = document.getElementById('txnPagination');
    if (total <= 1) { ul.innerHTML = ''; return; }

    let html = '';

    // Prev
    html += `<li class="page-item ${current === 1 ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="loadTransactions(${current - 1});return false;">«</a>
    </li>`;

    // Page numbers: show max 5 around current
    const start = Math.max(1, current - 2);
    const end   = Math.min(total, current + 2);

    if (start > 1) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadTransactions(1);return false;">1</a></li>`;
        if (start > 2) html += `<li class="page-item disabled"><span class="page-link">…</span></li>`;
    }

    for (let i = start; i <= end; i++) {
        html += `<li class="page-item ${i === current ? 'active' : ''}">
            <a class="page-link" href="#" onclick="loadTransactions(${i});return false;">${i}</a>
        </li>`;
    }

    if (end < total) {
        if (end < total - 1) html += `<li class="page-item disabled"><span class="page-link">…</span></li>`;
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadTransactions(${total});return false;">${total}</a></li>`;
    }

    // Next
    html += `<li class="page-item ${current === total ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="loadTransactions(${current + 1});return false;">»</a>
    </li>`;

    ul.innerHTML = html;
}

// Fire on tab click — using both Bootstrap 4 event and direct click fallback
$(document).on('shown.bs.tab', 'a[href="#tabTransactions"]', function () {
    if (txnCurrentPage === 1 && document.getElementById('txnTableBody').querySelector('.fa-spinner') === null) {
        loadTransactions(1);
    }
});

// Direct click fallback in case shown.bs.tab doesn't fire
$(document).on('click', 'a[href="#tabTransactions"]', function () {
    setTimeout(() => loadTransactions(1), 150);
});

// Filter changes reload from page 1
document.getElementById('txnFilterStatus').addEventListener('change', () => loadTransactions(1));
document.getElementById('txnFilterType').addEventListener('change', () => loadTransactions(1));
</script>

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