<?php
include "../include/db.php";
include "include/header.php";

$errors = [];
$success = '';

// Pagination Settings
$per_page = 10;
$page = (int)($_GET['page'] ?? 1);
$offset = ($page - 1) * $per_page;

// Handle Mark as Read
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_read'])) {
    $id = (int)($_POST['contact_id'] ?? 0);
    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE contacts SET status = 'read' WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $success = "Message marked as read!";
        } else {
            $errors[] = "Failed to update.";
        }
        $stmt->close();
    }
}

// Handle Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_contact'])) {
    $id = (int)($_POST['contact_id'] ?? 0);
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM contacts WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $success = "Message deleted successfully!";
        } else {
            $errors[] = "Failed to delete.";
        }
        $stmt->close();
    }
}

// Total contacts
$total_stmt = $conn->query("SELECT COUNT(*) as total FROM contacts");
$total_row = $total_stmt->fetch_assoc();
$total_contacts = $total_row['total'];
$total_pages = ceil($total_contacts / $per_page);

// Fetch contacts with LIMIT
$stmt = $conn->prepare("SELECT * FROM contacts ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bind_param("ii", $per_page, $offset);
$stmt->execute();
$result = $stmt->get_result();
$contacts = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Contact Messages</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        body { font-family: 'Inter', sans-serif; overflow-x: hidden; }
        .content { transition: margin-left 0.3s ease; margin-left: 250px; }
        .top-nav { background: linear-gradient(135deg, #1E293B 0%, #334155 100%); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
        .search-input { transition: all 0.3s; }
        .search-input:focus { transform: scale(1.02); box-shadow: 0 0 0 3px rgba(251, 191, 36, 0.3); }

        /* Table */
        .table-container {
            background: white; border-radius: 16px; overflow: hidden; box-shadow: 0 20px 40px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
        }
        .table-container:hover { box-shadow: 0 25px 50px rgba(0,0,0,0.12); }
        .table-header {
            background: linear-gradient(135deg, #1E293B 0%, #334155 100%); color: white; font-weight: 600;
            text-transform: uppercase; letter-spacing: 0.5px; font-size: 0.875rem;
        }
        .table-row { transition: all 0.2s ease; border-bottom: 1px solid #f1f5f9; }
        .table-row:hover {
            background: linear-gradient(to right, #fffbeb 0%, #fefce8 100%);
            transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        .badge { @apply inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold; min-width: 70px; justify-content: center; }
        .badge-unread { background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); color: #991b1b; }
        .badge-read { background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%); color: #065f46; }
        .action-btn { @apply px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-200 flex items-center gap-1; }
        .btn-reply { @apply bg-blue-600 text-white hover:bg-blue-700; }
        .btn-read { @apply bg-emerald-600 text-white hover:bg-emerald-700; }
        .btn-delete04 { @apply bg-rose-600 text-white hover:bg-rose-700; }
        .empty-state { text-align: center; padding: 4rem 2rem; color: #64748b; }
        .empty-state i { font-size: 3rem; color: #cbd5e1; margin-bottom: 1rem; }

        /* Send Mail Button (Top Right) */
        .btn-send-mail {
            @apply bg-gradient-to-r from-amber-500 to-amber-600 text-white px-5 py-2.5 rounded-xl font-semibold flex items-center gap-2 shadow-lg hover:from-amber-600 hover:to-amber-700 transition-all;
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 0.5rem;
            margin-top: 2rem;
        }
        .pagination a, .pagination span {
            @apply px-4 py-2 rounded-lg text-sm font-medium transition-all;
        }
        .pagination a {
            @apply bg-white border border-gray-300 text-gray-700 hover:bg-amber-50 hover:border-amber-400;
        }
        .pagination a.active {
            @apply bg-gradient-to-r from-amber-500 to-amber-600 text-white border-amber-600;
        }
        .pagination a.disabled {
            @apply bg-gray-100 text-gray-400 cursor-not-allowed border-gray-200;
        }

        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .top-nav .right-nav { gap: 0.5rem; }
            .btn-send-mail { font-size: 0.875rem; padding: 0.5rem 1rem; }
            .pagination { flex-wrap: wrap; }
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40 backdrop-blur-md bg-white/10">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-xs mx-4">
            <input type="text" placeholder="Search messages..." class="search-input w-full p-3 border border-gray-300 rounded-xl bg-white/20 backdrop-blur text-white placeholder-gray-300 focus:outline-none focus:ring-2 focus:ring-amber-400">
        </div>
        <div class="right-nav flex items-center gap-4">
            <!-- Send Mail Button -->
            <a href="send_mail.php" class="btn-send-mail" title="Send New Email">
                Send Mail
            </a>

            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-amber-500 cursor-pointer transition-all"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-amber-500 cursor-pointer transition-all"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" alt="Profile" class="w-10 h-10 rounded-full ring-2 ring-amber-400">
                <span class="text-white font-medium">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-amber-500 cursor-pointer transition-all"></i>
        </div>
    </nav>

    <!-- Content -->
    <div class="content p-6 min-h-screen">
        <div class="max-w-7xl mx-auto my-8">
            <div class="table-container">
                <div class="p-6 border-b border-gray-200 bg-gradient-to-r from-amber-50 to-yellow-50">
                    <h2 class="text-3xl font-bold text-gray-800 flex items-center gap-3">
                        Contact Messages
                    </h2>
                    <p class="text-gray-600 mt-1">Showing <?php echo count($contacts); ?> of <?php echo $total_contacts; ?> messages</p>
                </div>

                <!-- Success -->
                <?php if ($success): ?>
                    <div class="mx-6 mt-6 p-4 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl flex items-center gap-2">
                        <i class="fas fa-check-circle"></i>
                        <?php echo htmlspecialchars($success); ?>
                    </div>
                <?php endif; ?>

                <!-- Errors -->
                <?php if (!empty($errors)): ?>
                    <div class="mx-6 mt-6 p-4 bg-rose-50 border border-rose-200 text-rose-700 rounded-xl">
                        <ul class="list-disc list-inside">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <!-- Table -->
                <div class="overflow-x-auto">
                    <table class="min-w-full">
                        <thead>
                            <tr class="table-header">
                                <th class="px-6 py-4">ID</th>
                                <th class="px-6 py-4">Name</th>
                                <th class="px-6 py-4">Email</th>
                                <th class="px-6 py-4">Subject</th>
                                <th class="px-6 py-4">Message</th>
                                <th class="px-6 py-4">Date</th>
                                <th class="px-6 py-4">Status</th>
                                <th class="px-6 py-4 text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($contacts)): ?>
                                <tr>
                                    <td colspan="8" class="empty-state">
                                        <i class="fas fa-envelope"></i>
                                        <h3 class="text-xl font-semibold text-gray-500 mt-3">No messages yet</h3>
                                        <p class="mt-2">Messages from contact form will appear here.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($contacts as $contact): ?>
                                    <tr class="table-row">
                                        <td class="px-6 py-4 font-mono text-sm">#<?php echo $contact['id']; ?></td>
                                        <td class="px-6 py-4 font-medium text-gray-800">
                                            <?php echo htmlspecialchars($contact['name']); ?>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-600">
                                            <a href="mailto:<?php echo htmlspecialchars($contact['email']); ?>" class="hover:text-amber-600">
                                                <?php echo htmlspecialchars($contact['email']); ?>
                                            </a>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-700">
                                            <?php echo htmlspecialchars(substr($contact['subject'], 0, 40)) . (strlen($contact['subject']) > 40 ? '...' : ''); ?>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-600 max-w-xs">
                                            <div class="truncate">
                                                <?php echo htmlspecialchars(substr($contact['message'], 0, 60)) . (strlen($contact['message']) > 60 ? '...' : ''); ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-600">
                                            <?php echo date('M j, Y', strtotime($contact['created_at'])); ?>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="badge badge-<?php echo $contact['status']; ?>">
                                                <i class="fas fa-circle text-[8px] mr-1"></i>
                                                <?php echo ucfirst($contact['status']); ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="flex gap-2 justify-center">
                                                <!-- REPLY -->
                                                <a href="reply_contact.php?id=<?php echo $contact['id']; ?>"
                                                   class="action-btn btn-reply"
                                                   title="Reply via Email">
                                                    Reply
                                                </a>

                                                <!-- Mark as Read -->
                                                <?php if ($contact['status'] === 'unread'): ?>
                                                    <form method="POST" style="display:inline;">
                                                        <input type="hidden" name="contact_id" value="<?php echo $contact['id']; ?>">
                                                        <input type="hidden" name="mark_read" value="1">
                                                        <button type="submit" class="action-btn btn-read" title="Mark as Read">
                                                            Read
                                                        </button>
                                                    </form>
                                                <?php endif; ?>

                                                <!-- Delete -->
                                                <form method="POST" onsubmit="return confirm('Delete this message permanently?');" style="display:inline;">
                                                    <input type="hidden" name="contact_id" value="<?php echo $contact['id']; ?>">
                                                    <input type="hidden" name="delete_contact" value="1">
                                                    <button type="submit" class="action-btn btn-delete04" title="Delete">
                                                        Delete
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <!-- Previous -->
                        <?php if ($page > 1): ?>
                            <a href="?page=<?php echo $page - 1; ?>">Previous</a>
                        <?php else: ?>
                            <span class="disabled">Previous</span>
                        <?php endif; ?>

                        <!-- Page Numbers -->
                        <?php
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        if ($start > 1) {
                            echo '<a href="?page=1">1</a> <span>...</span> ';
                        }
                        for ($i = $start; $i <= $end; $i++): ?>
                            <a href="?page=<?php echo $i; ?>" class="<?php echo $i == $page ? 'active' : ''; ?>">
                                <?php echo $i; ?>
                            </a>
                        <?php endfor;
                        if ($end < $total_pages) {
                            echo ' <span>...</span> <a href="?page=' . $total_pages . '">' . $total_pages . '</a>';
                        }
                        ?>

                        <!-- Next -->
                        <?php if ($page < $total_pages): ?>
                            <a href="?page=<?php echo $page + 1; ?>">Next</a>
                        <?php else: ?>
                            <span class="disabled">Next</span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php include "include/footer.php"; ?>
    <?php $conn->close(); ?>
</body>
</html>