<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Role-based access: only admin and headteacher
$allowed_roles = ['admin', 'headteacher'];
if (!in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: dashboard.php?error=access_denied');
    exit;
}

require_once 'config.php';
require_once __DIR__ . '/includes/upload_validator.php';
$conn = getDBConnection();

// Helper function to generate staff ID
function generateStaffId($conn) {
    $result = $conn->query("SELECT staff_id FROM staff WHERE staff_id REGEXP '^STF[0-9]+$' ORDER BY CAST(SUBSTRING(staff_id, 4) AS UNSIGNED) DESC LIMIT 1");
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $lastId = $row['staff_id'];
        $number = intval(substr($lastId, 3));
        $nextNumber = $number + 1;
    } else {
        $nextNumber = 1;
    }
    return 'STF' . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
}

// Handle form submissions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Add Staff
    if (isset($_POST['action']) && $_POST['action'] === 'add') {
        $staff_id = generateStaffId($conn);
        // Use trim() not sanitize() — prepared statements handle SQL safety; HTML-encoding is done at output time.
        $full_name = trim((string) ($_POST['full_name'] ?? ''));
        $reg_no = trim((string) ($_POST['reg_no'] ?? ''));
        $academic_qualification = trim((string) ($_POST['academic_qualification'] ?? ''));
        $professional_qualification = trim((string) ($_POST['professional_qualification'] ?? ''));
        $class_taught = trim((string) ($_POST['class_taught'] ?? ''));
        $present_rank = trim((string) ($_POST['present_rank'] ?? ''));
        $date_promoted_to_present_rank = trim((string) ($_POST['date_promoted_to_present_rank'] ?? '')) ?: null;
        $date_of_first_appointment = trim((string) ($_POST['date_of_first_appointment'] ?? '')) ?: null;
        $year_of_certification = trim((string) ($_POST['year_of_certification'] ?? ''));
        $age = intval($_POST['age'] ?? 0);
        $sex = trim((string) ($_POST['sex'] ?? ''));
        $date_of_birth = trim((string) ($_POST['date_of_birth'] ?? '')) ?: null;
        $place_of_birth = trim((string) ($_POST['place_of_birth'] ?? ''));
        $nationality = trim((string) ($_POST['nationality'] ?? ''));
        $residential_address = trim((string) ($_POST['residential_address'] ?? ''));
        $institutions_attended = trim((string) ($_POST['institutions_attended'] ?? ''));
        $teaching_experience = trim((string) ($_POST['teaching_experience'] ?? ''));
        $previous_schools = trim((string) ($_POST['previous_schools'] ?? ''));
        $bank_name = trim((string) ($_POST['bank_name'] ?? ''));
        $bank_account = trim((string) ($_POST['bank_account'] ?? ''));
        $date_posted_to_present_station = trim((string) ($_POST['date_posted_to_present_station'] ?? '')) ?: null;
        $expected_retirement_date = trim((string) ($_POST['expected_retirement_date'] ?? '')) ?: null;
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $tel_no = trim((string) ($_POST['tel_no'] ?? ''));
        $religious_denomination = trim((string) ($_POST['religious_denomination'] ?? ''));
        $email = trim((string) ($_POST['email'] ?? ''));
        $marital_status = trim((string) ($_POST['marital_status'] ?? ''));
        $languages_spoken = trim((string) ($_POST['languages_spoken'] ?? ''));
        $next_of_kin = trim((string) ($_POST['next_of_kin'] ?? ''));
        $next_of_kin_phone = trim((string) ($_POST['next_of_kin_phone'] ?? ''));
        $digital_address = trim((string) ($_POST['digital_address'] ?? ''));
        $ssnit_number = trim((string) ($_POST['ssnit_number'] ?? ''));
        $district = trim((string) ($_POST['district'] ?? ''));
        $tin_number = trim((string) ($_POST['tin_number'] ?? ''));
        $region = trim((string) ($_POST['region'] ?? ''));
        $hometown = trim((string) ($_POST['hometown'] ?? ''));
        $date_of_employment = trim((string) ($_POST['date_of_employment'] ?? '')) ?: null;
        $salary = floatval($_POST['salary'] ?? 0);
        $class_assigned = trim((string) ($_POST['class_assigned'] ?? ''));
        $subject_to_teach = trim((string) ($_POST['subject_to_teach'] ?? ''));
        $approved_by = trim((string) ($_POST['approved_by'] ?? ''));
        $status = trim((string) ($_POST['status'] ?? 'active'));

        // Handle photo upload
        $photo_path = null;
        if (!empty($_FILES['photo']['name'])) {
            $photo_path = save_uploaded_image($_FILES['photo'], 'uploads/staff', $photoErr);
        } elseif (!empty($_POST['photo_data'])) {
            $photo_path = save_base64_image((string) $_POST['photo_data'], 'uploads/staff', $photoErr);
        }

        // Insert into database
        $stmt = $conn->prepare("INSERT INTO staff (
            staff_id, full_name, reg_no, academic_qualification, professional_qualification,
            class_taught, present_rank, date_promoted_to_present_rank, date_of_first_appointment,
            year_of_certification, age, sex, date_of_birth, place_of_birth, nationality,
            residential_address, institutions_attended, teaching_experience, previous_schools,
            bank_name, bank_account, date_posted_to_present_station, expected_retirement_date,
            phone, tel_no, religious_denomination, email, marital_status, languages_spoken,
            next_of_kin, next_of_kin_phone, digital_address, ssnit_number, district, tin_number,
            region, hometown, photo_path, date_of_employment, salary, class_assigned, subject_to_teach,
            approved_by, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        $insertTypes = str_repeat('s', 10) . 'i' . str_repeat('s', 28) . 'd' . str_repeat('s', 4);
        $stmt->bind_param($insertTypes,
            $staff_id, $full_name, $reg_no, $academic_qualification, $professional_qualification,
            $class_taught, $present_rank, $date_promoted_to_present_rank, $date_of_first_appointment,
            $year_of_certification, $age, $sex, $date_of_birth, $place_of_birth, $nationality,
            $residential_address, $institutions_attended, $teaching_experience, $previous_schools,
            $bank_name, $bank_account, $date_posted_to_present_station, $expected_retirement_date,
            $phone, $tel_no, $religious_denomination, $email, $marital_status, $languages_spoken,
            $next_of_kin, $next_of_kin_phone, $digital_address, $ssnit_number, $district, $tin_number,
            $region, $hometown, $photo_path, $date_of_employment, $salary, $class_assigned, $subject_to_teach,
            $approved_by, $status
        );

        $created_user = null; // holds username/password if auto-created
        if ($stmt->execute()) {
            $staff_insert_id = (int) $conn->insert_id;
            $message = 'Staff added successfully! Staff ID: ' . $staff_id;
            $messageType = 'success';
            $stmt->close();

            // Auto-create user account for teacher/tutor roles
            $teacher_roles = ['teacher', 'tutor', 'class teacher'];
            if (in_array(strtolower($status), $teacher_roles)) {
                // Generate username from full name
                $username = strtolower(preg_replace('/\s+/', '.', trim($full_name)));
                $username = preg_replace('/[^a-z0-9.]/', '', $username);

                // Ensure unique
                $chkUser = $conn->prepare("SELECT id FROM users WHERE username = ?");
                $chkUser->bind_param('s', $username);
                $chkUser->execute();
                if ($chkUser->get_result()->num_rows > 0) {
                    $username .= rand(10, 99);
                }
                $chkUser->close();

                $temp_password = 'Teacher' . rand(1000, 9999) . '!';
                $hash = password_hash($temp_password, PASSWORD_BCRYPT);
                $tutor_role = 'tutor';

                $uStmt = $conn->prepare(
                    "INSERT INTO users (username, password, full_name, email, phone, role, is_active, created_at)
                     VALUES (?,?,?,?,?,?,1,NOW())"
                );
                $uStmt->bind_param('ssssss', $username, $hash, $full_name, $email, $phone, $tutor_role);
                if ($uStmt->execute()) {
                    $new_user_id = (int) $conn->insert_id;
                    $uStmt->close();

                    // Link staff record to user
                    $lStmt = $conn->prepare("UPDATE staff SET user_id = ? WHERE id = ?");
                    $lStmt->bind_param('ii', $new_user_id, $staff_insert_id);
                    $lStmt->execute();
                    $lStmt->close();

                    $created_user = ['username' => $username, 'password' => $temp_password];
                    $message .= ' A teacher login account has been created (see below).';
                } else {
                    $uStmt->close();
                }
            }
        } else {
            $message = 'Failed to add staff: ' . $stmt->error;
            $messageType = 'danger';
            $stmt->close();
        }
    }

    // Update Staff
    elseif (isset($_POST['action']) && $_POST['action'] === 'update') {
        $id = intval($_POST['id'] ?? 0);
        // Use trim() not sanitize() — prepared statements handle SQL safety; HTML-encoding is done at output time.
        $staff_id = trim((string) ($_POST['staff_id'] ?? ''));
        $full_name = trim((string) ($_POST['full_name'] ?? ''));
        $reg_no = trim((string) ($_POST['reg_no'] ?? ''));
        $academic_qualification = trim((string) ($_POST['academic_qualification'] ?? ''));
        $professional_qualification = trim((string) ($_POST['professional_qualification'] ?? ''));
        $class_taught = trim((string) ($_POST['class_taught'] ?? ''));
        $present_rank = trim((string) ($_POST['present_rank'] ?? ''));
        $date_promoted_to_present_rank = trim((string) ($_POST['date_promoted_to_present_rank'] ?? '')) ?: null;
        $date_of_first_appointment = trim((string) ($_POST['date_of_first_appointment'] ?? '')) ?: null;
        $year_of_certification = trim((string) ($_POST['year_of_certification'] ?? ''));
        $age = intval($_POST['age'] ?? 0);
        $sex = trim((string) ($_POST['sex'] ?? ''));
        $date_of_birth = trim((string) ($_POST['date_of_birth'] ?? '')) ?: null;
        $place_of_birth = trim((string) ($_POST['place_of_birth'] ?? ''));
        $nationality = trim((string) ($_POST['nationality'] ?? ''));
        $residential_address = trim((string) ($_POST['residential_address'] ?? ''));
        $institutions_attended = trim((string) ($_POST['institutions_attended'] ?? ''));
        $teaching_experience = trim((string) ($_POST['teaching_experience'] ?? ''));
        $previous_schools = trim((string) ($_POST['previous_schools'] ?? ''));
        $bank_name = trim((string) ($_POST['bank_name'] ?? ''));
        $bank_account = trim((string) ($_POST['bank_account'] ?? ''));
        $date_posted_to_present_station = trim((string) ($_POST['date_posted_to_present_station'] ?? '')) ?: null;
        $expected_retirement_date = trim((string) ($_POST['expected_retirement_date'] ?? '')) ?: null;
        $phone = trim((string) ($_POST['phone'] ?? ''));
        $tel_no = trim((string) ($_POST['tel_no'] ?? ''));
        $religious_denomination = trim((string) ($_POST['religious_denomination'] ?? ''));
        $email = trim((string) ($_POST['email'] ?? ''));
        $marital_status = trim((string) ($_POST['marital_status'] ?? ''));
        $languages_spoken = trim((string) ($_POST['languages_spoken'] ?? ''));
        $next_of_kin = trim((string) ($_POST['next_of_kin'] ?? ''));
        $next_of_kin_phone = trim((string) ($_POST['next_of_kin_phone'] ?? ''));
        $digital_address = trim((string) ($_POST['digital_address'] ?? ''));
        $ssnit_number = trim((string) ($_POST['ssnit_number'] ?? ''));
        $district = trim((string) ($_POST['district'] ?? ''));
        $tin_number = trim((string) ($_POST['tin_number'] ?? ''));
        $region = trim((string) ($_POST['region'] ?? ''));
        $hometown = trim((string) ($_POST['hometown'] ?? ''));
        $date_of_employment = trim((string) ($_POST['date_of_employment'] ?? '')) ?: null;
        $salary = floatval($_POST['salary'] ?? 0);
        $class_assigned = trim((string) ($_POST['class_assigned'] ?? ''));
        $subject_to_teach = trim((string) ($_POST['subject_to_teach'] ?? ''));
        $approved_by = trim((string) ($_POST['approved_by'] ?? ''));
        $status = trim((string) ($_POST['status'] ?? 'active'));
        $existing_photo_path = trim((string) ($_POST['existing_photo_path'] ?? ''));

        $photo_path = $existing_photo_path;
        if (!empty($_FILES['photo']['name'])) {
            $photo_path = save_uploaded_image($_FILES['photo'], 'uploads/staff', $photoErr);
        } elseif (!empty($_POST['photo_data'])) {
            $photo_path = save_base64_image((string) $_POST['photo_data'], 'uploads/staff', $photoErr);
        } elseif (!empty($_POST['remove_photo'])) {
            $photo_path = '';
        }

        $sql = "UPDATE staff SET
            staff_id = ?, full_name = ?, reg_no = ?, academic_qualification = ?, professional_qualification = ?,
            class_taught = ?, present_rank = ?, date_promoted_to_present_rank = ?, date_of_first_appointment = ?,
            year_of_certification = ?, age = ?, sex = ?, date_of_birth = ?, place_of_birth = ?, nationality = ?,
            residential_address = ?, institutions_attended = ?, teaching_experience = ?, previous_schools = ?,
            bank_name = ?, bank_account = ?, date_posted_to_present_station = ?, expected_retirement_date = ?, phone = ?,
            tel_no = ?, religious_denomination = ?, email = ?, marital_status = ?, languages_spoken = ?, next_of_kin = ?,
            next_of_kin_phone = ?, digital_address = ?, ssnit_number = ?, district = ?, tin_number = ?, region = ?,
            hometown = ?, photo_path = ?, date_of_employment = ?, salary = ?, class_assigned = ?, subject_to_teach = ?,
            approved_by = ?, status = ?
            WHERE id = ?";
        $stmt = $conn->prepare($sql);

        if (!$stmt) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => $conn->error]);
            exit;
        }

        $updateTypes = str_repeat('s', 10) . 'i' . str_repeat('s', 28) . 'd' . str_repeat('s', 4) . 'i';
        $stmt->bind_param(
            $updateTypes,
            $staff_id,
            $full_name,
            $reg_no,
            $academic_qualification,
            $professional_qualification,
            $class_taught,
            $present_rank,
            $date_promoted_to_present_rank,
            $date_of_first_appointment,
            $year_of_certification,
            $age,
            $sex,
            $date_of_birth,
            $place_of_birth,
            $nationality,
            $residential_address,
            $institutions_attended,
            $teaching_experience,
            $previous_schools,
            $bank_name,
            $bank_account,
            $date_posted_to_present_station,
            $expected_retirement_date,
            $phone,
            $tel_no,
            $religious_denomination,
            $email,
            $marital_status,
            $languages_spoken,
            $next_of_kin,
            $next_of_kin_phone,
            $digital_address,
            $ssnit_number,
            $district,
            $tin_number,
            $region,
            $hometown,
            $photo_path,
            $date_of_employment,
            $salary,
            $class_assigned,
            $subject_to_teach,
            $approved_by,
            $status,
            $id
        );

        $success = $stmt->execute();
        $errorMessage = $stmt->error ?: $conn->error;
        $stmt->close();

        header('Content-Type: application/json');
        if ($success) {
            echo json_encode(['success' => true, 'message' => 'Staff updated']);
        } else {
            echo json_encode(['success' => false, 'message' => $errorMessage]);
        }
        exit;
    }
}

