<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || !$user->isTeacher()) {
    header("Location: ../index.php");
    exit;
}

$message = '';
$error = '';
$tab = isset($_GET['tab']) ? $_GET['tab'] : 'students';

// --- Student Logic ---

// Handle CSV Upload
if (isset($_POST['upload_csv'])) {
    if (isset($_FILES['student_csv']) && $_FILES['student_csv']['error'] == 0) {
        $file = $_FILES['student_csv']['tmp_name'];
        $class_id = $_POST['class_id'];
        
        if (($handle = fopen($file, "r")) !== FALSE) {
            $row = 0;
            $success_count = 0;
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                // Skip header row if exists
                if ($row == 0 && strtolower($data[0]) == 'username') {
                    $row++;
                    continue;
                }
                
                $username = trim($data[0]);
                $password = trim($data[1]);
                $full_name = isset($data[2]) ? trim($data[2]) : null;
                
                if (!empty($username) && !empty($password)) {
                    $hashed = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
                    $stmt->execute([$username]);
                    if ($stmt->fetchColumn() == 0) {
                        $stmt = $pdo->prepare("INSERT INTO users (username, password, role, class_id, full_name) VALUES (?, ?, 'student', ?, ?)");
                        if ($stmt->execute([$username, $hashed, $class_id, $full_name])) {
                            $success_count++;
                        }
                    }
                }
                $row++;
            }
            fclose($handle);
            $message = "Imported $success_count students successfully.";
        }
    } else {
        $error = "Please upload a valid CSV file.";
    }
    $tab = 'students';
}

