<?php
session_start();

// Handle logout at the VERY TOP of the file
if (isset($_GET['logout']) || isset($_POST['logout'])) {
    // Clear all session data
    $_SESSION = array();
    
    // Destroy the session cookie
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time()-3600, '/');
    }
    
    // Destroy the session
    session_destroy();
    
    // Redirect to login page
    header('Location: index.php');
    exit;
}

// Check if logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Database connection
try {
    $pdo = new PDO('mysql:host=localhost;dbname=migrant_ereg', 'root', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Get statistics
$total_migrants = $pdo->query("SELECT COUNT(*) FROM biographical_information WHERE deleted_at IS NULL")->fetchColumn();

$status_stats = $pdo->query("
    SELECT status, COUNT(*) as count 
    FROM application_status a1
    WHERE created_at = (
        SELECT MAX(created_at) 
        FROM application_status a2 
        WHERE a2.person_id = a1.person_id
    )
    GROUP BY status
")->fetchAll(PDO::FETCH_KEY_PAIR);

$pending = ($status_stats['Submitted'] ?? 0) + ($status_stats['Under Review'] ?? 0);
$approved = $status_stats['Approved'] ?? 0;
$rejected = $status_stats['Rejected'] ?? 0;

// Get recent migrants
$recent = $pdo->query("
    SELECT b.*, a.status 
    FROM biographical_information b
    LEFT JOIN application_status a ON b.person_id = a.person_id
    WHERE b.deleted_at IS NULL
    GROUP BY b.person_id
    ORDER BY b.created_at DESC
    LIMIT 5
")->fetchAll();

// Get nationality distribution
$nationalities = $pdo->query("
    SELECT nationality, COUNT(*) as count 
    FROM biographical_information 
    WHERE deleted_at IS NULL 
    GROUP BY nationality 
    ORDER BY count DESC 
    LIMIT 5
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - NIS Migrant e-Registration</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --nis-primary: #006747;
            --nis-secondary: #00843D;
            --nis-accent: #FFD100;
            --nis-dark: #004225;
            --nis-light: #E8F0E8;
        }
        body {
            background: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .wrapper {
            display: flex;
            width: 100%;
            align-items: stretch;
        }
        #sidebar {
            min-width: 280px;
            max-width: 280px;
            background: linear-gradient(180deg, var(--nis-primary) 0%, var(--nis-dark) 100%);
            color: #fff;
            transition: all 0.3s;
            min-height: 100vh;
            position: fixed;
            height: 100%;
            overflow-y: auto;
        }
        #sidebar .sidebar-header {
            padding: 20px;
            text-align: center;
            border-bottom: 2px solid var(--nis-accent);
        }
        #sidebar .sidebar-header h3 {
            color: var(--nis-accent);
            font-size: 1.2rem;
            margin-top: 10px;
        }
        #sidebar ul.components {
            padding: 20px 0;
        }
        #sidebar ul li a {
            padding: 12px 20px;
            display: flex;
            align-items: center;
            color: #fff;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 4px solid transparent;
        }
        #sidebar ul li a i {
            width: 25px;
            margin-right: 10px;
        }
        #sidebar ul li a:hover {
            background: rgba(255,255,255,0.1);
            border-left-color: var(--nis-accent);
        }
        #sidebar ul li a.logout-btn {
            border-top: 1px solid rgba(255,255,255,0.1);
            margin-top: 20px;
        }
        #sidebar ul li a.logout-btn:hover {
            background: #dc3545;
            border-left-color: #ffc107;
        }
        #content {
            width: 100%;
            margin-left: 280px;
            padding: 20px;
        }
        .navbar {
            background: #fff;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border-radius: 10px;
            padding: 15px;
        }
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
            transition: transform 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .stat-card .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--nis-dark);
        }
        .stat-card .stat-label {
            color: #6c757d;
        }
        .btn-nis {
            background: var(--nis-primary);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .btn-nis:hover {
            background: var(--nis-dark);
            color: white;
            transform: translateY(-2px);
        }
        .btn-outline-nis {
            border: 2px solid var(--nis-primary);
            color: var(--nis-primary);
            background: transparent;
            padding: 8px 20px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .btn-outline-nis:hover {
            background: var(--nis-primary);
            color: white;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 50px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .badge-draft { background: #6c757d; color: white; }
        .badge-submitted { background: #ffc107; color: #000; }
        .badge-review { background: #17a2b8; color: white; }
        .badge-approved { background: #28a745; color: white; }
        .badge-rejected { background: #dc3545; color: white; }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .card-header {
            background: white;
            border-bottom: 2px solid var(--nis-light);
            padding: 15px 20px;
            font-weight: 600;
        }
        .card-header i {
            color: var(--nis-primary);
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <i class="fas fa-passport fa-3x"></i>
                <h3>NIS MIGRANT<br>e-REGISTRATION</h3>
            </div>
            
            <ul class="list-unstyled components">
                <li class="active">
                    <a href="dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                </li>
                <?php if (in_array($_SESSION['role'], ['ImmigrationOfficer', 'Admin', 'SuperAdmin'])): ?>
                <li>
                    <a href="register.php">
                        <i class="fas fa-user-plus"></i> New Registration
                    </a>
                </li>
                <?php endif; ?>
                <li>
                    <a href="search.php">
                        <i class="fas fa-search"></i> Search Migrants
                    </a>
                </li>
                <?php if (in_array($_SESSION['role'], ['Admin', 'SuperAdmin'])): ?>
                <li>
                    <a href="pending.php">
                        <i class="fas fa-clock"></i> Pending Reviews
                    </a>
                </li>
                <?php endif; ?>
                <?php if ($_SESSION['role'] === 'SuperAdmin'): ?>
                <li>
                    <a href="users.php">
                        <i class="fas fa-users-cog"></i> User Management
                    </a>
                </li>
                <?php endif; ?>
                <li>
                    <a href="profile.php">
                        <i class="fas fa-user-circle"></i> My Profile
                    </a>
                </li>
                <li>
                    <li>
    <a href="logout.php" class="logout-btn" onclick="return confirm('Are you sure you want to logout?');">
        <i class="fas fa-sign-out-alt"></i> Logout
    </a>
</li>
                </li>
            </ul>
        </nav>

        <!-- Page Content -->
        <div id="content">
            <nav class="navbar">
                <div class="container-fluid">
                    <h4 class="mb-0"><i class="fas fa-tachometer-alt me-2" style="color: var(--nis-primary);"></i>Dashboard</h4>
                    <div class="d-flex align-items-center">
                        <i class="fas fa-user-circle fa-2x me-2" style="color: var(--nis-primary);"></i>
                        <div>
                            <div class="fw-bold"><?= htmlspecialchars($_SESSION['full_name']) ?></div>
                            <small class="text-muted"><?= $_SESSION['role'] ?></small>
                        </div>
                    </div>
                </div>
            </nav>

            <!-- Statistics Cards -->
            <div class="row">
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="d-flex justify-content-between">
                            <div>
                                <div class="stat-value"><?= $total_migrants ?></div>
                                <div class="stat-label">Total Migrants</div>
                            </div>
                            <i class="fas fa-users fa-3x" style="color: var(--nis-primary); opacity: 0.3;"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="d-flex justify-content-between">
                            <div>
                                <div class="stat-value"><?= $pending ?></div>
                                <div class="stat-label">Pending Review</div>
                            </div>
                            <i class="fas fa-clock fa-3x" style="color: #ffc107; opacity: 0.3;"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="d-flex justify-content-between">
                            <div>
                                <div class="stat-value"><?= $approved ?></div>
                                <div class="stat-label">Approved</div>
                            </div>
                            <i class="fas fa-check-circle fa-3x" style="color: #28a745; opacity: 0.3;"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="d-flex justify-content-between">
                            <div>
                                <div class="stat-value"><?= $rejected ?></div>
                                <div class="stat-label">Rejected</div>
                            </div>
                            <i class="fas fa-times-circle fa-3x" style="color: #dc3545; opacity: 0.3;"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Charts Row -->
            <div class="row mt-4">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-chart-pie me-2"></i>
                            Nationality Distribution
                        </div>
                        <div class="card-body">
                            <canvas id="nationalityChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-chart-bar me-2"></i>
                            Application Status
                        </div>
                        <div class="card-body">
                            <canvas id="statusChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Registrations -->
            <div class="row mt-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <i class="fas fa-user-plus me-2"></i>
                            Recent Registrations
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Person ID</th>
                                            <th>Name</th>
                                            <th>Document No</th>
                                            <th>Nationality</th>
                                            <th>Status</th>
                                            <th>Date</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent as $row): ?>
                                        <tr>
                                            <td><code><?= htmlspecialchars($row['person_id']) ?></code></td>
                                            <td><?= htmlspecialchars($row['surname']) ?>, <?= htmlspecialchars($row['given_name']) ?></td>
                                            <td><?= htmlspecialchars($row['document_no']) ?></td>
                                            <td><?= htmlspecialchars($row['nationality']) ?></td>
                                            <td>
                                                <?php
                                                $status = $row['status'] ?? 'Draft';
                                                $badge = '';
                                                switch($status) {
                                                    case 'Draft': $badge = 'badge-draft'; break;
                                                    case 'Submitted': $badge = 'badge-submitted'; break;
                                                    case 'Under Review': $badge = 'badge-review'; break;
                                                    case 'Approved': $badge = 'badge-approved'; break;
                                                    case 'Rejected': $badge = 'badge-rejected'; break;
                                                }
                                                ?>
                                                <span class="status-badge <?= $badge ?>"><?= $status ?></span>
                                            </td>
                                            <td><?= date('d/m/Y', strtotime($row['created_at'])) ?></td>
                                            <td>
                                                <a href="view.php?id=<?= urlencode($row['person_id']) ?>" class="btn btn-sm btn-outline-nis">
                                                    <i class="fas fa-eye"></i> View
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Nationality Chart
        const nationalityCtx = document.getElementById('nationalityChart').getContext('2d');
        new Chart(nationalityCtx, {
            type: 'pie',
            data: {
                labels: [<?php foreach ($nationalities as $n): ?><?= "'" . addslashes($n['nationality']) . "'," ?><?php endforeach; ?>],
                datasets: [{
                    data: [<?php foreach ($nationalities as $n): ?><?= $n['count'] ?>,<?php endforeach; ?>],
                    backgroundColor: ['#006747', '#00843D', '#FFD100', '#004225', '#2E7D32']
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // Status Chart
        const statusCtx = document.getElementById('statusChart').getContext('2d');
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['Draft', 'Submitted', 'Under Review', 'Approved', 'Rejected'],
                datasets: [{
                    data: [
                        <?= $status_stats['Draft'] ?? 0 ?>,
                        <?= $status_stats['Submitted'] ?? 0 ?>,
                        <?= $status_stats['Under Review'] ?? 0 ?>,
                        <?= $status_stats['Approved'] ?? 0 ?>,
                        <?= $status_stats['Rejected'] ?? 0 ?>
                    ],
                    backgroundColor: ['#6c757d', '#ffc107', '#17a2b8', '#28a745', '#dc3545']
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>