<?php
// FILE: public_html/admin/admin_data_plans.php
session_start();
require_once '../db.php'; 

// 1. ADMIN SESSION CHECK
if (!isset($_SESSION['admin_id'])) { 
    // header("Location: index.php"); exit(); 
}

$message = "";

// =========================================================
// 1. HANDLE FORM SUBMISSIONS (Add / Edit / Delete)
// =========================================================

// --- DELETE PLAN ---
if (isset($_GET['delete_id'])) {
    $id = intval($_GET['delete_id']);
    $conn->query("DELETE FROM data_plans WHERE id = $id");
    $message = "Plan deleted successfully!";
}

// --- ADD OR UPDATE PLAN ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $plan_id = $_POST['plan_id'];
    $provider_plan_id = $_POST['provider_plan_id'];
    $network = $_POST['network'];
    $category = $_POST['category'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
    $validity = $_POST['validity'];
    
    if (!empty($_POST['edit_id'])) {
        // UPDATE
        $id = intval($_POST['edit_id']);
        $stmt = $conn->prepare("UPDATE data_plans SET plan_id=?, provider_plan_id=?, network=?, category=?, quantity=?, price=?, validity=? WHERE id=?");
        $stmt->bind_param("iisssssi", $plan_id, $provider_plan_id, $network, $category, $quantity, $price, $validity, $id);
        $stmt->execute();
        $message = "Plan updated successfully!";
    } else {
        // INSERT
        $stmt = $conn->prepare("INSERT INTO data_plans (plan_id, provider_plan_id, network, category, quantity, price, validity, switch) VALUES (?, ?, ?, ?, ?, ?, ?, 1)");
        $stmt->bind_param("iisssss", $plan_id, $provider_plan_id, $network, $category, $quantity, $price, $validity);
        $stmt->execute();
        $message = "New plan added successfully!";
    }
}

