<?php
require_once '../connection.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit();
}

// Get statistics
$stmt = $pdo->query("SELECT COUNT(*) as total FROM clients WHERE is_active = 1");
$total_clients = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as active_subs FROM subscriptions WHERE is_active = 1 AND end_date >= CURDATE()");
$active_subs = $stmt->fetch()['active_subs'];

$stmt = $pdo->query("SELECT SUM(amount) as total_revenue FROM transactions WHERE type IN ('subscription_payment', 'auto_debit') AND status = 'completed'");
$total_revenue = $stmt->fetch()['total_revenue'] ?? 0;

$stmt = $pdo->query("SELECT SUM(wallet_balance) as total_wallet FROM clients");
$total_wallet = $stmt->fetch()['total_wallet'] ?? 0;
?>

<!DOCTYPE html>
<html>
<head>
    <title>ISP Manager - Admin Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-dark bg-dark">
        <div class="container-fluid">
            <span class="navbar-brand">ISP Manager - Admin Panel</span>
            <a href="../logout.php" class="btn btn-outline-light">Logout</a>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-3">
                <div class="card text-white bg-primary mb-3">
                    <div class="card-body">
                        <h5 class="card-title">Total Clients</h5>
                        <h2><?php echo $total_clients; ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-white bg-success mb-3">
                    <div class="card-body">
                        <h5 class="card-title">Active Subscriptions</h5>
                        <h2><?php echo $active_subs; ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-white bg-info mb-3">
                    <div class="card-body">
                        <h5 class="card-title">Total Revenue</h5>
                        <h2>$<?php echo number_format($total_revenue, 2); ?></h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-white bg-warning mb-3">
                    <div class="card-body">
                        <h5 class="card-title">Wallet Balance</h5>
                        <h2>$<?php echo number_format($total_wallet, 2); ?></h2>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item">
                <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#clients">Clients</button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#plans">Plans</button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#payments">Payments</button>
            </li>
           <li class="nav-item">
    <a href="laptops.php" class="nav-link">
        <i class="fas fa-laptop"></i> Manage Laptops
    </a>
</li>
        </ul>

        <div class="tab-content mt-3">
            <!-- Clients Tab -->
            <div class="tab-pane fade show active" id="clients">
                <div class="card">
                    <div class="card-header">
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addClientModal">Add New Client</button>
                    </div>
                    <div class="card-body">
                        <table id="clientsTable" class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Username</th>
                                    <th>Full Name</th>
                                    <th>Email</th>
                                    <th>PPPoE User</th>
                                    <th>Wallet Balance</th>
                                    <th>Current Plan</th>
                                    <th>Subscription Expiry</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $stmt = $pdo->query("
                                    SELECT c.*, s.end_date as expiry_date, p.name as plan_name 
                                    FROM clients c 
                                    LEFT JOIN subscriptions s ON c.id = s.client_id AND s.is_active = 1 
                                    LEFT JOIN plans p ON s.plan_id = p.id
                                    WHERE c.is_active = 1
                                ");
                                while($row = $stmt->fetch()) {
                                    $expiry_class = strtotime($row['expiry_date']) < time() ? 'text-danger' : 'text-success';
                                    echo "<tr>
                                        <td>{$row['id']}</td>
                                        <td>{$row['username']}</td>
                                        <td>{$row['full_name']}</td>
                                        <td>{$row['email']}</td>
                                        <td>{$row['pppoe_username']}</td>
                                        <td>\${$row['wallet_balance']}</td>
                                        <td>{$row['plan_name']}</td>
                                        <td class='$expiry_class'>{$row['expiry_date']}</td>
                                        <td><span class='badge bg-success'>Active</span></td>
                                        <td>
                                            <button class='btn btn-sm btn-info' onclick='viewClient({$row['id']})'>View</button>
                                            <button class='btn btn-sm btn-danger' onclick='disableClient({$row['id']})'>Disable</button>
                                        </td>
                                    </tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Plans Tab -->
            <div class="tab-pane fade" id="plans">
                <div class="card">
                    <div class="card-header">
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPlanModal">Add New Plan</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Plan Name</th>
                                    <th>Speed (Mbps)</th>
                                    <th>Price</th>
                                    <th>Duration</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $stmt = $pdo->query("SELECT * FROM plans WHERE is_active = 1");
                                while($plan = $stmt->fetch()) {
                                    echo "<tr>
                                        <td>{$plan['id']}</td>
                                        <td>{$plan['name']}</td>
                                        <td>{$plan['speed_mbps']}</td>
                                        <td>\${$plan['price']}</td>
                                        <td>{$plan['duration_days']} days</td>
                                        <td><span class='badge bg-success'>Active</span></td>
                                        <td>
                                            <button class='btn btn-sm btn-warning' onclick='editPlan({$plan['id']})'>Edit</button>
                                            <button class='btn btn-sm btn-danger' onclick='deletePlan({$plan['id']})'>Delete</button>
                                        </td>
                                    </tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Payments Tab -->
            <div class="tab-pane fade" id="payments">
                <div class="card">
                    <div class="card-body">
                        <table id="paymentsTable" class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Client</th>
                                    <th>Amount</th>
                                    <th>Type</th>
                                    <th>Reference</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $stmt = $pdo->query("
                                    SELECT t.*, c.full_name 
                                    FROM transactions t 
                                    JOIN clients c ON t.client_id = c.id 
                                    ORDER BY t.created_at DESC 
                                    LIMIT 100
                                ");
                                while($payment = $stmt->fetch()) {
                                    echo "<tr>
                                        <td>{$payment['created_at']}</td>
                                        <td>{$payment['full_name']}</td>
                                        <td>\${$payment['amount']}</td>
                                        <td>{$payment['type']}</td>
                                        <td>{$payment['reference']}</td>
                                        <td><span class='badge bg-success'>{$payment['status']}</span></td>
                                    </tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Client Modal -->
    <div class="modal fade" id="addClientModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Client</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="add_client.php" method="POST">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label>Username</label>
                            <input type="text" name="username" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label>Password</label>
                            <input type="password" name="password" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label>Full Name</label>
                            <input type="text" name="full_name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label>Email</label>
                            <input type="email" name="email" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label>Phone</label>
                            <input type="text" name="phone" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label>Plan</label>
                            <select name="plan_id" class="form-control" required>
                                <option value="">Select Plan</option>
                                <?php
                                $plans = $pdo->query("SELECT * FROM plans WHERE is_active = 1");
                                while($plan = $plans->fetch()) {
                                    echo "<option value='{$plan['id']}'>{$plan['name']} - {$plan['speed_mbps']}Mbps (\${$plan['price']})</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Add Client</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#clientsTable').DataTable();
            $('#paymentsTable').DataTable();
        });
        
        function viewClient(id) {
            window.location.href = 'view_client.php?id=' + id;
        }
        
        function disableClient(id) {
            if(confirm('Are you sure you want to disable this client?')) {
                window.location.href = 'disable_client.php?id=' + id;
            }
        }
    </script>
</body>
</html>