<?php
require_once '../includes/db.php';
require_once '../includes/functions.php';

// Ensure only admin can access this page
redirectIfNotAdmin();

// Handle message deletion
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    try {
        $stmt = $pdo->prepare("DELETE FROM contact_messages WHERE id = ?");
        $stmt->execute([$_GET['delete']]);
        $_SESSION['success'] = "Message deleted successfully.";
    } catch (PDOException $e) {
        error_log("Error deleting message: " . $e->getMessage());
        $_SESSION['error'] = "Failed to delete message.";
    }
    header("Location: manage-messages.php");
    exit();
}

// Handle bulk delete
if (isset($_POST['bulk_delete']) && isset($_POST['message_ids']) && is_array($_POST['message_ids'])) {
    try {
        $ids = array_map('intval', $_POST['message_ids']);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $pdo->prepare("DELETE FROM contact_messages WHERE id IN ($placeholders)");
        $stmt->execute($ids);
        $_SESSION['success'] = count($ids) . " message(s) deleted successfully.";
    } catch (PDOException $e) {
        error_log("Error bulk deleting messages: " . $e->getMessage());
        $_SESSION['error'] = "Failed to delete selected messages.";
    }
    header("Location: manage-messages.php");
    exit();
}

// Update message status
if (isset($_POST['update_status']) && isset($_POST['message_id']) && isset($_POST['status'])) {
    try {
        $stmt = $pdo->prepare("UPDATE contact_messages SET status = ? WHERE id = ?");
        $stmt->execute([$_POST['status'], $_POST['message_id']]);
        $_SESSION['success'] = "Message status updated successfully.";
    } catch (PDOException $e) {
        error_log("Error updating message status: " . $e->getMessage());
        $_SESSION['error'] = "Failed to update message status.";
    }
    header("Location: manage-messages.php");
    exit();
}

// Pagination setup
$perPage = 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
$offset = ($page - 1) * $perPage;

// Filter setup
$statusFilter = isset($_GET['status']) ? $_GET['status'] : '';
$searchFilter = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query with filters
$whereConditions = [];
$params = [];

if ($statusFilter !== '') {
    $whereConditions[] = "status = ?";
    $params[] = $statusFilter;
}

