<?php
require_once 'config.php';
require_admin();

$message = $_GET['msg'] ?? '';
$searchQuery = $_GET['search'] ?? '';
$newPassword = null;

// --- Handle Password Reset ---
if (isset($_POST['reset_password'])) {
    $studentId = (int)$_POST['student_id'];
    $newPassword = generate_random_password(8); // Generate random password
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

    try {
        // 1. Update password and store plain text version in 'new_password' for temporary display
        $stmt = $pdo->prepare("UPDATE users SET password = ?, new_password = ? WHERE id = ? AND role = 'student'");
        $stmt->execute([$hashedPassword, $newPassword, $studentId]);
        $message = 'Password reset successful.';
    } catch (PDOException $e) {
        $message = 'Error resetting password: ' . $e->getMessage();
    }
}

// --- Handle Student Removal ---
if (isset($_POST['remove_student'])) {
    $studentId = (int)$_POST['student_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'student'");
        $stmt->execute([$studentId]);
        $message = 'Student successfully removed.';
    } catch (PDOException $e) {
        $message = 'Error removing student: ' . $e->getMessage();
    }
}

// --- Fetch Students (with optional search) ---
// FIX: Changed 'name' to 'first_name', 'last_name' and used CONCAT for display/search logic
$sql = "SELECT id, first_name, last_name, email, a_l_year, new_password FROM users WHERE role = 'student'";
$params = [];

if (!empty($searchQuery)) {
    // Modify search to look in first_name, last_name, or email
    $sql .= " AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ?)";
    $searchParam = "%" . $searchQuery . "%";
    $params = [$searchParam, $searchParam, $searchParam];
}
$sql .= " ORDER BY id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$students = $stmt->fetchAll();

require_once 'layouts.php';
render_header('User Management');
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('Student Management');
?>

