<?php
session_start();

// Hardcoded credentials for the dashboard
$admin_user = 'admin';
$admin_pass = 'admin';

// Handle login submission
if (isset($_POST['login'])) {
    if ($_POST['username'] === $admin_user && $_POST['password'] === $admin_pass) {
        $_SESSION['logged_in'] = true;
        header("Location: dashboard.php");
        exit;
    } else {
        $error = "Invalid credentials!";
    }
}

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: dashboard.php");
    exit;
}

// Show login form if not logged in
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Login | TrueQuoteZone</title>
    <link href="./assets/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --brand-primary: #0D203A;
            --brand-secondary: #008080;
        }
        body { 
            background: linear-gradient(135deg, var(--brand-primary) 0%, #051929 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Inter', sans-serif;
        }
        .login-card {
            background: white;
            padding: 2.5rem;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.2);
            width: 100%;
            max-width: 420px;
        }
        .logo-container {
            text-align: center;
            margin-bottom: 2rem;
        }
        .logo-container img {
            width: 200px;
            height: auto;
        }
        .login-title {
            color: var(--brand-primary);
            font-weight: 700;
            text-align: center;
            margin-bottom: 1.5rem;
            font-size: 1.5rem;
        }
        .btn-login {
            background-color: var(--brand-primary);
            border: none;
            border-radius: 10px;
            padding: 0.75rem;
            font-weight: 600;
            color: white;
            width: 100%;
        }
        .btn-login:hover {
            background-color: var(--brand-secondary);
            color: white;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="logo-container">
            <img src="./assets/images/logo.png" alt="TrueQuoteZone">
        </div>
        <h3 class="login-title">Admin Access</h3>
        <?php if (isset($error)): ?>
            <div class="alert alert-danger shadow-sm border-0"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <form method="POST">
            <div class="mb-3">
                <label class="form-label fw-bold text-muted small text-uppercase">Username</label>
                <input type="text" name="username" class="form-control" required autofocus>
            </div>
            <div class="mb-4">
                <label class="form-label fw-bold text-muted small text-uppercase">Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <button type="submit" name="login" class="btn btn-login">Sign In to Dashboard</button>
        </form>
    </div>
</body>
</html>
<?php
    exit;
}

// --- Dashboard Logic Below (Protected) ---
require_once 'db.php';
$db = getDB();

// Define the mapping of Display Name => internal category value
$category_map = [
    "Auto Insurance" => "auto",
    "Accidental" => "accident",
    "Home Warranty" => "homewarranty",
    "Solar" => "solar",
    "Bathroom" => "bathroom",
    "Gutters" => "gutters",
    "Windows" => "window",
    "Roofing" => "roofing",
    "Contact" => "Contact"
];

// Filter logic
$selected_display = $_GET['category'] ?? 'All';
if ($selected_display !== 'All') {
    $internal_cat = $category_map[$selected_display] ?? $selected_display;
    $stmt = $db->prepare("SELECT * FROM leads WHERE category = :category ORDER BY created_at DESC");
    $stmt->execute([':category' => $internal_cat]);
    $leads = $stmt->fetchAll();
} else {
    $stmt = $db->query("SELECT * FROM leads ORDER BY created_at DESC");
    $leads = $stmt->fetchAll();
}