// Handle Single Registration
if (isset($_POST['register_student'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $class_id = $_POST['class_id'];
    $full_name = isset($_POST['full_name']) ? trim($_POST['full_name']) : null;
    
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
    $stmt->execute([$username]);
    if ($stmt->fetchColumn() > 0) {
        $error = "Username already exists.";
    } else {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (username, password, role, class_id, full_name) VALUES (?, ?, 'student', ?, ?)");
        if ($stmt->execute([$username, $hashed, $class_id, $full_name])) {
            $message = "Student registered successfully.";
        } else {
            $error = "Registration failed.";
        }
    }
    $tab = 'students';
}

// Update Student
if (isset($_POST['update_user'])) {
    $uid = (int)$_POST['user_id'];
    $username = trim($_POST['username']);
    $full_name = isset($_POST['full_name']) ? trim($_POST['full_name']) : null;
    $class_id = $_POST['class_id'];
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    
    if ($uid && !empty($username) && !empty($class_id)) {
        if (!empty($password)) {
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, class_id = ?, password = ? WHERE user_id = ?");
            $ok = $stmt->execute([$username, $full_name, $class_id, $hashed, $uid]);
        } else {
            $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, class_id = ? WHERE user_id = ?");
            $ok = $stmt->execute([$username, $full_name, $class_id, $uid]);
        }
        if ($ok) $message = "Student updated.";
        else $error = "Failed to update student.";
    } else {
        $error = "Please fill required fields.";
    }
    $tab = 'students';
}

// Generate PIN
if (isset($_POST['generate_pin'])) {
    $student_id = $_POST['user_id'];
    $pin = $user->generateAccessPin($student_id);
    if ($pin) $message = "PIN: $pin";
    $tab = 'students';
}

// Delete User (Student or Staff)
if (isset($_POST['delete_user'])) {
    $pdo->prepare("DELETE FROM users WHERE user_id = ?")->execute([$_POST['user_id']]);
    $message = "User deleted.";
}

// --- Staff Logic ---

if (isset($_POST['add_staff'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $full_name = trim($_POST['full_name']);
    $role = $_POST['role']; // teacher or admin
    $perms = isset($_POST['permissions']) ? $_POST['permissions'] : [];
    
    // If Admin selected, maybe force all perms or leave as is? 
    // Usually admin role implies all, but we store permissions too for flexibility.
    
    $result = $user->register($username, $password, $role, $perms);
    if ($result === true) {
        // Update full name as register only takes 4 args
        // We need to fetch ID and update full_name or modify register. 
        // Modifying register is better but let's do update for now to avoid breaking other calls if any.
        // Actually I updated register to take permissions. I should update it to take full_name too?
        // Let's just update full_name separately.
        $stmt = $pdo->prepare("UPDATE users SET full_name = ? WHERE username = ?");
        $stmt->execute([$full_name, $username]);
        $message = "Staff added successfully.";
    } else {
        $error = $result;
    }
    $tab = 'staff';
}

if (isset($_POST['update_staff'])) {
    $uid = $_POST['user_id'];
    $username = trim($_POST['username']);
    $full_name = trim($_POST['full_name']);
    $role = $_POST['role'];
    $perms = isset($_POST['permissions']) ? $_POST['permissions'] : [];
    $password = trim($_POST['password']);
    
    $perms_json = json_encode($perms);
    
    if (!empty($password)) {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, role = ?, permissions = ?, password = ? WHERE user_id = ?");
        $stmt->execute([$username, $full_name, $role, $perms_json, $hashed, $uid]);
    } else {
        $stmt = $pdo->prepare("UPDATE users SET username = ?, full_name = ?, role = ?, permissions = ? WHERE user_id = ?");
        $stmt->execute([$username, $full_name, $role, $perms_json, $uid]);
    }
    $message = "Staff updated successfully.";
    $tab = 'staff';
}

// Fetch Data
$classes = $pdo->query("SELECT * FROM classes")->fetchAll();
$students = $pdo->query("SELECT u.*, c.class_name FROM users u LEFT JOIN classes c ON u.class_id = c.class_id WHERE u.role = 'student'")->fetchAll();
$staff = $pdo->query("SELECT * FROM users WHERE role IN ('admin', 'teacher') ORDER BY role, username")->fetchAll();

// Helper for perms
$all_perms = [
    'manage_students' => 'Manage Students',
    'manage_teachers' => 'Manage Staff',
    'manage_questions' => 'Manage Questions',
    'manage_exams' => 'Manage Exams',
    'manage_results' => 'View/Print Results',
    'manage_settings' => 'System Settings'
];

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
    <link rel="stylesheet" href="../assets/css/admin.css">
    <style>
        .tabs { display: flex; border-bottom: 2px solid #ddd; margin-bottom: 20px; }
        .tab { padding: 10px 20px; cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -2px; }
        .tab.active { border-bottom-color: var(--primary-color, #2563eb); color: var(--primary-color, #2563eb); font-weight: bold; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .perm-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; margin-top: 10px; }
    </style>
</head>
<body>
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="content">
        <?php include '../includes/page_header.php'; ?>
        <h1>User Management</h1>
        <?php if ($message): ?> <div class="alert alert-success"><?php echo $message; ?></div> <?php endif; ?>
        <?php if ($error): ?> <div class="alert alert-danger"><?php echo $error; ?></div> <?php endif; ?>

        <div class="tabs">
            <div class="tab <?php echo $tab=='students'?'active':''; ?>" onclick="switchTab('students')">Students</div>
            <div class="tab <?php echo $tab=='staff'?'active':''; ?>" onclick="switchTab('staff')">Staff (Teachers & Admins)</div>
        </div>

        <!-- STUDENTS TAB -->
        <div id="students" class="tab-content <?php echo $tab=='students'?'active':''; ?>">
            <div class="card">
                <h3>Add Single Student</h3>
                <form method="POST">
                    <input type="text" name="username" placeholder="Username" required>
                    <input type="text" name="password" placeholder="Password" required>
                    <input type="text" name="full_name" placeholder="Full Name (optional)">
                    <select name="class_id" required>
                        <option value="">Select Class</option>
                        <?php foreach ($classes as $c): ?>
                            <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" name="register_student" class="btn">Register</button>
                </form>
            </div>

            <div class="card">
                <h3>Bulk Upload Students (CSV)</h3>
                <p>Format: <code>Username, Password, FullName</code></p>
                <form method="POST" enctype="multipart/form-data">
                    <select name="class_id" required>
                        <option value="">Select Class for these students</option>
                        <?php foreach ($classes as $c): ?>
                            <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input type="file" name="student_csv" accept=".csv" required>
                    <button type="submit" name="upload_csv" class="btn">Upload CSV</button>
                </form>
            </div>

            <h3>Registered Students</h3>
            <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Name</th>
                        <th>Class</th>
                        <th>PIN</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students as $s): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($s['username']); ?></td>
                        <td><?php echo htmlspecialchars($s['full_name'] ?: ''); ?></td>
                        <td><?php echo htmlspecialchars($s['class_name'] ?? 'N/A'); ?></td>
                        <td><?php echo $s['access_pin'] ?: 'None'; ?></td>
                        <td>
                            <button type="button" class="btn" onclick="openEditStudentModal(<?php echo $s['user_id']; ?>)" data-uid="<?php echo $s['user_id']; ?>" data-student='<?php echo json_encode(['user_id'=>$s['user_id'],'username'=>$s['username'],'full_name'=>$s['full_name'],'class_id'=>$s['class_id']]); ?>'>Edit</button>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="user_id" value="<?php echo $s['user_id']; ?>">
                                <button type="submit" name="generate_pin" class="btn">PIN</button>
                            </form>
                            <a class="btn" target="_blank" href="export_pdf.php?type=timetable&user_id=<?php echo $s['user_id']; ?>">Timetable PDF</a>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?');">
                                <input type="hidden" name="user_id" value="<?php echo $s['user_id']; ?>">
                                <button type="submit" name="delete_user" class="btn btn-danger">Delete</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        </div>

        <!-- STAFF TAB -->
        <div id="staff" class="tab-content <?php echo $tab=='staff'?'active':''; ?>">
            <div class="card">
                <h3>Add Staff Member</h3>
                <form method="POST">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Username</label>
                            <input type="text" name="username" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label>Password</label>
                            <input type="text" name="password" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label>Full Name / Title</label>
                            <input type="text" name="full_name" class="form-control" placeholder="e.g. Mr. John Doe">
                        </div>
                        <div class="form-group">
                            <label>Role</label>
                            <select name="role" class="form-control" required onchange="togglePerms(this)">
                                <option value="teacher">Teacher (Selected Privileges)</option>
                                <option value="admin">Admin (Full Access)</option>
                            </select>
                        </div>
                    </div>
                    
                    <div id="perm-section">
                        <h4>Privileges</h4>
                        <div class="perm-grid">
                            <?php foreach ($all_perms as $key => $label): ?>
                                <label><input type="checkbox" name="permissions[]" value="<?php echo $key; ?>"> <?php echo $label; ?></label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <button type="submit" name="add_staff" class="btn btn-primary" style="margin-top:15px;">Add Staff</button>
                </form>
            </div>

            <h3>Staff List</h3>
            <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Name</th>
                        <th>Role</th>
                        <th>Permissions</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($staff as $s): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($s['username']); ?></td>
                        <td><?php echo htmlspecialchars($s['full_name'] ?: ''); ?></td>
                        <td><?php echo ucfirst($s['role']); ?></td>
                        <td>
                            <?php 
                                if ($s['role'] === 'admin') echo 'Full Access';
                                else {
                                    $p = json_decode($s['permissions'] ?? '[]', true);
                                    if (empty($p)) echo 'None';
                                    else {
                                        $labels = [];
                                        foreach ($p as $k) $labels[] = $all_perms[$k] ?? $k;
                                        echo implode(', ', $labels);
                                    }
                                }
                            ?>
                        </td>
                        <td>
                            <?php if ($s['user_id'] != $_SESSION['user_id']): ?>
                                <button type="button" class="btn" onclick="openEditStaffModal(<?php echo htmlspecialchars(json_encode($s)); ?>)">Edit</button>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete Staff?');">
                                    <input type="hidden" name="user_id" value="<?php echo $s['user_id']; ?>">
                                    <button type="submit" name="delete_user" class="btn btn-danger">Delete</button>
                                </form>
                            <?php else: ?>
                                <span class="badge badge-success">You</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        </div>

    </div>

    <!-- Edit Student Modal -->
    <div class="modal-backdrop" id="editStudentBackdrop">
        <div class="modal">
            <header>Edit Student</header>
            <form method="POST">
                <input type="hidden" name="user_id" id="edit_student_id">
                <div class="form-grid">
                    <div class="form-group"><label>Username</label><input type="text" name="username" id="edit_student_username" class="form-control" required></div>
                    <div class="form-group"><label>Full Name</label><input type="text" name="full_name" id="edit_student_fullname" class="form-control"></div>
                    <div class="form-group">
                        <label>Class</label>
                        <select name="class_id" id="edit_student_class" class="form-control" required>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group"><label>New Password</label><input type="password" name="password" class="form-control"></div>
                </div>
                <div class="actions">
                    <button type="button" class="btn" onclick="closeModal('editStudentBackdrop')">Cancel</button>
                    <button type="submit" name="update_user" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Staff Modal -->
    <div class="modal-backdrop" id="editStaffBackdrop">
        <div class="modal">
            <header>Edit Staff</header>
            <form method="POST">
                <input type="hidden" name="user_id" id="edit_staff_id">
                <div class="form-grid">
                    <div class="form-group"><label>Username</label><input type="text" name="username" id="edit_staff_username" class="form-control" required></div>
                    <div class="form-group"><label>Full Name</label><input type="text" name="full_name" id="edit_staff_fullname" class="form-control"></div>
                    <div class="form-group">
                        <label>Role</label>
                        <select name="role" id="edit_staff_role" class="form-control" required onchange="toggleEditPerms(this)">
                            <option value="teacher">Teacher</option>
                            <option value="admin">Admin</option>
                        </select>
                    </div>
                    <div class="form-group"><label>New Password</label><input type="password" name="password" class="form-control"></div>
                </div>
                <div id="edit_perm_section">
                    <h4>Privileges</h4>
                    <div class="perm-grid">
                        <?php foreach ($all_perms as $key => $label): ?>
                            <label><input type="checkbox" name="permissions[]" value="<?php echo $key; ?>" class="edit-perm-check"> <?php echo $label; ?></label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="actions">
                    <button type="button" class="btn" onclick="closeModal('editStaffBackdrop')">Cancel</button>
                    <button type="submit" name="update_staff" class="btn btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function switchTab(tabId) {
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            document.querySelector('.tab[onclick="switchTab(\'' + tabId + '\')"]').classList.add('active');
            document.getElementById(tabId).classList.add('active');
            const url = new URL(window.location);
            url.searchParams.set('tab', tabId);
            window.history.pushState({}, '', url);
        }

        function togglePerms(select) {
            document.getElementById('perm-section').style.display = select.value === 'admin' ? 'none' : 'block';
        }
        function toggleEditPerms(select) {
            document.getElementById('edit_perm_section').style.display = select.value === 'admin' ? 'none' : 'block';
        }

        function openEditStudentModal(id) {
            const btn = document.querySelector('button[data-uid="'+id+'"]');
            const data = JSON.parse(btn.getAttribute('data-student'));
            document.getElementById('edit_student_id').value = data.user_id;
            document.getElementById('edit_student_username').value = data.username;
            document.getElementById('edit_student_fullname').value = data.full_name;
            document.getElementById('edit_student_class').value = data.class_id;
            document.getElementById('editStudentBackdrop').classList.add('show');
        }

        function openEditStaffModal(data) {
            document.getElementById('edit_staff_id').value = data.user_id;
            document.getElementById('edit_staff_username').value = data.username;
            document.getElementById('edit_staff_fullname').value = data.full_name;
            document.getElementById('edit_staff_role').value = data.role;
            
            // Handle Perms
            const perms = JSON.parse(data.permissions || '[]');
            document.querySelectorAll('.edit-perm-check').forEach(cb => {
                cb.checked = perms.includes(cb.value);
            });
            
            toggleEditPerms(document.getElementById('edit_staff_role'));
            document.getElementById('editStaffBackdrop').classList.add('show');
        }

        function closeModal(id) {
            document.getElementById(id).classList.remove('show');
        }
    </script>
</body>
</html>