// Handle delete
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $stmt = $conn->prepare("DELETE FROM staff WHERE id = ?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $message = 'Staff deleted successfully!';
        $messageType = 'success';
    } else {
        $message = 'Failed to delete staff: ' . $stmt->error;
        $messageType = 'danger';
    }
    $stmt->close();
}

// Fetch all staff for listing
$staffList = [];
$result = $conn->query("SELECT id, staff_id, full_name, phone, email, status FROM staff ORDER BY id DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $staffList[] = $row;
    }
}

// Get next staff ID for preview
$nextStaffId = generateStaffId($conn);

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Management - EduTrack PRO</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <!-- Webcam and Signature (optional) -->
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/webcamjs@1.0.26/webcam.min.js"></script>
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar (same as other pages, add Staff link) -->
        <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>
        </nav>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
                <div class="header-right">
                    <span class="badge bg-primary me-3">Role: <?php echo htmlspecialchars(ucfirst((string) ($_SESSION['role'] ?? ''))); ?></span>
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <!-- Page Content -->
            <main class="content">
                <div class="content-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h2><i class="fas fa-chalkboard-teacher me-2"></i>Staff Management</h2>
                            <p>Manage teacher and staff records</p>
                        </div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addStaffModal">
                            <i class="fas fa-plus me-2"></i>Add Staff
                        </button>
                    </div>
                </div>

                <!-- Alert Message -->
                <?php if ($message): ?>
                <div class="alert alert-<?php echo htmlspecialchars($messageType); ?> alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Teacher credentials card (shown after auto-creating a login) -->
                <?php if (!empty($created_user)): ?>
                <div class="alert alert-info border-info" role="alert">
                    <h6 class="alert-heading"><i class="fas fa-user-plus me-2"></i>Teacher Login Account Created</h6>
                    <p class="mb-1">Please share these credentials with the teacher:</p>
                    <table class="table table-sm table-bordered w-auto mb-2">
                        <tr><th>Username</th><td><code id="newTeacherUser"><?= htmlspecialchars($created_user['username']) ?></code></td></tr>
                        <tr><th>Temp Password</th><td><code id="newTeacherPass"><?= htmlspecialchars($created_user['password']) ?></code></td></tr>
                    </table>
                    <button class="btn btn-sm btn-outline-info" onclick="
                        navigator.clipboard.writeText('Username: <?= htmlspecialchars($created_user['username']) ?>\nPassword: <?= htmlspecialchars($created_user['password']) ?>');
                        this.textContent='Copied!'; setTimeout(()=>this.textContent='Copy to Clipboard',2000);
                    "><i class="fas fa-copy me-1"></i>Copy to Clipboard</button>
                    <p class="small text-muted mt-2 mb-0">The teacher should change their password after first login.</p>
                </div>
                <?php endif; ?>

                <!-- Staff Table -->
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5><i class="fas fa-list me-2"></i>All Staff</h5>
                            <div class="search-box">
                                <i class="fas fa-search"></i>
                                <input type="text" class="form-control" id="searchInput" placeholder="Search staff...">
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover" id="staffTable">
                                <thead>
                                    <tr>
                                        <th>Staff ID</th>
                                        <th>Name</th>
                                        <th>Phone</th>
                                        <th>Email</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($staffList)): ?>
                                    <tr><td colspan="6" class="text-center py-5">No staff found.</td></tr>
                                    <?php else: ?>
                                    <?php foreach ($staffList as $staff): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($staff['staff_id']); ?></td>
                                        <td><?php echo htmlspecialchars($staff['full_name']); ?></td>
                                        <td><?php echo htmlspecialchars($staff['phone'] ?: '-'); ?></td>
                                        <td><?php echo htmlspecialchars($staff['email'] ?: '-'); ?></td>
                                        <td><span class="badge badge-<?php echo $staff['status']; ?>"><?php echo ucfirst($staff['status']); ?></span></td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="action-btn view" onclick="viewStaff(<?php echo $staff['id']; ?>)"><i class="fas fa-eye"></i></button>
                                                <button class="action-btn edit" onclick="editStaff(<?php echo $staff['id']; ?>)"><i class="fas fa-edit"></i></button>
                                                <a href="staff.php?action=delete&id=<?php echo $staff['id']; ?>" class="action-btn delete" onclick="return confirm('Delete this staff member?')"><i class="fas fa-trash"></i></a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>

            <!-- Footer -->
            <footer class="footer"><p>&copy; 2024 EduTrack PRO. All rights reserved.</p></footer>
        </div>
    </div>

    <!-- Add Staff Modal (very large, with tabs) -->
    <div class="modal fade" id="addStaffModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-plus me-2"></i>Add New Staff</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="staff.php" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="add">
                    <div class="modal-body">
                        <!-- Staff ID preview -->
                        <div class="alert alert-info">
                            <strong>Staff ID will be:</strong> <?php echo $nextStaffId; ?> (auto-generated)
                        </div>
                        <!-- Nav tabs -->
                        <ul class="nav nav-tabs" id="staffTabs" role="tablist">
                            <li class="nav-item"><div class="nav-link active" data-bs-toggle="tab" data-bs-target="#particulars">Particulars</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#professional">Professional</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#bank">Bank & Official</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#other">Other</div></li>
                            <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#photo">Photo</div></li>
                        </ul>
                        <div class="tab-content mt-3">
                            <!-- Particulars Tab -->
                            <div class="tab-pane fade show active" id="particulars">
                                <div class="row">
                                    <div class="col-md-6 mb-3"><label>Full Name *</label><input type="text" class="form-control" name="full_name" required></div>
                                    <div class="col-md-6 mb-3"><label>Reg. No</label><input type="text" class="form-control" name="reg_no"></div>
                                    <div class="col-md-6 mb-3"><label>Date of Birth</label><input type="date" class="form-control" name="date_of_birth"></div>
                                    <div class="col-md-6 mb-3"><label>Place of Birth</label><input type="text" class="form-control" name="place_of_birth"></div>
                                    <div class="col-md-4 mb-3"><label>Age</label><input type="number" class="form-control" name="age"></div>
                                    <div class="col-md-4 mb-3"><label>Sex</label><select class="form-select" name="sex"><option value="">Select</option><option value="Male">Male</option><option value="Female">Female</option><option value="Other">Other</option></select></div>
                                    <div class="col-md-4 mb-3"><label>Nationality</label><input type="text" class="form-control" name="nationality"></div>
                                    <div class="col-md-6 mb-3"><label>Residential Address</label><textarea class="form-control" name="residential_address"></textarea></div>
                                    <div class="col-md-6 mb-3"><label>Digital Address</label><input type="text" class="form-control" name="digital_address"></div>
                                    <div class="col-md-4 mb-3"><label>Phone Number</label><input type="tel" class="form-control" name="phone"></div>
                                    <div class="col-md-4 mb-3"><label>Tel No (Alternative)</label><input type="tel" class="form-control" name="tel_no"></div>
                                    <div class="col-md-4 mb-3"><label>Email</label><input type="email" class="form-control" name="email"></div>
                                    <div class="col-md-4 mb-3"><label>Religious Denomination</label><input type="text" class="form-control" name="religious_denomination"></div>
                                    <div class="col-md-4 mb-3"><label>Marital Status</label><select class="form-select" name="marital_status"><option value="">Select</option><option value="Single">Single</option><option value="Married">Married</option><option value="Divorced">Divorced</option><option value="Widowed">Widowed</option></select></div>
                                    <div class="col-md-4 mb-3"><label>Languages Spoken</label><input type="text" class="form-control" name="languages_spoken" placeholder="e.g., English, Twi"></div>
                                    <div class="col-md-6 mb-3"><label>Next of Kin</label><input type="text" class="form-control" name="next_of_kin" placeholder="Name"></div>
                                    <div class="col-md-6 mb-3"><label>Next of Kin Phone</label><input type="tel" class="form-control" name="next_of_kin_phone"></div>
                                    <div class="col-md-4 mb-3"><label>SSNIT Number</label><input type="text" class="form-control" name="ssnit_number"></div>
                                    <div class="col-md-4 mb-3"><label>TIN Number</label><input type="text" class="form-control" name="tin_number"></div>
                                    <div class="col-md-4 mb-3"><label>Hometown</label><input type="text" class="form-control" name="hometown"></div>
                                    <div class="col-md-4 mb-3"><label>District</label><input type="text" class="form-control" name="district"></div>
                                    <div class="col-md-4 mb-3"><label>Region</label><input type="text" class="form-control" name="region"></div>
                                </div>
                            </div>
                            <!-- Professional Tab -->
                            <div class="tab-pane fade" id="professional">
                                <div class="row">
                                    <div class="col-md-6 mb-3"><label>Academic Qualification</label><textarea class="form-control" name="academic_qualification"></textarea></div>
                                    <div class="col-md-6 mb-3"><label>Professional Qualification</label><textarea class="form-control" name="professional_qualification"></textarea></div>
                                    <div class="col-md-4 mb-3"><label>Class Taught</label><input type="text" class="form-control" name="class_taught"></div>
                                    <div class="col-md-4 mb-3"><label>Present Rank</label><input type="text" class="form-control" name="present_rank"></div>
                                    <div class="col-md-4 mb-3"><label>Date Promoted to Present Rank</label><input type="date" class="form-control" name="date_promoted_to_present_rank"></div>
                                    <div class="col-md-4 mb-3"><label>Date of 1st Appointment</label><input type="date" class="form-control" name="date_of_first_appointment"></div>
                                    <div class="col-md-4 mb-3"><label>Year of Certification</label><input type="text" class="form-control" name="year_of_certification"></div>
                                    <div class="col-md-12 mb-3"><label>Institutions Attended</label><textarea class="form-control" name="institutions_attended"></textarea></div>
                                    <div class="col-md-12 mb-3"><label>Teaching Experience</label><textarea class="form-control" name="teaching_experience"></textarea></div>
                                    <div class="col-md-12 mb-3"><label>Previous Schools</label><textarea class="form-control" name="previous_schools"></textarea></div>
                                    <div class="col-md-4 mb-3"><label>Date Posted to Present Station</label><input type="date" class="form-control" name="date_posted_to_present_station"></div>
                                    <div class="col-md-4 mb-3"><label>Expected Date of Retirement</label><input type="date" class="form-control" name="expected_retirement_date"></div>
                                </div>
                            </div>
                            <!-- Bank & Official Tab -->
                            <div class="tab-pane fade" id="bank">
                                <div class="row">
                                    <div class="col-md-6 mb-3"><label>Bank Name</label><input type="text" class="form-control" name="bank_name"></div>
                                    <div class="col-md-6 mb-3"><label>Bank Account No.</label><input type="text" class="form-control" name="bank_account"></div>
                                    <hr>
                                    <h6>Official Use Only</h6>
                                    <div class="col-md-4 mb-3"><label>Date of Employment</label><input type="date" class="form-control" name="date_of_employment"></div>
                                    <div class="col-md-4 mb-3"><label>Salary (GHS)</label><input type="number" step="0.01" class="form-control" name="salary"></div>
                                    <div class="col-md-4 mb-3"><label>Class Assigned</label><input type="text" class="form-control" name="class_assigned"></div>
                                    <div class="col-md-4 mb-3"><label>Subject to Teach</label><input type="text" class="form-control" name="subject_to_teach"></div>
                                    <div class="col-md-4 mb-3"><label>Approved By</label><input type="text" class="form-control" name="approved_by"></div>
                                    <div class="col-md-4 mb-3"><label>Status</label><select class="form-select" name="status"><option value="active">Active</option><option value="inactive">Inactive</option></select></div>
                                </div>
                            </div>
                            <!-- Other Tab (can include next of kin, etc, but we already put them in particulars) -->
                            <div class="tab-pane fade" id="other">
                                <!-- Any remaining fields can go here -->
                            </div>
                            <!-- Photo Tab -->
                            <div class="tab-pane fade" id="photo">
                                <div class="row">
                                    <div class="col-md-6">
                                        <label>Capture Photo (Webcam)</label>
                                        <div id="webcam-container"></div>
                                        <button type="button" class="btn btn-sm btn-primary mt-2" onclick="capturePhoto()">Capture</button>
                                        <div id="photo-preview" class="mt-2"></div>
                                        <input type="hidden" name="photo_data" id="photo_data">
                                    </div>
                                    <div class="col-md-6">
                                        <label>Or Upload Photo</label>
                                        <input type="file" class="form-control" name="photo" accept="image/*" id="photo-file">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Staff</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Staff Modal -->
    <div class="modal fade" id="editStaffModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-edit me-2"></i>Edit Staff</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="staff.php" enctype="multipart/form-data" id="editStaffForm">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="editStaffId">
                    <div class="modal-body" id="editStaffContent">
                        <!-- Loaded via AJAX -->
                        <p class="text-center">Loading...</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-warning me-auto" id="resetTeacherLoginBtn" onclick="resetTeacherLogin()" style="display:none">
                            <i class="fas fa-key me-1"></i>Reset Teacher Login
                        </button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Staff</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Staff Modal -->
    <div class="modal fade" id="viewStaffModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user me-2"></i>Staff Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="viewStaffContent">
                    <p class="text-center">Loading...</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="js/main.js"></script>
    <script>
        // Search functionality
        $('#searchInput').on('keyup', function() {
            const val = $(this).val().toLowerCase();
            $('#staffTable tbody tr').filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(val) > -1);
            });
        });

        // Webcam
        Webcam.set({ width: 320, height: 240, image_format: 'jpeg', jpeg_quality: 90 });
        $('#addStaffModal').on('shown.bs.modal', function() {
            Webcam.attach('#webcam-container');
        });
        $('#addStaffModal').on('hidden.bs.modal', function() {
            Webcam.reset();
            $('#photo-preview').empty();
            $('#photo_data').val('');
        });

        function capturePhoto() {
            Webcam.snap(function(data_uri) {
                $('#photo_data').val(data_uri);
                $('#photo-preview').html('<img src="' + data_uri + '" style="max-width:100%;">');
            });
        }

        // File upload preview
        $('#photo-file').on('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#photo-preview').html('<img src="' + e.target.result + '" style="max-width:100%;">');
                };
                reader.readAsDataURL(file);
            }
        });

        // Edit Staff
        function editStaff(id) {
            $('#editStaffId').val(id);
            $('#resetTeacherLoginBtn').hide();
            $('#editStaffModal').modal('show');
            $('#editStaffContent').html('<p class="text-center">Loading...</p>');
            $.ajax({
                url: 'ajax/staff.php?action=edit&id=' + id,
                type: 'GET',
                success: function(res) {
                    $('#editStaffContent').html(res);
                    // Show reset button for teacher/tutor roles
                    const roleField = document.querySelector('#editStaffContent [name="status"]');
                    if (roleField) {
                        const teacherRoles = ['teacher','tutor','class teacher'];
                        if (teacherRoles.includes(roleField.value.toLowerCase())) {
                            $('#resetTeacherLoginBtn').show();
                        }
                        roleField.addEventListener('change', function() {
                            $('#resetTeacherLoginBtn').toggle(teacherRoles.includes(this.value.toLowerCase()));
                        });
                    }
                },
                error: function() {
                    $('#editStaffContent').html('<p class="text-danger">Failed to load data.</p>');
                }
            });
        }

        function resetTeacherLogin() {
            const id = $('#editStaffId').val();
            if (!id) return;
            if (!confirm('Generate a new temporary password for this teacher?')) return;
            $.ajax({
                url: 'ajax/staff.php',
                type: 'POST',
                data: { action: 'reset_teacher_login', staff_id: id },
                dataType: 'json',
                success: function(r) {
                    if (r.success) {
                        alert('New credentials:\nUsername: ' + r.username + '\nPassword: ' + r.password + '\n\nShare these with the teacher.');
                    } else {
                        alert(r.message || 'Failed to reset login');
                    }
                },
                error: function() { alert('Request failed'); }
            });
        }

        // View Staff
        function viewStaff(id) {
            $('#viewStaffModal').modal('show');
            $('#viewStaffContent').html('<p class="text-center">Loading...</p>');
            $.ajax({
                url: 'ajax/staff.php?action=view&id=' + id,
                type: 'GET',
                success: function(res) {
                    $('#viewStaffContent').html(res);
                },
                error: function() {
                    $('#viewStaffContent').html('<p class="text-danger">Failed to load data.</p>');
                }
            });
        }

        $('#editStaffForm').on('submit', function(e) {
            e.preventDefault();

            const formData = new FormData(this);

            $.ajax({
                url: 'staff.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert(response.message);
                        $('#editStaffModal').modal('hide');
                        window.location.reload();
                    } else {
                        alert(response.message || 'Failed to update staff');
                    }
                },
                error: function(xhr) {
                    let message = 'Failed to update staff';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                    alert(message);
                }
            });
        });
    </script>
</body>
</html>
