<?php
include "include/db.php"; // Include database connection
include "include/header.php";

// Initialize variables
$errors = [];
$success = '';
$per_page = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $per_page;

// Handle Filter Parameters
$filters = [
    'name' => trim($_GET['name'] ?? ''),
    'phone' => trim($_GET['phone'] ?? ''),
    'role' => trim($_GET['role'] ?? ''),
    'status' => trim($_GET['status'] ?? '')
];

// Build Query with Filters
$query = "SELECT SQL_CALC_FOUND_ROWS id, name, phone, role, profile_pic, bio, status, created_at
          FROM users
          WHERE 1=1";
$params = [];
$types = '';

if ($filters['name']) {
    $query .= " AND name LIKE ?";
    $params[] = '%' . $filters['name'] . '%';
    $types .= 's';
}
if ($filters['phone']) {
    $query .= " AND phone LIKE ?";
    $params[] = '%' . $filters['phone'] . '%';
    $types .= 's';
}
if ($filters['role']) {
    $query .= " AND role = ?";
    $params[] = $filters['role'];
    $types .= 's';
}
if ($filters['status']) {
    $query .= " AND status = ?";
    $params[] = $filters['status'];
    $types .= 's';
}

$query .= " ORDER BY created_at DESC LIMIT ?, ?";
$params[] = $offset;
$params[] = $per_page;
$types .= 'ii';

// Execute Query
$stmt = $conn->prepare($query);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$users = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get Total Rows for Pagination
$total_result = $conn->query("SELECT FOUND_ROWS() AS total");
$total_rows = $total_result->fetch_assoc()['total'];
$total_pages = ceil($total_rows / $per_page);