function formatLeadData($jsonData) {
    $data = json_decode($jsonData, true);
    if (!$data) return "No data available";
    
    $output = '<div class="lead-details-grid">';
    foreach ($data as $key => $value) {
        if (in_array($key, ['category', 'email', 'phone'])) continue; // Skip redundant fields
        if (empty($value)) continue;
        
        $cleanKey = ucwords(str_replace(['_', '-'], ' ', $key));
        $output .= '<div class="detail-item">';
        $output .= '<span class="detail-label">' . htmlspecialchars($cleanKey) . ':</span> ';
        $output .= '<span class="detail-value">' . htmlspecialchars($value) . '</span>';
        $output .= '</div>';
    }
    $output .= '</div>';
    return $output;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lead Dashboard | TrueQuoteZone</title>
    <link href="./assets/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --brand-primary: #0D203A;
            --brand-secondary: #008080;
            --sidebar-width: 280px;
        }
        body { 
            background-color: #F4FBFF; 
            font-family: 'Inter', sans-serif;
            margin: 0;
            display: flex;
        }
        
        /* Sidebar Styles */
        .sidebar {
            width: var(--sidebar-width);
            background-color: var(--brand-primary);
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            color: white;
            padding: 2rem 1.5rem;
            z-index: 1000;
            display: flex;
            flex-direction: column;
        }
        .sidebar-logo {
            width: 180px;
            margin-bottom: 2.5rem;
            display: block;
        }
        .sidebar-heading {
            text-transform: uppercase;
            font-size: 0.75rem;
            font-weight: 700;
            color: rgba(255,255,255,0.5);
            margin-bottom: 1rem;
            letter-spacing: 1px;
        }
        .nav-categories {
            overflow-y: auto;
            flex: 1;
            margin-right: -0.5rem;
            padding-right: 0.5rem;
        }
        /* Custom scrollbar for sidebar */
        .nav-categories::-webkit-scrollbar {
            width: 5px;
        }
        .nav-categories::-webkit-scrollbar-thumb {
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
        }
        
        .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 0.8rem 1rem;
            border-radius: 10px;
            margin-bottom: 0.5rem;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            text-decoration: none;
        }
        .nav-link:hover, .nav-link.active {
            background-color: rgba(255,255,255,0.1);
            color: white;
        }
        .nav-link.active {
            background-color: var(--brand-secondary);
        }
        
        /* Main Content */
        .main-content {
            margin-left: var(--sidebar-width);
            flex: 1;
            padding: 2rem 3rem;
            min-height: 100vh;
        }
        
        .dashboard-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            padding: 2rem;
        }
        
        .header-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }
        
        .lead-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }
        .lead-table thead th {
            background: none;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75rem;
            padding: 0 1rem;
            border: none;
        }
        .lead-row {
            background: #fff;
            border-radius: 12px;
            transition: transform 0.2s ease;
        }
        .lead-row td {
            padding: 1.5rem 1rem;
            border-top: 1px solid #f1f5f9;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: top;
        }
        .lead-row td:first-child { border-left: 1px solid #f1f5f9; border-top-left-radius: 12px; border-bottom-left-radius: 12px; }
        .lead-row td:last-child { border-right: 1px solid #f1f5f9; border-top-right-radius: 12px; border-bottom-right-radius: 12px; }
        
        .badge-cat {
            background: #e0f2fe;
            color: var(--brand-primary);
            padding: 0.4rem 0.8rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.8rem;
        }
        
        /* Data Display Styles */
        .lead-details-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
            margin-top: 5px;
        }
        .detail-item {
            font-size: 0.85rem;
            color: #475569;
        }
        .detail-label {
            font-weight: 700;
            color: #1e293b;
        }
        
        .btn-logout-alt {
            color: #ef4444;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <img src="./assets/images/logo.png" alt="TrueQuoteZone" class="sidebar-logo">
        <p class="sidebar-heading">Categories</p>
        <div class="nav-categories">
            <nav>
                <a href="dashboard.php?category=All" class="nav-link <?= $selected_display === 'All' ? 'active' : '' ?>">All Leads</a>
                <?php foreach ($category_map as $display => $internal): ?>
                    <a href="dashboard.php?category=<?= urlencode($display) ?>" class="nav-link <?= $selected_display === $display ? 'active' : '' ?>">
                        <?= htmlspecialchars($display) ?>
                    </a>
                <?php endforeach; ?>
            </nav>
        </div>
        
        <div class="mt-auto pt-4">
            <hr style="border-color: rgba(255,255,255,0.1);">
            <a href="dashboard.php?logout=true" class="nav-link" style="color: #fda4af;">Sign Out</a>
        </div>
    </div>

    <div class="main-content">
        <div class="header-bar">
            <div>
                <h2 class="fw-bold text-dark m-0"><?= htmlspecialchars($selected_display) ?> Leads</h2>
                <p class="text-muted m-0">Managing entries for TrueQuoteZone</p>
            </div>
            <div class="text-end">
                <span class="badge bg-white text-dark shadow-sm p-2 px-3 border rounded-pill">
                    Total: <?= count($leads) ?> entries
                </span>
            </div>
        </div>

        <div class="dashboard-card">
            <div class="table-responsive">
                <table class="lead-table">
                    <thead>
                        <tr>
                            <th style="width: 80px;">ID</th>
                            <th style="width: 150px;">Date</th>
                            <th style="width: 250px;">Contact Info</th>
                            <th>Form Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($leads) > 0): ?>
                            <?php foreach ($leads as $lead): ?>
                                <tr class="lead-row">
                                    <td class="text-muted fw-bold">#<?= htmlspecialchars($lead['id']) ?></td>
                                    <td>
                                        <div class="fw-bold"><?= date('M j, Y', strtotime($lead['created_at'])) ?></div>
                                        <div class="text-muted small"><?= date('g:i A', strtotime($lead['created_at'])) ?></div>
                                    </td>
                                    <td>
                                        <div class="fw-bold"><?= htmlspecialchars($lead['email']) ?></div>
                                        <div class="text-primary small fw-bold"><?= htmlspecialchars($lead['phone']) ?></div>
                                        <div class="mt-2"><span class="badge-cat"><?= htmlspecialchars($lead['category']) ?></span></div>
                                    </td>
                                    <td>
                                        <?= formatLeadData($lead['data']) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="text-center py-5 text-muted">No leads found in this category.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