// 2. FETCH PLANS
$plans = $conn->query("SELECT * FROM data_plans ORDER BY network ASC, price ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Data Plans - Nagarta Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        /* --- PREMIUM THEME (MATCHING TRANSACTIONS.PHP) --- */
        :root { 
            --primary: #2c5364; --secondary: #203a43; --accent: #00d2ff; --bg: #f4f7f6; 
            --text: #334155; --white: #ffffff; --sidebar-width: 260px;
        }
        * { margin:0; padding:0; box-sizing:border-box; font-family:'Poppins', sans-serif; -webkit-tap-highlight-color: transparent; }
        body { background:var(--bg); color:var(--text); display:flex; min-height:100vh; overflow-x: hidden; }
        
        /* SIDEBAR */
        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, var(--secondary) 0%, var(--primary) 100%); color:white; display:flex; flex-direction:column; position: fixed; height: 100%; z-index: 1000; transition: 0.3s; left: 0; box-shadow: 5px 0 15px rgba(0,0,0,0.1); }
        .brand { padding:25px; border-bottom:1px solid rgba(255,255,255,0.05); text-align:center; }
        .brand img { max-height: 45px; }
        .nav { flex:1; padding:20px; overflow-y:auto; }
        .nav a { display:flex; align-items:center; color:rgba(255,255,255,0.7); padding:12px 15px; text-decoration:none; margin-bottom:5px; border-radius:12px; font-weight: 500; transition:0.2s; font-size: 1rem; }
        .nav a:hover, .nav a.active { background:var(--white); color:var(--primary); font-weight: 600; }
        .nav i { width:30px; text-align:center; }

        /* MAIN CONTENT */
        .main { flex:1; margin-left: var(--sidebar-width); padding: 25px; width: calc(100% - var(--sidebar-width)); transition: 0.3s; }
        .header { display:flex; justify-content:space-between; align-items:center; margin-bottom:25px; background: var(--white); padding: 15px 20px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); position: sticky; top: 0; z-index: 90; }
        .menu-toggle { display:none; font-size:1.4rem; cursor:pointer; color: var(--primary); }

        /* TABLE CONTAINER */
        .table-container { background:var(--white); border-radius:16px; padding:20px; margin-bottom:30px; box-shadow:0 10px 30px rgba(0,0,0,0.04); overflow-x: auto; }
        table { width:100%; border-collapse:collapse; min-width: 800px; }
        th, td { padding:15px; text-align:left; border-bottom:1px solid #f1f5f9; font-size:0.85rem; }
        th { background:#f8fafc; color:#64748b; font-weight:600; text-transform:uppercase; font-size:0.8rem; }
        
        /* CUSTOM BADGES & TEXT */
        .network-MTN { color: #FFCC00; font-weight: 700; }
        .network-AIRTEL { color: #FF0000; font-weight: 700; }
        .network-GLO { color: #00C300; font-weight: 700; }
        .network-9MOBILE { color: #006400; font-weight: 700; }
        
        .badge { padding:5px 12px; border-radius:20px; font-size:0.75rem; font-weight:600; }
        .badge-id { background:#e2e8f0; color:#475569; font-family: monospace; }
        .badge-vendor { background:#e0f2fe; color:#0369a1; font-family: monospace; }

        /* BUTTONS */
        .btn-add { background:var(--primary); color:white; border:none; padding:10px 20px; border-radius:10px; cursor:pointer; font-weight: 600; display: flex; align-items: center; gap: 8px; text-decoration: none; }
        .btn-add:hover { background: var(--secondary); color: white; }
        
        /* BOOTSTRAP OVERRIDES (For Modal) */
        .modal-header { background: var(--bg); border-bottom: 1px solid #e2e8f0; }
        .form-label { font-size: 0.85rem; font-weight: 600; color: var(--text); }
        .form-control, .form-select { border-radius: 10px; padding: 10px; font-size: 0.9rem; border: 1px solid #e2e8f0; }
        .form-control:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(44, 83, 100, 0.1); }

        @media(max-width: 991px) { .sidebar { left: -280px; } .sidebar.active { left: 0; } .main { margin-left: 0; width: 100%; } .menu-toggle { display: block; } }
    </style>
</head>
<body>

<div class="sidebar">
    <div class="brand"><img src="../assets/images/logo.png" alt="Logo"></div>
    <div class="nav">
        <a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a>
        <a href="users.php"><i class="fas fa-users"></i> Users</a>
        <a href="transactions.php"><i class="fas fa-chart-line"></i> Transactions</a>
        <a href="credit_user.php"><i class="fas fa-wallet"></i> Credit User</a>
        <a href="admin_data_plans.php" class="active"><i class="fas fa-wifi"></i> Data Plans</a>
        <a href="notifications.php"><i class="fas fa-bell"></i> Notifications</a>
        <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
        <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
</div>

<div class="main">
    <div class="header">
        <div class="menu-toggle" onclick="document.querySelector('.sidebar').classList.toggle('active')"><i class="fas fa-bars"></i></div>
        <div>
            <h3 style="margin:0; font-weight:600; color:var(--primary);">Manage Data Plans</h3>
            <small style="color:#64748b;">Configure Prices & IDs</small>
        </div>
        <button class="btn-add" onclick="openModal()">
            <i class="fas fa-plus-circle"></i> Add Plan
        </button>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" style="margin-bottom: 20px; border-radius: 12px;" role="alert">
            <i class="fas fa-check-circle me-2"></i> <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Network</th>
                    <th>Category</th>
                    <th>Size</th>
                    <th>Price</th>
                    <th>Validity</th>
                    <th>App ID</th>
                    <th>Vendor ID</th>
                    <th style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $plans->fetch_assoc()): ?>
                <tr>
                    <td class="network-<?= $row['network'] ?>"><?= $row['network'] ?></td>
                    <td><?= $row['category'] ?></td>
                    <td style="font-weight: 600;"><?= $row['quantity'] ?></td>
                    <td style="font-weight: 700; color: var(--text);">₦<?= number_format($row['price'], 2) ?></td>
                    <td><?= $row['validity'] ?></td>
                    <td><span class="badge badge-id"><?= $row['plan_id'] ?></span></td>
                    <td><span class="badge badge-vendor"><?= $row['provider_plan_id'] ?></span></td>
                    <td style="text-align:right;">
                        <button class="btn btn-sm btn-warning me-1" style="color:white;" onclick='editPlan(<?= json_encode($row) ?>)'>
                            <i class="fas fa-edit"></i>
                        </button>
                        <a href="?delete_id=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this plan?')">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="planModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius: 16px; border: none;">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold" id="modalTitle" style="color:var(--primary);">Add Data Plan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <input type="hidden" name="edit_id" id="edit_id">
                    
                    <div class="row g-3">
                        <div class="col-6">
                            <label class="form-label">Network</label>
                            <select name="network" id="network" class="form-select" required>
                                <option value="MTN">MTN</option>
                                <option value="AIRTEL">AIRTEL</option>
                                <option value="GLO">GLO</option>
                                <option value="9MOBILE">9MOBILE</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Category</label>
                            <select name="category" id="category" class="form-select" required>
                                <option value="SME">SME</option>
                                <option value="GIFTING">GIFTING</option>
                                <option value="CG">CG (Corporate)</option>
                                <option value="AWOOF">AWOOF / PROMO</option>
                            </select>
                        </div>
                    </div>

                    <div class="row g-3 mt-1">
                        <div class="col-6">
                            <label class="form-label">Data Size</label>
                            <input type="text" name="quantity" id="quantity" class="form-control" placeholder="e.g. 1GB" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Price (₦)</label>
                            <input type="number" name="price" id="price" class="form-control" step="0.01" required>
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Validity</label>
                        <input type="text" name="validity" id="validity" class="form-control" value="30 Days" required>
                    </div>

                    <div class="mt-4 p-3" style="background: #f8fafc; border-radius: 10px;">
                        <div class="row g-3">
                            <div class="col-6">
                                <label class="form-label text-primary">App Plan ID</label>
                                <input type="number" name="plan_id" id="plan_id" class="form-control" placeholder="Unique ID" required>
                            </div>
                            <div class="col-6">
                                <label class="form-label text-danger">Alumma ID</label>
                                <input type="number" name="provider_plan_id" id="provider_plan_id" class="form-control" placeholder="Vendor ID" required>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer" style="background:var(--white); border-top:none; padding-bottom: 25px;">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success" style="background:var(--primary); border:none;">Save Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    var modal;
    
    function openModal() {
        document.getElementById('edit_id').value = '';
        document.getElementById('modalTitle').innerText = "Add Data Plan";
        document.querySelector('form').reset();
        modal = new bootstrap.Modal(document.getElementById('planModal'));
        modal.show();
    }

    function editPlan(data) {
        document.getElementById('edit_id').value = data.id;
        document.getElementById('network').value = data.network;
        document.getElementById('category').value = data.category;
        document.getElementById('quantity').value = data.quantity;
        document.getElementById('price').value = data.price;
        document.getElementById('validity').value = data.validity;
        document.getElementById('plan_id').value = data.plan_id;
        document.getElementById('provider_plan_id').value = data.provider_plan_id;
        
        document.getElementById('modalTitle').innerText = "Edit Plan: " + data.network + " " + data.quantity;
        modal = new bootstrap.Modal(document.getElementById('planModal'));
        modal.show();
    }
</script>

</body>
</html>