if ($searchFilter !== '') {
    $whereConditions[] = "(name LIKE ? OR email LIKE ? OR subject LIKE ? OR message LIKE ?)";
    $searchTerm = "%$searchFilter%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$whereClause = !empty($whereConditions) ? "WHERE " . implode(" AND ", $whereConditions) : "";

// Count total messages with filters
$countSql = "SELECT COUNT(*) FROM contact_messages $whereClause";
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalCount = $countStmt->fetchColumn();
$totalPages = ceil($totalCount / $perPage);

try {
    // Fetch all contact messages ordered by newest first (paginated)
    $sql = "SELECT * FROM contact_messages $whereClause ORDER BY created_at DESC LIMIT ? OFFSET ?";
    $stmt = $pdo->prepare($sql);
    $queryParams = array_merge($params, [$perPage, $offset]);
    $stmt->execute($queryParams);
    $messages = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Error fetching messages: " . $e->getMessage());
    die("Error fetching messages. Please try again later.");
}

// Get current admin info
$adminId = $_SESSION['user_id'];
$adminInfo = $pdo->prepare("SELECT full_name, email FROM users WHERE user_id = ?");
$adminInfo->execute([$adminId]);
$admin = $adminInfo->fetch();

// Calculate statistics
$totalMessages = $totalCount;
$newCount = $pdo->query("SELECT COUNT(*) FROM contact_messages WHERE status = 'new'")->fetchColumn();
$readCount = $pdo->query("SELECT COUNT(*) FROM contact_messages WHERE status = 'read'")->fetchColumn();
$repliedCount = $pdo->query("SELECT COUNT(*) FROM contact_messages WHERE status = 'replied'")->fetchColumn();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oakshire Finance - Contact Messages</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --warning-orange: #f39c12;
            --error-red: #dc3545;
            --info-blue: #17a2b8;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
            overflow-x: hidden;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: var(--transition);
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.3px;
        }

        .nav-menu {
            padding: 24px 16px;
        }

        .nav-item {
            margin-bottom: 8px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .nav-link.active i {
            color: white;
        }

        .logout-section {
            padding: 24px 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            transition: var(--transition);
            font-weight: 500;
        }

        .logout-btn:hover {
            background: rgba(220, 53, 69, 0.1);
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        /* Top Header */
        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
            transition: var(--transition);
        }

        .notification-btn:hover {
            color: var(--primary-blue);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-avatar i {
            font-size: 18px;
            color: white;
        }

        .user-details h4 {
            font-size: 14px;
            font-weight: 600;
            color: var(--gray-900);
        }

        .user-details p {
            font-size: 12px;
            color: var(--gray-600);
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 24px;
            margin-bottom: 32px;
        }

        .stat-card {
            background: var(--white);
            border-radius: 20px;
            padding: 20px;
            border: 1px solid var(--gray-200);
            transition: var(--transition);
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-hover);
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            background: rgba(26, 77, 140, 0.1);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
        }

        .stat-icon i {
            font-size: 24px;
            color: var(--primary-blue);
        }

        .stat-card h3 {
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: var(--gray-900);
        }

        /* Filter Bar */
        .filter-bar {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            padding: 20px 24px;
            margin-bottom: 24px;
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            align-items: center;
            justify-content: space-between;
        }

        .filter-group {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }

        .filter-group input,
        .filter-group select {
            padding: 10px 14px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 10px;
            transition: var(--transition);
            outline: none;
        }

        .filter-group input:focus,
        .filter-group select:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .btn-filter,
        .btn-clear {
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            border: none;
        }

        .btn-filter {
            background: var(--primary-navy);
            color: white;
        }

        .btn-filter:hover {
            background: var(--primary-dark);
        }

        .btn-clear {
            background: var(--gray-100);
            color: var(--gray-700);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-clear:hover {
            background: var(--gray-200);
        }

        /* Bulk Actions */
        .bulk-actions {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            padding: 16px 24px;
            margin-bottom: 24px;
            display: flex;
            gap: 16px;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
        }

        .bulk-actions-left {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        .btn-bulk-delete {
            padding: 8px 16px;
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-bulk-delete:hover {
            background: var(--error-red);
            color: white;
        }

        /* Table */
        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 13px;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            font-size: 14px;
            color: var(--gray-800);
        }

        .data-table tr:hover td {
            background: var(--gray-50);
        }

        /* Badges */
        .badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-new {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .badge-read {
            background: rgba(108, 117, 125, 0.1);
            color: var(--gray-600);
        }

        .badge-replied {
            background: rgba(26, 77, 140, 0.1);
            color: var(--primary-blue);
        }

        .message-preview {
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        /* Buttons */
        .btn-icon {
            padding: 6px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .btn-view {
            background: rgba(26, 77, 140, 0.1);
            color: var(--primary-blue);
        }

        .btn-view:hover {
            background: var(--primary-blue);
            color: white;
        }

        .btn-delete {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .btn-delete:hover {
            background: var(--error-red);
            color: white;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 48px;
            color: var(--gray-500);
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        /* Checkbox */
        .checkbox {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: var(--primary-blue);
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-top: 24px;
        }

        .pagination a {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 36px;
            height: 36px;
            padding: 0 12px;
            border-radius: 8px;
            background: var(--white);
            border: 1px solid var(--gray-200);
            color: var(--gray-700);
            text-decoration: none;
            font-size: 14px;
            transition: var(--transition);
        }

        .pagination a:hover {
            background: var(--gray-100);
            border-color: var(--gray-300);
        }

        .pagination a.active {
            background: var(--primary-navy);
            border-color: var(--primary-navy);
            color: white;
        }

        /* Alert Messages */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-700);
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .user-details {
                display: none;
            }

            .stats-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .filter-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .filter-group {
                flex-direction: column;
                width: 100%;
            }

            .filter-group input,
            .filter-group select {
                width: 100%;
            }

            .bulk-actions {
                flex-direction: column;
                align-items: stretch;
            }

            .bulk-actions-left {
                justify-content: space-between;
            }

            .data-table th,
            .data-table td {
                padding: 12px 16px;
            }

            .message-preview {
                max-width: 200px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <nav class="nav-menu">
                <div class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="fas fa-chart-line"></i>
                        <span>Dashboard</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-users.php" class="nav-link">
                        <i class="fas fa-users"></i>
                        <span>Manage Users</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-loans.php" class="nav-link">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Manage Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-investments.php" class="nav-link">
                        <i class="fas fa-chart-pie"></i>
                        <span>Manage Investments</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="track-investments.php" class="nav-link">
                        <i class="fas fa-chart-simple"></i>
                        <span>Users Investments</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="role.php" class="nav-link">
                        <i class="fas fa-user-tag"></i>
                        <span>Roles</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="recent_transactions.php" class="nav-link">
                        <i class="fas fa-exchange-alt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan-history.php" class="nav-link">
                        <i class="fas fa-history"></i>
                        <span>Loan History</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="login-records.php" class="nav-link">
                        <i class="fas fa-sign-in-alt"></i>
                        <span>Login Records</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-messages.php" class="nav-link active">
                        <i class="fas fa-envelope"></i>
                        <span>Contact Messages</span>
                    </a>
                </div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <button class="hamburger" id="hamburger">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1>Contact Messages</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn">
                        <i class="fas fa-bell"></i>
                    </button>
                    <div class="user-info">
                        <div class="user-avatar">
                            <i class="fas fa-user-shield"></i>
                        </div>
                        <div class="user-details">
                            <h4><?= htmlspecialchars($admin['full_name'] ?? 'Admin User') ?></h4>
                            <p>System Administrator</p>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Statistics Cards -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-envelope"></i>
                        </div>
                        <h3>Total Messages</h3>
                        <div class="stat-value"><?= number_format($totalMessages) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <h3>New Messages</h3>
                        <div class="stat-value"><?= number_format($newCount) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <h3>Read</h3>
                        <div class="stat-value"><?= number_format($readCount) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-reply-all"></i>
                        </div>
                        <h3>Replied</h3>
                        <div class="stat-value"><?= number_format($repliedCount) ?></div>
                    </div>
                </div>

                <!-- Alert Messages -->
                <?php if (isset($_SESSION['success'])): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <span><?= $_SESSION['success'] ?></span>
                    </div>
                    <?php unset($_SESSION['success']); ?>
                <?php endif; ?>

                <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?= $_SESSION['error'] ?></span>
                    </div>
                    <?php unset($_SESSION['error']); ?>
                <?php endif; ?>

                <!-- Filter Bar -->
                <div class="filter-bar">
                    <form method="GET" style="display: contents;">
                        <div class="filter-group">
                            <input type="text" name="search" placeholder="Search by name, email, subject..."
                                value="<?= htmlspecialchars($searchFilter) ?>">
                            <select name="status">
                                <option value="">All Status</option>
                                <option value="new" <?= $statusFilter === 'new' ? 'selected' : '' ?>>New</option>
                                <option value="read" <?= $statusFilter === 'read' ? 'selected' : '' ?>>Read</option>
                                <option value="replied" <?= $statusFilter === 'replied' ? 'selected' : '' ?>>Replied
                                </option>
                            </select>
                            <button type="submit" class="btn-filter">
                                <i class="fas fa-search"></i> Apply Filters
                            </button>
                            <a href="manage-messages.php" class="btn-clear">
                                <i class="fas fa-times"></i> Clear
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Bulk Actions -->
                <form method="POST" id="bulkForm">
                    <div class="bulk-actions">
                        <div class="bulk-actions-left">
                            <input type="checkbox" id="selectAll" class="checkbox">
                            <label for="selectAll" style="font-size: 14px;">Select All</label>
                        </div>
                        <div>
                            <button type="submit" name="bulk_delete" class="btn-bulk-delete"
                                onclick="return confirmBulkDelete()">
                                <i class="fas fa-trash"></i> Delete Selected
                            </button>
                        </div>
                    </div>

                    <!-- Messages Table -->
                    <div class="table-container">
                        <?php if (empty($messages)): ?>
                            <div class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <p>No messages found</p>
                                <?php if ($searchFilter || $statusFilter): ?>
                                    <p style="margin-top: 8px; font-size: 13px;">Try adjusting your filters</p>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th style="width: 40px;">
                                            <input type="checkbox" id="selectAllHeader" class="checkbox">
                                        </th>
                                        <th>Date</th>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Subject</th>
                                        <th>Message</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                </thead>
                                <tbody>
                                    <?php foreach ($messages as $message):
                                        $statusClass = '';
                                        $statusIcon = '';
                                        if ($message['status'] === 'new') {
                                            $statusClass = 'badge-new';
                                            $statusIcon = 'fa-envelope';
                                        } elseif ($message['status'] === 'read') {
                                            $statusClass = 'badge-read';
                                            $statusIcon = 'fa-check-circle';
                                        } else {
                                            $statusClass = 'badge-replied';
                                            $statusIcon = 'fa-reply-all';
                                        }
                                        ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" name="message_ids[]" value="<?= $message['id'] ?>"
                                                    class="checkbox message-checkbox">
                                            </td>
                                            <td data-label="Date">
                                                <strong><?= date('M d, Y', strtotime($message['created_at'])) ?></strong>
                                                <br>
                                                <small
                                                    style="color: var(--gray-500);"><?= date('h:i A', strtotime($message['created_at'])) ?></small>
                                            </td>
                                            <td data-label="Name">
                                                <strong><?= htmlspecialchars($message['name']) ?></strong>
                                            </td>
                                            <td data-label="Email">
                                                <a href="mailto:<?= htmlspecialchars($message['email']) ?>"
                                                    style="color: var(--primary-blue); text-decoration: none;">
                                                    <?= htmlspecialchars($message['email']) ?>
                                                </a>
                                            </td>
                                            <td data-label="Subject">
                                                <?= htmlspecialchars($message['subject']) ?>
                                            </td>
                                            <td data-label="Message" class="message-preview">
                                                <?= htmlspecialchars($message['message']) ?>
                                            </td>
                                            <td data-label="Status">
                                                <span class="badge <?= $statusClass ?>">
                                                    <i class="fas <?= $statusIcon ?>"></i> <?= ucfirst($message['status']) ?>
                                                </span>
                                            </td>
                                            <td data-label="Actions">
                                                <div class="action-buttons">
                                                    <a href="view-message.php?id=<?= $message['id'] ?>"
                                                        class="btn-icon btn-view">
                                                        <i class="fas fa-eye"></i> View
                                                    </a>
                                                    <a href="manage-messages.php?delete=<?= $message['id'] ?>"
                                                        class="btn-icon btn-delete"
                                                        onclick="return confirm('Are you sure you want to delete this message?')">
                                                        <i class="fas fa-trash"></i> Delete
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>

                    <!-- Hidden input to identify bulk delete action -->
                    <input type="hidden" name="bulk_delete" id="bulkDeleteHidden" value="">
                </form>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a
                                href="?page=<?= $page - 1 ?>&search=<?= urlencode($searchFilter) ?>&status=<?= urlencode($statusFilter) ?>">
                                <i class="fas fa-chevron-left"></i> Prev
                            </a>
                        <?php endif; ?>

                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                <a href="?page=<?= $i ?>&search=<?= urlencode($searchFilter) ?>&status=<?= urlencode($statusFilter) ?>"
                                    class="<?= $i == $page ? 'active' : '' ?>">
                                    <?= $i ?>
                                </a>
                            <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                <span style="padding: 0 4px;">...</span>
                            <?php endif; ?>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                            <a
                                href="?page=<?= $page + 1 ?>&search=<?= urlencode($searchFilter) ?>&status=<?= urlencode($statusFilter) ?>">
                                Next <i class="fas fa-chevron-right"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                sidebar.classList.toggle('mobile-open');
            });
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (event) {
            if (window.innerWidth <= 1024) {
                const isClickInside = sidebar.contains(event.target) || hamburger.contains(event.target);
                if (!isClickInside && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Select All functionality
        const selectAll = document.getElementById('selectAll');
        const selectAllHeader = document.getElementById('selectAllHeader');
        const checkboxes = document.querySelectorAll('.message-checkbox');

        function updateSelectAll() {
            const allChecked = checkboxes.length > 0 && Array.from(checkboxes).every(cb => cb.checked);
            if (selectAll) selectAll.checked = allChecked;
            if (selectAllHeader) selectAllHeader.checked = allChecked;
        }

        if (selectAll) {
            selectAll.addEventListener('change', function () {
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        }

        if (selectAllHeader) {
            selectAllHeader.addEventListener('change', function () {
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        }

        checkboxes.forEach(cb => {
            cb.addEventListener('change', updateSelectAll);
        });

        // Bulk delete confirmation
        function confirmBulkDelete() {
            const selected = document.querySelectorAll('.message-checkbox:checked');
            if (selected.length === 0) {
                alert('Please select at least one message to delete.');
                return false;
            }
            return confirm(`Are you sure you want to delete ${selected.length} message(s)? This action cannot be undone.`);
        }

        // Auto-dismiss alerts after 5 seconds
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        });
    </script>
</body>

</html>