<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}
include '../includes/db_connection.php';

// Pagination logic
$limit = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $limit;

$sql = "SELECT * FROM leads ORDER BY created_at DESC LIMIT $start, $limit";
$result = $conn->query($sql);

$total_sql = "SELECT COUNT(id) FROM leads";
$total_result = $conn->query($total_sql);
$total_rows = $total_result->fetch_row()[0];
$total_pages = ceil($total_rows / $limit);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Trips Taker</title>
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <div class="admin-header" style="background: var(--primary-color); padding: 15px; color: white; display: flex; justify-content: space-between; align-items: center;">
        <h2>Dashboard</h2>
        <div>
            <span>Welcome, <?php echo $_SESSION['admin_user']; ?></span>
            <a href="logout.php" style="color: white; margin-left: 15px; text-decoration: underline;">Logout</a>
        </div>
    </div>

    <div class="admin-container">
        <h3>Recent Leads</h3>
        <table class="lead-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Phone</th>
                    <th>Origin - Dest</th>
                    <th>Date</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['customer_name'] . "</td>";
        echo "<td>" . $row['phone_number'] . "</td>";
        echo "<td>" . $row['origin'] . " <i class='fas fa-arrow-right'></i> " . $row['destination'] . "</td>";
        echo "<td>" . date('d M Y', strtotime($row['created_at'])) . "</td>";
        echo "<td>" . $row['status'] . "</td>";
        echo "<td><a href='view_lead.php?id=" . $row['id'] . "' class='cta-btn' style='padding: 5px 10px; font-size: 0.8rem;'>View</a></td>";
        echo "</tr>";
    }
}
else {
    echo "<tr><td colspan='7'>No leads found</td></tr>";
}
?>
            </tbody>
        </table>

        <!-- Pagination -->
        <div class="pagination">
            <?php
for ($i = 1; $i <= $total_pages; $i++) {
    $active = ($i == $page) ? 'active' : '';
    echo "<a href='dashboard.php?page=$i' class='$active'>$i</a>";
}
?>
        </div>
    </div>
</body>
</html>