<div class="space-y-8 p-4 md:p-8">
    <?php if ($message): ?>
        <!-- Animated Success/Error Message -->
        <div class="message-alert <?php echo strpos($message, 'Error') === 0 ? 'bg-red-100 border-red-500 text-red-700' : 'bg-indigo-100 border-indigo-500 text-indigo-700'; ?> border-l-4 p-4 rounded-xl shadow-md transition duration-500 ease-in-out transform hover:scale-[1.01]" role="alert">
            <div class="flex items-center">
                <i class="fa-solid <?php echo strpos($message, 'Error') === 0 ? 'fa-circle-xmark' : 'fa-circle-check'; ?> text-2xl mr-3"></i>
                <span class="font-medium"><?php echo htmlspecialchars($message); ?></span>
            </div>
        </div>
    <?php endif; ?>

    <!-- Search Bar Card -->
    <div class="bg-white p-6 rounded-2xl shadow-xl border border-gray-100 transition duration-300 hover:shadow-2xl">
        <form method="GET" action="usermanage.php" class="flex flex-col sm:flex-row w-full space-y-4 sm:space-y-0 sm:space-x-4">
            <div class="relative flex-grow">
                <i class="fa-solid fa-user-graduate absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <input type="text" name="search" placeholder="Search students by name or email..." value="<?php echo htmlspecialchars($searchQuery); ?>"
                       class="w-full pl-12 pr-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-indigo-500 focus:border-indigo-500 transition duration-200 shadow-inner">
            </div>
            
            <button type="submit" class="w-full sm:w-auto px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 font-semibold shadow-lg hover:shadow-xl transform hover:scale-[1.05] transition duration-300 ease-out flex items-center justify-center space-x-2">
                <i class="fa-solid fa-magnifying-glass"></i>
                <span>Search</span>
            </button>
            <?php if ($searchQuery): ?>
                <a href="usermanage.php" class="w-full sm:w-auto px-6 py-3 bg-gray-200 text-gray-800 rounded-xl hover:bg-gray-300 font-semibold shadow-md transform hover:scale-[1.05] transition duration-300 ease-out flex items-center justify-center">
                    Clear
                </a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Students Table Section -->
    <h2 class="text-3xl font-extrabold text-gray-900 border-b pb-4 mb-4">Registered Students <span class="text-indigo-600">(<?php echo count($students); ?>)</span></h2>
    
    <div class="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-4 text-left text-sm font-bold text-gray-600 uppercase tracking-wider">ID</th>
                        <th class="px-6 py-4 text-left text-sm font-bold text-gray-600 uppercase tracking-wider">Name</th>
                        <th class="px-6 py-4 text-left text-sm font-bold text-gray-600 uppercase tracking-wider">Email</th>
                        <th class="px-6 py-4 text-left text-sm font-bold text-gray-600 uppercase tracking-wider">A/L Year</th>
                        <th class="px-6 py-4 text-left text-sm font-bold text-gray-600 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-100">
                    <?php if ($students): ?>
                        <?php foreach ($students as $student): ?>
                            <?php
                                // Combine first and last name for display
                                $fullName = htmlspecialchars($student['first_name'] . ' ' . ($student['last_name'] ?? ''));
                            ?>
                            <tr class="student-row hover:bg-indigo-50/50 transition duration-150 ease-in-out">
                                <td class="px-6 py-4 whitespace-nowrap text-base font-semibold text-gray-900">CK<?php echo htmlspecialchars($student['id'] + 100000); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-base text-gray-800"><?php echo $fullName; ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600"><?php echo htmlspecialchars($student['email']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600"><?php echo htmlspecialchars($student['a_l_year'] ?? 'N/A'); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <form method="POST" action="usermanage.php" class="inline-block" onsubmit="return confirm('Are you sure you want to remove this student? This action cannot be undone.');">
                                        <input type="hidden" name="student_id" value="<?php echo $student['id']; ?>">
                                        <button type="submit" name="remove_student" class="action-btn text-red-600 hover:text-red-800 font-medium mr-4 transition duration-150 hover:underline">
                                            <i class="fa-solid fa-trash-can"></i> Remove
                                        </button>
                                    </form>
                                    <button onclick="openPasswordResetModal(<?php echo $student['id']; ?>, '<?php echo htmlspecialchars(addslashes($fullName)); ?>')" class="action-btn text-indigo-600 hover:text-indigo-800 font-medium transition duration-150 hover:underline">
                                        <i class="fa-solid fa-arrows-rotate"></i> Reset Password
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="px-6 py-8 text-center text-lg font-medium text-gray-500 bg-gray-50">
                            <i class="fa-solid fa-triangle-exclamation text-xl mr-2 text-yellow-500"></i> No students found matching the criteria.
                        </td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Password Reset Confirmation Modal -->
<div id="password-reset-modal" class="fixed inset-0 bg-gray-900 bg-opacity-70 hidden items-center justify-center p-4 z-50 transition-opacity duration-300">
    <div class="bg-white rounded-3xl shadow-3xl max-w-sm w-full p-8 text-center transform scale-95 transition-transform duration-300" id="reset-modal-content">
        <i class="fa-solid fa-shield-halved text-6xl text-indigo-500 mb-6 animate-pulse-slow"></i>
        <h3 class="text-2xl font-extrabold text-gray-900 mb-2">Confirm Secure Reset</h3>
        <p class="text-gray-600 mb-8 leading-relaxed">You are about to reset the password for student <span id="student-name-reset" class="font-bold text-indigo-700"></span>. A new, temporary password will be generated and displayed.</p>
        <form method="POST" action="usermanage.php" class="flex flex-col space-y-4">
            <input type="hidden" name="student_id" id="reset-student-id">
            <button type="submit" name="reset_password" class="w-full px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 font-semibold shadow-lg hover:shadow-xl transform hover:scale-105 transition duration-300">
                <i class="fa-solid fa-key mr-2"></i> Reset & Display Password
            </button>
            <button type="button" onclick="closeModal('password-reset-modal')" class="w-full px-6 py-3 bg-gray-200 text-gray-800 rounded-xl hover:bg-gray-300 font-semibold transition duration-300">
                Cancel
            </button>
        </form>
    </div>
</div>

<!-- New Password Display Modal (Pop-up) -->
<div id="new-password-modal" class="fixed inset-0 bg-gray-900 bg-opacity-70 hidden items-center justify-center p-4 z-50 transition-opacity duration-300">
    <div class="bg-white rounded-3xl shadow-3xl max-w-md w-full p-10 text-center transform scale-95 transition-transform duration-300" id="password-modal-content">
        <i class="fa-solid fa-lock-open text-6xl text-green-500 mb-6 transition duration-500 ease-in-out"></i>
        <h3 class="text-3xl font-extrabold text-gray-900 mb-3">Password Successfully Updated!</h3>
        <p class="text-gray-600 mb-6 font-medium">Please securely share this **temporary** new password with the student:</p>
        
        <!-- Animated Password Display Box -->
        <div class="relative bg-gray-50 p-5 rounded-xl border-2 border-indigo-200 border-dashed mb-8 group cursor-pointer transition duration-300 hover:bg-indigo-50" 
             onclick="copyPassword()">
            <code id="new-password-display" class="text-3xl font-mono text-indigo-700 font-bold select-all break-all transition duration-300"></code>
            <button id="copy-btn" class="absolute right-3 top-3 p-2 text-gray-400 hover:text-indigo-600 opacity-0 group-hover:opacity-100 transition duration-300">
                <i class="fa-solid fa-copy"></i>
            </button>
        </div>
        
        <button onclick="closeModal('new-password-modal');" class="px-8 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 font-semibold transition duration-300 shadow-lg hover:shadow-xl transform hover:scale-[1.03]">
            <i class="fa-solid fa-thumbs-up mr-2"></i> Done
        </button>
        <p id="copy-message" class="text-sm text-green-600 mt-3 font-medium hidden">Copied!</p>
    </div>
</div>

<script>
    // Utility function to open a modal
    function openModal(modalId) {
        const modal = document.getElementById(modalId);
        modal.classList.remove('hidden');
        modal.classList.add('flex', 'opacity-0');
        // A little delay for the fade-in animation
        setTimeout(() => {
            modal.classList.remove('opacity-0');
        }, 10);
    }

    // Utility function to close a modal
    function closeModal(modalId) {
        const modal = document.getElementById(modalId);
        modal.classList.add('opacity-0');
        // Wait for the fade-out transition to finish before hiding
        setTimeout(() => {
            modal.classList.remove('flex');
            modal.classList.add('hidden');
        }, 300);
    }

    // Function to handle opening the password reset confirmation
    function openPasswordResetModal(studentId, studentName) {
        document.getElementById('reset-student-id').value = studentId;
        document.getElementById('student-name-reset').textContent = studentName;
        openModal('password-reset-modal');
    }

    // Function to copy the new password to clipboard
    function copyPassword() {
        const passwordText = document.getElementById('new-password-display').textContent;
        // Use document.execCommand('copy') for better compatibility in iframe environments
        const tempInput = document.createElement('textarea');
        tempInput.value = passwordText;
        document.body.appendChild(tempInput);
        tempInput.select();
        document.execCommand('copy');
        document.body.removeChild(tempInput);

        // Show confirmation message
        const copyMsg = document.getElementById('copy-message');
        copyMsg.classList.remove('hidden');
        setTimeout(() => {
            copyMsg.classList.add('hidden');
        }, 1500);
    }


    <?php if ($newPassword): // Automatically open the display modal if a password was reset ?>
        document.addEventListener('DOMContentLoaded', () => {
            const newPassDisplay = document.getElementById('new-password-display');
            newPassDisplay.textContent = '<?php echo htmlspecialchars($newPassword); ?>';
            openModal('new-password-modal');
        });
    <?php endif; ?>
</script>

<?php render_main_content_end(); ?>