<?php
// Filename: admin_teachers.php
require 'config.php';
requireLogin(); 

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
// Fetch fresh role from DB to be safe
$stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
$stmt->execute([$uid]);
$curr_user = $stmt->fetch();
$user_roles = explode(',', $curr_user['role'] ?? '');

$allowed_roles = ['admin', 'principal', 'assistant', 'assistant_hem'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

$msg = '';
$msg_type = '';

// --- FETCH SUBJECTS FROM DB (Integrated with admin_subjects.php) ---
// We fetch these to generate the checkboxes later
$all_subjects = $pdo->query("SELECT subject_name FROM subjects ORDER BY subject_name ASC")->fetchAll(PDO::FETCH_COLUMN);

// --- ACTIONS (ADD/EDIT/DELETE/IMPORT) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // ADD SINGLE
    if (isset($_POST['action']) && $_POST['action'] === 'add_single') {
        $ic = trim($_POST['ic_number']);
        $name = strtoupper(trim($_POST['full_name']));
        $phone = trim($_POST['phone_number']);
        $roles = isset($_POST['roles']) ? implode(',', $_POST['roles']) : 'teacher';
        
        // FIX: Handle Subjects as Array (from checkboxes)
        $sub_input = $_POST['subjects'] ?? [];
        $subjects = is_array($sub_input) ? implode(',', $sub_input) : trim($sub_input);
        
        $exclude = isset($_POST['exclude_relief']) ? 1 : 0;
        $max_weekly = intval($_POST['max_relief_weekly'] ?? 3);
        $rank = intval($_POST['position_rank'] ?? 0);
        $mobility = $_POST['mobility_status'] ?? 'fit';
        $preg = isset($_POST['is_pregnant']) ? 1 : 0;
        $telegram = trim($_POST['telegram_chat_id'] ?? '');

        if (empty($ic) || empty($name)) {
            $msg = "IC Number and Name are required."; $msg_type = "danger";
        } else {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$ic]);
            if ($stmt->fetch()) {
                $msg = "Error: User with IC $ic already exists."; $msg_type = "danger";
            } else {
                try {
                    $hashed_pass = password_hash($ic, PASSWORD_BCRYPT);
                    $sql = "INSERT INTO users (username, password, full_name, role, phone_number, subjects, exclude_relief, max_relief_weekly, position_rank, mobility_status, is_pregnant, telegram_chat_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    $insert = $pdo->prepare($sql);
                    $insert->execute([$ic, $hashed_pass, $name, $roles, $phone, $subjects, $exclude, $max_weekly, $rank, $mobility, $preg, $telegram]);
                    $msg = "User added successfully."; $msg_type = "success";
                } catch (PDOException $e) { $msg = "Database Error: " . $e->getMessage(); $msg_type = "danger"; }
            }
        }
    }

    // EDIT USER
    if (isset($_POST['action']) && $_POST['action'] === 'edit_user') {
        $target_uid = $_POST['user_id'];
        $name = strtoupper(trim($_POST['full_name']));
        $ic = trim($_POST['username']);
        $phone = trim($_POST['phone_number']);
        $roles = isset($_POST['roles']) ? implode(',', $_POST['roles']) : 'teacher';
        
        // FIX: Handle Subjects as Array (from checkboxes)
        $sub_input = $_POST['subjects'] ?? [];
        $subjects = is_array($sub_input) ? implode(',', $sub_input) : trim($sub_input);
        
        $max_weekly = intval($_POST['max_relief_weekly']);
        $exclude = isset($_POST['exclude_relief']) ? 1 : 0;
        $rank = intval($_POST['position_rank']);
        $mobility = $_POST['mobility_status'];
        $preg = isset($_POST['is_pregnant']) ? 1 : 0;
        $telegram = trim($_POST['telegram_chat_id']);
        
        if ($target_uid == $_SESSION['user_id'] && strpos($roles, 'admin') === false) {
            $msg = "You cannot remove your own Admin rights."; $msg_type = "danger";
        } else {
            try {
                $sql = "UPDATE users SET full_name=?, username=?, phone_number=?, role=?, subjects=?, max_relief_weekly=?, exclude_relief=?, position_rank=?, mobility_status=?, is_pregnant=?, telegram_chat_id=? WHERE id=?";
                $pdo->prepare($sql)->execute([$name, $ic, $phone, $roles, $subjects, $max_weekly, $exclude, $rank, $mobility, $preg, $telegram, $target_uid]);
                $msg = "User details updated."; $msg_type = "success";
            } catch (PDOException $e) { $msg = "Error: IC/Username likely duplicate."; $msg_type = "danger"; }
        }
    }

    // RESET PASSWORD
    if (isset($_POST['action']) && $_POST['action'] === 'reset_password') {
        $target_uid = $_POST['user_id'];
        $reset_type = $_POST['reset_type']; 
        if ($target_uid) {
            try {
                if ($reset_type === 'default') {
                    $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
                    $stmt->execute([$target_uid]);
                    $user = $stmt->fetch();
                    if ($user) {
                        $new_pass = $user['username'];
                        $hashed = password_hash($new_pass, PASSWORD_BCRYPT);
                        $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$hashed, $target_uid]);
                        $msg = "Password reset to IC Number (" . htmlspecialchars($new_pass) . ")."; $msg_type = "success";
                    }
                } elseif ($reset_type === 'manual' && !empty($_POST['new_password'])) {
                    $hashed = password_hash($_POST['new_password'], PASSWORD_BCRYPT);
                    $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$hashed, $target_uid]);
                    $msg = "Password updated manually."; $msg_type = "success";
                }
            } catch (Exception $e) { $msg = "Error updating password."; $msg_type = "danger"; }
        }
    }
}