// Handle User Deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_user'])) {
    $user_id = trim($_POST['user_id'] ?? '');
    if (empty($user_id) || !is_numeric($user_id)) {
        $errors[] = "Invalid user ID.";
    } else {
        // Check if user exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            $errors[] = "User not found.";
        } else {
            // Delete user
            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt->bind_param("i", $user_id);
            if ($stmt->execute()) {
                $success = "User deleted successfully!";
            } else {
                $errors[] = "Failed to delete user: " . $conn->error;
            }
        }
        $stmt->close();
    }
}
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen">
    <style>
        /* Tailwind CSS CDN (embedded for top-class design) */
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');

        /* Custom styles for enhanced design */
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; }
        .content { transition: margin-left 0.3s ease; }
        .filter-section, .table-section, .modal-content { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .filter-section:hover, .table-section:hover, .modal-content:hover { transform: translateY(-5px); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        input, select { transition: all 0.2s ease; }
        input:focus, select:focus { ring: 2px solid #F59E0B; }
        .error { color: #DC2626; }
        .success { color: #10B981; font-size: 1.25rem; font-weight: bold; }
        table { width: 100%; border-collapse: separate; border-spacing: 0; }
        th, td { padding: 12px; text-align: left; }
        th { background: #1F2937; color: white; }
        tr:nth-child(even) { background: #F9FAFB; }
        tr:hover { background: #E5E7EB; }
        .pagination { display: flex; gap: 0.5rem; justify-content: center; margin-top: 1rem; }
        .pagination a, .pagination span { padding: 0.5rem 1rem; border: 1px solid #D1D5DB; border-radius: 0.375rem; text-decoration: none; color: #1F2937; }
        .pagination a:hover { background: #F59E0B; color: white; }
        .pagination .active { background: #1F2937; color: white; }
        .pagination .disabled { color: #9CA3AF; pointer-events: none; }
        .modal { transition: opacity 0.3s ease; }
        .modal-content { animation: slideIn 0.3s ease; background: #F9FAFB; border-left: 4px solid #F59E0B; }
        .modal-content img { border: 2px solid #F59E0B; }
        .status-active { color: #10B981; }
        .status-inactive { color: #DC2626; }
        @keyframes slideIn { from { transform: translateY(-20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
            table { font-size: 0.875rem; }
            .filter-section { flex-direction: column; }
            .modal-content { width: 90%; }
        }
        @media (min-width: 769px) {
            .content { margin-left: 250px; }
        }
    </style>

    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40">
        <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 students..." class="w-full p-2 border border-gray-300 rounded-md bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-yellow-500">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Notifications"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Messages"></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">
                <span class="text-white">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Toggle Menu"></i>
        </div>
    </nav>

    <!-- Filter Section -->
    <div class="filter-section bg-white p-6 rounded-lg shadow-md w-full my-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Filter Students</h2>
        <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label for="name" class="block text-sm font-medium text-gray-700">Name</label>
                <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($filters['name']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
            </div>
            <div>
                <label for="phone" class="block text-sm font-medium text-gray-700">Phone</label>
                <input type="text" id="phone" name="phone" value="<?php echo htmlspecialchars($filters['phone']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
            </div>
            <div>
                <label for="role" class="block text-sm font-medium text-gray-700">Role</label>
                <select id="role" name="role" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                    <option value="">All</option>
                    <option value="student" <?php echo $filters['role'] === 'student' ? 'selected' : ''; ?>>Student</option>
                    <option value="admin" <?php echo $filters['role'] === 'admin' ? 'selected' : ''; ?>>Admin</option>
                </select>
            </div>
            <div>
                <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                <select id="status" name="status" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                    <option value="">All</option>
                    <option value="active" <?php echo $filters['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo $filters['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                </select>
            </div>
            <div class="md:col-span-3 flex gap-4">
                <button type="submit" class="bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Apply Filters</button>
                <a href="student_list.php" class="bg-gray-500 text-white p-2 rounded-md hover:bg-gray-600 transition-colors">Clear Filters</a>
            </div>
        </form>
    </div>

    <!-- Students Table -->
    <div class="table-section bg-white p-6 rounded-lg shadow-md w-full my-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">All Students</h2>
        
        <!-- Success/Error Messages -->
        <?php if ($success): ?>
            <p class="success text-center mb-4"><?php echo htmlspecialchars($success); ?></p>
        <?php endif; ?>
        <?php if (!empty($errors)): ?>
            <ul class="error mb-4">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <!-- Users Table -->
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Role</th>
                        <th>Profile Pic</th>
                        <th>Bio</th>
                        <th>Status</th>
                        <th>Created At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($users)): ?>
                        <tr>
                            <td colspan="9" class="text-center py-4">No students found.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($users as $user): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($user['id']); ?></td>
                                <td><?php echo htmlspecialchars($user['name']); ?></td>
                                <td><?php echo htmlspecialchars($user['phone']); ?></td>
                                <td><?php echo htmlspecialchars($user['role']); ?></td>
                                <td>
                                    <?php if ($user['profile_pic']): ?>
                                        <img src="<?php echo htmlspecialchars($user['profile_pic']); ?>" alt="Profile Pic" class="w-10 h-10 rounded-full object-cover">
                                    <?php else: ?>
                                        <img src="https://via.placeholder.com/40" alt="No Pic" class="w-10 h-10 rounded-full">
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars(substr($user['bio'] ?? '', 0, 50)) . (strlen($user['bio'] ?? '') > 50 ? '...' : ''); ?></td>
                                <td class="status-<?php echo htmlspecialchars($user['status']); ?>">
                                    <?php echo htmlspecialchars($user['status']); ?>
                                </td>
                                <td><?php echo htmlspecialchars($user['created_at']); ?></td>
                                <td class="flex gap-2">
                                    <button onclick="openModal(<?php echo htmlspecialchars($user['id']); ?>)" class="bg-green-500 text-white px-3 py-1 rounded-md hover:bg-green-600 transition-colors">View</button>
                                    <a href="edit_student.php?id=<?php echo htmlspecialchars($user['id']); ?>" class="bg-blue-900 text-white px-3 py-1 rounded-md hover:bg-blue-800 transition-colors">Edit</a>
                                    <form method="POST" onsubmit="return confirm('Are you sure you want to delete this user?');">
                                        <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user['id']); ?>">
                                        <input type="hidden" name="delete_user" value="1">
                                        <button type="submit" class="bg-red-600 text-white px-3 py-1 rounded-md hover:bg-red-700 transition-colors">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php
                $query_params = $_GET;
                unset($query_params['page']);
                $query_string = http_build_query($query_params);
                $base_url = 'student_list.php' . ($query_string ? '?' . $query_string . '&' : '?');

                if ($page > 1) {
                    echo '<a href="' . $base_url . 'page=' . ($page - 1) . '">Previous</a>';
                } else {
                    echo '<span class="disabled">Previous</span>';
                }

                for ($i = 1; $i <= $total_pages; $i++) {
                    echo '<a href="' . $base_url . 'page=' . $i . '" class="' . ($i === $page ? 'active' : '') . '">' . $i . '</a>';
                }

                if ($page < $total_pages) {
                    echo '<a href="' . $base_url . 'page=' . ($page + 1) . '">Next</a>';
                } else {
                    echo '<span class="disabled">Next</span>';
                }
                ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Modal for Viewing User Details -->
    <div id="userModal" class="modal hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="modal-content bg-white p-8 rounded-lg max-w-lg w-full">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-semibold text-gray-900">User Profile</h2>
                <button onclick="closeModal()" class="text-gray-600 hover:text-gray-900">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div id="modalContent" class="space-y-4">
                <!-- Content will be populated via AJAX -->
            </div>
            <button onclick="closeModal()" class="mt-6 bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors w-full">Close</button>
        </div>
    </div>

    <!-- JavaScript for Modal -->
    <script>
        function openModal(userId) {
            fetch('student_list.php?get_user=' + userId)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                        return;
                    }
                    const modalContent = document.getElementById('modalContent');
                    modalContent.innerHTML = `
                        <div class="flex flex-col items-center">
                            <img src="${data.profile_pic || 'https://via.placeholder.com/100'}" alt="Profile Pic" class="w-24 h-24 rounded-full object-cover mb-4 border-2 border-yellow-500">
                            <h3 class="text-xl font-medium text-gray-900">${data.name}</h3>
                            <p class="text-sm text-gray-600">${data.role}</p>
                        </div>
                        <div class="border-t border-gray-200 mt-4 pt-4 space-y-3">
                            <p><span class="font-medium text-gray-700">ID:</span> ${data.id}</p>
                            <p><span class="font-medium text-gray-700">Phone:</span> ${data.phone}</p>
                            <p><span class="font-medium text-gray-700">Bio:</span> ${data.bio || 'None'}</p>
                            <p><span class="font-medium text-gray-700">Status:</span> <span class="status-${data.status}">${data.status}</span></p>
                            <p><span class="font-medium text-gray-700">Created At:</span> ${data.created_at}</p>
                        </div>
                    `;
                    document.getElementById('userModal').classList.remove('hidden');
                })
                .catch(error => alert('Error fetching user details: ' + error));
        }

        function closeModal() {
            document.getElementById('userModal').classList.add('hidden');
        }

        // Close modal when clicking outside
        document.getElementById('userModal').addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });

        // Handle AJAX request for user details
        <?php if (isset($_GET['get_user']) && is_numeric($_GET['get_user'])): ?>
            <?php
            $stmt = $conn->prepare("SELECT id, name, phone, role, profile_pic, bio, status, created_at FROM users WHERE id = ?");
            $stmt->bind_param("i", $_GET['get_user']);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows === 0) {
                echo "echo json_encode(['error' => 'User not found']);";
                exit;
            }
            $user = $result->fetch_assoc();
            echo "echo json_encode(" . json_encode($user) . ");";
            $stmt->close();
            exit;
            ?>
        <?php endif; ?>
    </script>
</div>

<?php
include "include/footer.php";
$conn->close(); // Close database connection
?>