// DELETE USER
if (isset($_GET['delete_id'])) {
    $del_id = $_GET['delete_id'];
    if ($del_id == $_SESSION['user_id']) { 
        $msg = "Cannot delete yourself."; $msg_type = "danger"; 
    } else { 
        try {
            $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$del_id]); 
            $msg = "User deleted."; $msg_type = "warning"; 
        } catch (PDOException $e) { $msg = "Cannot delete user: Active records exist."; $msg_type = "danger"; }
    }
}

// FETCH USERS
$search = $_GET['search'] ?? '';
$sql = "SELECT * FROM users WHERE full_name LIKE ? OR username LIKE ? ORDER BY FIELD(role, 'admin') DESC, full_name ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute(["%$search%", "%$search%"]);
$users = $stmt->fetchAll();

// --- AUTO-OPEN LOGIC ---
$auto_reset_id = $_GET['open_reset'] ?? null;
$auto_reset_name = '';
if($auto_reset_id) {
    foreach($users as $u) {
        if($u['id'] == $auto_reset_id) {
            $auto_reset_name = $u['full_name'];
            break;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Teachers</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    
    <style>
       :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; --text-dark: #1e293b; --text-gray: #64748b; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .user-item { background: white; border-radius: 16px; padding: 15px; margin-bottom: 10px; border: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; transition: transform 0.2s; }
        .user-item:active { transform: scale(0.99); background: #f8fafc; }
        .user-item.admin { border-left: 4px solid #f59e0b; }
        .avatar-box { width: 45px; height: 45px; border-radius: 14px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; margin-right: 15px; font-size: 1.4rem; background: #f1f5f9; color: #64748b; }
        .avatar-box.admin { background: #fff7ed; color: #ea580c; }
        .nav-pills .nav-link { border-radius: 50px; color: #64748b; font-weight: 700; padding: 8px 20px; background: #f1f5f9; margin-right: 5px; font-size: 0.85rem; }
        .nav-pills .nav-link.active { background: #8B5CF6; color: white; box-shadow: 0 4px 10px rgba(139, 92, 246, 0.3); }
        .cond-badge { font-size: 0.65rem; padding: 3px 8px; border-radius: 6px; margin-right: 4px; font-weight: 700; }
        .bg-role { background: #e0f2fe; color: #0284c7; }
        .form-control, .form-select { border-radius: 12px; padding: 10px; border: 1px solid #e2e8f0; background: #f8fafc; font-size: 0.9rem; }
        .form-control:focus, .form-select:focus { border-color: #8B5CF6; background: white; box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1); }
        .form-label { font-size: 0.75rem; font-weight: 700; color: #64748b; margin-bottom: 4px; text-transform: uppercase; }
        .subject-scroll { max-height: 150px; overflow-y: auto; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 10px; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Staff Management</div>
            <div style="width: 24px;"></div>
        </div>
        <h2 class="mb-0 fw-bold"><?= count($users) ?></h2>
        <div class="opacity-75 small">Total Registered Users</div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-3"><?= $msg ?></div><?php endif; ?>

        <ul class="nav nav-pills mb-3 justify-content-center" id="userTabs">
            <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#list-view">Staff List</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#single-add">Add New</button></li>
        </ul>

        <div class="tab-content">
            
            <div class="tab-pane fade show active" id="list-view">
                <form method="GET" class="mb-3">
                    <div class="input-group">
                        <span class="input-group-text bg-light border-0 ps-3 rounded-start-pill"><i class="bi bi-search text-muted"></i></span>
                        <input type="text" name="search" class="form-control border-0 bg-light rounded-end-pill fw-bold" placeholder="Search name or IC..." value="<?= htmlspecialchars($search) ?>">
                    </div>
                </form>

                <?php foreach($users as $u): 
                    $isAdmin = strpos($u['role'], 'admin') !== false;
                    $roles = explode(',', $u['role']);
                    $highlight = ($auto_reset_id && $u['id'] == $auto_reset_id) ? 'border-warning border-3 shadow' : '';
                ?>
                <div class="user-item <?= $isAdmin ? 'admin' : '' ?> <?= $highlight ?>">
                    <div class="d-flex align-items-center overflow-hidden">
                        <div class="avatar-box <?= $isAdmin ? 'admin' : '' ?>">
                            <i class="bi bi-person-fill"></i>
                        </div>
                        <div class="text-truncate">
                            <div class="fw-bold text-dark text-truncate" style="max-width: 180px;"><?= htmlspecialchars($u['full_name']) ?></div>
                            <div class="small text-muted font-monospace"><?= htmlspecialchars($u['username']) ?></div>
                            <div class="mt-1 d-flex flex-wrap gap-1">
                                <?php foreach($roles as $r): ?><span class="cond-badge bg-role"><?= ucfirst(trim($r)) ?></span><?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex flex-column gap-2 ms-2">
                        <button class="btn btn-light border btn-sm rounded-circle text-primary" onclick='openEditModal(<?= json_encode($u) ?>)'><i class="bi bi-pencil-fill"></i></button>
                        <button class="btn btn-light border btn-sm rounded-circle text-warning" onclick="openResetModal(<?= $u['id'] ?>, '<?= addslashes($u['full_name']) ?>')"><i class="bi bi-key-fill"></i></button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="tab-pane fade" id="single-add">
                <form method="POST">
                    <input type="hidden" name="action" value="add_single">
                    <div class="row g-3 p-2">
                        <div class="col-12"><label class="form-label">Full Name</label><input type="text" name="full_name" class="form-control" required></div>
                        <div class="col-6"><label class="form-label">IC Number</label><input type="text" name="ic_number" class="form-control" required></div>
                        <div class="col-6"><label class="form-label">Phone</label><input type="text" name="phone_number" class="form-control"></div>
                        
                        <div class="col-12">
                            <label class="form-label">Assigned Subjects</label>
                            <div class="subject-scroll">
                                <div class="row g-2">
                                    <?php foreach($all_subjects as $sub): ?>
                                    <div class="col-6">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="subjects[]" value="<?= htmlspecialchars($sub) ?>" id="add_sub_<?= md5($sub) ?>">
                                            <label class="form-check-label small" for="add_sub_<?= md5($sub) ?>"><?= htmlspecialchars($sub) ?></label>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-12"><button type="submit" class="btn btn-primary w-100 rounded-pill fw-bold">Add Teacher</button></div>
                    </div>
                </form>
            </div>

        </div>
    </div>

    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-primary text-white">
                    <h6 class="modal-title fw-bold">Edit User</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="user_id" id="edit_uid">
                    <div class="modal-body p-4">
                        <div class="row g-3">
                            <div class="col-6"><label class="form-label">Name</label><input type="text" name="full_name" id="edit_name" class="form-control" required></div>
                            <div class="col-6"><label class="form-label">IC</label><input type="text" name="username" id="edit_ic" class="form-control" required></div>
                            <div class="col-6"><label class="form-label">Phone</label><input type="text" name="phone_number" id="edit_phone" class="form-control"></div>
                            <div class="col-6"><label class="form-label">Telegram ID</label><input type="text" name="telegram_chat_id" id="edit_telegram" class="form-control"></div>
                            
                            <div class="col-12">
                                <label class="form-label">Subjects</label>
                                <div class="subject-scroll">
                                    <div class="row g-2">
                                        <?php foreach($all_subjects as $sub): ?>
                                        <div class="col-4">
                                            <div class="form-check">
                                                <input class="form-check-input edit-subject" type="checkbox" name="subjects[]" value="<?= htmlspecialchars($sub) ?>" id="edit_sub_<?= md5($sub) ?>">
                                                <label class="form-check-label small" for="edit_sub_<?= md5($sub) ?>"><?= htmlspecialchars($sub) ?></label>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>

                            <div class="col-12"><hr class="my-1 border-light"></div>

                            <div class="col-6">
                                <label class="form-label">Rank</label>
                                <select name="position_rank" id="edit_rank" class="form-select">
                                    <option value="0">Guru Biasa</option><option value="1">Ketua Panitia</option><option value="2">GKMP</option><option value="3">PK</option><option value="4">Pengetua</option>
                                </select>
                            </div>
                            
                            <div class="col-6">
                                <label class="form-label">Mobility</label>
                                <select name="mobility_status" id="edit_mobility" class="form-select">
                                    <option value="fit">Fit</option><option value="limited_stairs">Limited</option><option value="ground_floor_only">Ground Only</option>
                                </select>
                            </div>

                            <div class="col-6"><label class="form-label">Max Relief</label><input type="number" name="max_relief_weekly" id="edit_max" class="form-control"></div>
                            
                            <div class="col-12 bg-light p-3 rounded d-flex gap-3 justify-content-between">
                                <div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="is_pregnant" id="edit_preg"><label class="form-check-label small fw-bold">Pregnant</label></div>
                                <div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="exclude_relief" id="edit_exclude"><label class="form-check-label small fw-bold">No Relief</label></div>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Roles</label>
                                <div class="d-flex flex-wrap gap-2">
                                    <?php $avail_roles=['teacher','discipline_teacher','form6_teacher','timetable_coord','assistant','assistant_hem','principal','admin','akp','admin_booking']; foreach($avail_roles as $ar): ?>
                                    <div class="form-check border rounded px-2 py-1">
                                        <input class="form-check-input ms-0 me-1 edit-role" type="checkbox" name="roles[]" value="<?= $ar ?>">
                                        <label class="form-check-label small"><?= ucfirst($ar) ?></label>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-0 bg-light d-flex justify-content-between">
                        <a href="#" id="modal_delete_btn" class="btn btn-light text-danger fw-bold rounded-pill" onclick="return confirm('Delete?')">Delete</a>
                        <button type="submit" class="btn btn-primary fw-bold rounded-pill px-4">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="resetModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <form method="POST" onsubmit="return handleResetSubmit()">
                    <div class="modal-header bg-warning text-dark border-0">
                        <h6 class="modal-title fw-bold"><i class="bi bi-key-fill me-2"></i>Reset Password</h6>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body p-4">
                        <input type="hidden" name="action" value="reset_password">
                        <input type="hidden" name="user_id" id="reset_user_id">
                        <p class="text-center small mb-3">Reset password for <strong id="reset_user_name"></strong>?</p>
                        <div class="bg-light p-3 rounded mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="reset_type" id="resetDefault" value="default" checked onchange="togglePassInput()">
                                <label class="form-check-label fw-bold" for="resetDefault">Reset to Default (IC)</label>
                            </div>
                        </div>
                        <div class="bg-light p-3 rounded">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="reset_type" id="resetManual" value="manual" onchange="togglePassInput()">
                                <label class="form-check-label fw-bold" for="resetManual">Set Manual Password</label>
                            </div>
                            <input type="text" name="new_password" id="manualPassInput" class="form-control mt-2" placeholder="Enter new password" disabled>
                        </div>
                    </div>
                    <div class="modal-footer border-0 bg-light">
                        <button type="submit" class="btn btn-warning w-100 fw-bold rounded-pill">Confirm Reset</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const editModal = new bootstrap.Modal(document.getElementById('editModal'));
        const resetModal = new bootstrap.Modal(document.getElementById('resetModal'));

        function openEditModal(u) {
            document.getElementById('edit_uid').value = u.id;
            document.getElementById('edit_name').value = u.full_name;
            document.getElementById('edit_ic').value = u.username;
            document.getElementById('edit_phone').value = u.phone_number;
            document.getElementById('edit_max').value = u.max_relief_weekly;
            document.getElementById('edit_telegram').value = u.telegram_chat_id;
            document.getElementById('edit_rank').value = u.position_rank;
            document.getElementById('edit_mobility').value = u.mobility_status || 'fit';
            document.getElementById('edit_exclude').checked = (u.exclude_relief == 1);
            document.getElementById('edit_preg').checked = (u.is_pregnant == 1);
            
            // Check Roles
            const userRoles = u.role.split(',').map(r => r.trim());
            document.querySelectorAll('.edit-role').forEach(chk => { chk.checked = userRoles.includes(chk.value); });

            // Check Subjects
            const userSubjects = (u.subjects || '').split(',').map(s => s.trim());
            document.querySelectorAll('.edit-subject').forEach(chk => { 
                chk.checked = userSubjects.includes(chk.value); 
            });

            const delBtn = document.getElementById('modal_delete_btn');
            if (u.id == <?= $_SESSION['user_id'] ?>) { delBtn.style.display = 'none'; } 
            else { delBtn.style.display = 'block'; delBtn.href = '?delete_id=' + u.id; }
            editModal.show();
        }

        function openResetModal(id, name) {
            document.getElementById('reset_user_id').value = id;
            document.getElementById('reset_user_name').innerText = name;
            document.getElementById('resetDefault').checked = true;
            togglePassInput();
            resetModal.show();
        }

        function togglePassInput() {
            const isManual = document.getElementById('resetManual').checked;
            const input = document.getElementById('manualPassInput');
            input.disabled = !isManual;
            if (!isManual) input.value = ''; else input.focus();
        }

        function handleResetSubmit() {
            if (document.getElementById('resetManual').checked) {
                if (document.getElementById('manualPassInput').value.trim() === "") {
                    alert("Please enter a new password."); return false;
                }
            }
            return confirm("Confirm password reset?");
        }

        const autoResetId = '<?= $auto_reset_id ?>';
        const autoResetName = '<?= addslashes($auto_reset_name) ?>';
        if (autoResetId && autoResetName) {
            setTimeout(() => { openResetModal(autoResetId, autoResetName); }, 300);
        }
    </script>
</body>
</html>