<?php
include 'includes/conn.php';
include 'includes/functions.php';
requireRole('admin');

enforceAccessControl($pdo);

// =========================
// CONFIG
// =========================
error_reporting(E_ALL);
ini_set('display_errors', 0);

$message = '';
$message_type = '';

// ===================================================
// ADD USER
// ===================================================
if (isset($_POST['add_user'])) {

    $first_name     = trim($_POST['first_name']);
    $last_name      = trim($_POST['last_name']);
    $username       = trim($_POST['username']);
    $email          = trim($_POST['email']);
    $date_of_birth  = $_POST['date_of_birth'];
    $role           = $_POST['role'];
    $password       = password_hash($_POST['password'], PASSWORD_DEFAULT);

    // Photo (BLOB)
    $photoData = null;
    if (!empty($_FILES['photo']['tmp_name'])) {
        $photoData = file_get_contents($_FILES['photo']['tmp_name']);
    }

    try {

        $stmt = $pdo->prepare("
            INSERT INTO users 
            (username, password, first_name, last_name, email, role, date_of_birth, photo, last_login)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");

        $stmt->execute([
            $username,
            $password,
            $first_name,
            $last_name,
            $email,
            $role,
            $date_of_birth,
            $photoData
        ]);

        $message = "User registered successfully!";
        $message_type = "success";

    } catch (PDOException $e) {

        if ($e->getCode() == 23000) {
            $message = "This username is already taken. Please choose a different username.";
        } else {
            $message = "An unexpected error occurred. Please try again.";
        }

        $message_type = "warning";
    }
}


// ===================================================
// ADD SUBJECT
// ===================================================
if (isset($_POST['add_subject'])) {
    $name = trim($_POST['name']);
    $code = trim($_POST['code']);
    $description = trim($_POST['description']);

    $check = $pdo->prepare("SELECT id FROM subjects WHERE code=?");
    $check->execute([$code]);

    if ($check->rowCount() > 0) {
        $message = "Subject code already exists!";
        $message_type = "danger";
    } else {
        $stmt = $pdo->prepare("INSERT INTO subjects (name, code, description) VALUES (?, ?, ?)");
        $stmt->execute([$name, $code, $description]);

        $message = "Subject added successfully!";
        $message_type = "success";
    }
}


// ===================================================
// UPDATE USER
// ===================================================
if (isset($_POST['update_user'])) {
    $user_id    = $_POST['user_id'];
    $username   = trim($_POST['username']);
    $first_name = trim($_POST['first_name']);
    $last_name  = trim($_POST['last_name']);
    $email      = trim($_POST['email']);
    $date_of_birth = trim($_POST['date_of_birth']);
    $role       = $_POST['role'];

    // Check duplicate username
    $check = $pdo->prepare("SELECT id FROM users WHERE username=? AND id!=?");
    $check->execute([$username, $user_id]);

    if ($check->rowCount() > 0) {
        $message = "Username already exists!";
        $message_type = "danger";
    } else {
        // Photo
        $photoData = null;
        if (!empty($_FILES['photo']['tmp_name'])) {
            $allowed = ['image/jpeg', 'image/png', 'image/gif'];
            if (!in_array($_FILES['photo']['type'], $allowed)) {
                $message = "Invalid photo type!";
                $message_type = "danger";
            } elseif ($_FILES['photo']['size'] > 2 * 1024 * 1024) {
                $message = "Photo too large!";
                $message_type = "danger";
            } else {
                $photoData = file_get_contents($_FILES['photo']['tmp_name']);
            }
        }

        // Build query
        if ($photoData) {
            $stmt = $pdo->prepare("
                UPDATE users SET username=?, first_name=?, last_name=?, email=?, date_of_birth=?, role=?, photo=? 
                WHERE id=?
            ");
            $stmt->execute([$username, $first_name, $last_name, $email, $date_of_birth, $role, $photoData, $user_id]);
        } else {
            $stmt = $pdo->prepare("
                UPDATE users SET username=?, first_name=?, last_name=?, email=?, date_of_birth=?, role=? 
                WHERE id=?
            ");
            $stmt->execute([$username, $first_name, $last_name, $email, $date_of_birth, $role, $user_id]);
        }

        $message = "User updated successfully";
        $message_type = "success";
    }
}


// ===================================================
// CHANGE PASSWORD
// ===================================================
if (isset($_POST['update_password'])) {
    $user_id = $_POST['user_id'];
    $new_password = $_POST['new_password'];
    $confirm = $_POST['confirm_password'];

    if ($new_password !== $confirm) {
        $message = "Passwords do not match!";
        $message_type = "danger";
    } elseif (strlen($new_password) < 6) {
        $message = "Password must be at least 6 characters!";
        $message_type = "danger";
    } else {
        $hashed = password_hash($new_password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET password=? WHERE id=?");
        $stmt->execute([$hashed, $user_id]);

        $message = "Password updated!";
        $message_type = "success";
    }
}


// ===================================================
// UPDATE SUBJECT
// ===================================================
if (isset($_POST['update_subject'])) {
    $subject_id  = $_POST['subject_id'];
    $name        = trim($_POST['name']);
    $code        = trim($_POST['code']);
    $description = trim($_POST['description']);

    $check = $pdo->prepare("SELECT id FROM subjects WHERE code=? AND id!=?");
    $check->execute([$code, $subject_id]);

    if ($check->rowCount() > 0) {
        $message = "Subject code already exists!";
        $message_type = "danger";
    } else {
        $stmt = $pdo->prepare("
            UPDATE subjects SET name=?, code=?, description=? WHERE id=?
        ");
        $stmt->execute([$name, $code, $description, $subject_id]);

        $message = "Subject updated!";
        $message_type = "success";
    }
}


// ===================================================
// DELETE ACTIONS
// ===================================================
if (isset($_GET['action'], $_GET['id'])) {
    $action = $_GET['action'];
    $id     = $_GET['id'];

    switch ($action) {
        case 'delete_user':      $result = deleteUser($pdo, $id); break;
        case 'delete_subject':   $result = deleteSubject($pdo, $id); break;
        case 'delete_classroom': $result = deleteClassroom($pdo, $id); break;
        default: $result = false;
    }

    if ($result === true) {
        $message = ucfirst(str_replace('_', ' ', $action)) . " deleted!";
        $message_type = "success";
    } else {
        $message = $result ?: "Error deleting!";
        $message_type = "danger";
    }
}


// ===================================================
// CLASS PROMOTION
// ===================================================
if (isset($_POST['promote_class']) && isset($_POST['classroom_id'])) {
    $classroom_id = $_POST['classroom_id'];

    // Get class info
    $stmt = $pdo->prepare("SELECT * FROM classrooms WHERE id = ?");
    $stmt->execute([$classroom_id]);
    $current_class = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$current_class) {
        $message = "Class not found!";
        $message_type = "danger";
    } else {
        $current_level = $current_class['class_level'];
        $current_name  = $current_class['name'];

        $map = [
            'JSS1' => 'JSS2',
            'JSS2' => 'JSS3',
            'JSS3' => 'SSS1',
            'SSS1' => 'SSS2',
            'SSS2' => 'SSS3',
            'SSS3' => 'Alumni'
        ];

        if (!isset($map[$current_level])) {
            $message = "This class cannot be promoted further.";
            $message_type = "danger";
        } else {
            $next_level = $map[$current_level];
            $next_name  = str_replace($current_level, $next_level, $current_name);

            // Check if next class exists
            $stmt = $pdo->prepare("SELECT * FROM classrooms WHERE name=?");
            $stmt->execute([$next_name]);
            $next_class = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$next_class) {
                $message = "Next class <b>$next_name</b> does not exist.";
                $message_type = "danger";
            } else {
                // Get students in class
                $stmt = $pdo->prepare("SELECT student_id FROM classroom_students WHERE classroom_id=?");
                $stmt->execute([$classroom_id]);
                $students = $stmt->fetchAll(PDO::FETCH_COLUMN);

                if (empty($students)) {
                    $message = "No students to promote!";
                    $message_type = "warning";
                } else {
                    foreach ($students as $sid) {
                        // Update user
                        $pdo->prepare("UPDATE users SET current_class=?, class_level=? WHERE id=?")
                            ->execute([$next_name, $next_level, $sid]);

                        // Move to new class
                        $pdo->prepare("DELETE FROM classroom_students WHERE classroom_id=? AND student_id=?")
                            ->execute([$classroom_id, $sid]);

                        $pdo->prepare("
                            INSERT INTO classroom_students (classroom_id, class_level, student_id)
                            VALUES (?, ?, ?)
                        ")->execute([$next_class['id'], $next_level, $sid]);
                    }

                    $message = "Students promoted to <b>$next_name</b>!";
                    $message_type = "success";
                }
            }
        }
    }
}


// ===================================================
// SESSION & TERM MANAGEMENT
// ===================================================
$sessions = $pdo->query("SELECT * FROM sessions ORDER BY id DESC")->fetchAll();
$active_session = $pdo->query("SELECT * FROM sessions WHERE is_active = 1 LIMIT 1")->fetch();

$terms = [];
if ($active_session) {
    $stmt = $pdo->prepare("SELECT * FROM terms WHERE session_id = ?");
    $stmt->execute([$active_session['id']]);
    $terms = $stmt->fetchAll();
}

// Add session
if (isset($_POST['add_session'])) {
    $pdo->prepare("
        INSERT INTO sessions (name, start_date, end_date)
        VALUES (?, ?, ?)
    ")->execute([$_POST['session_name'], $_POST['start_date'], $_POST['end_date']]);
}

// Activate session
if (isset($_POST['activate_session'])) {
    $pdo->exec("UPDATE sessions SET is_active = 0");
    $pdo->prepare("UPDATE sessions SET is_active = 1 WHERE id=?")
        ->execute([$_POST['session_id']]);
}

// Add term
if (isset($_POST['add_term']) && $active_session) {
    $pdo->prepare("INSERT INTO terms (session_id, name) VALUES (?, ?)")
        ->execute([$active_session['id'], $_POST['term_name']]);
}

// Activate term
if (isset($_POST['activate_term'])) {
    $pdo->prepare("UPDATE terms SET is_active = 0 WHERE session_id=?")
        ->execute([$active_session['id']]);

    $pdo->prepare("UPDATE terms SET is_active = 1 WHERE id=?")
        ->execute([$_POST['term_id']]);
}


// ===================================================
// DASHBOARD DATA
// ===================================================
$total_students  = $pdo->query("SELECT COUNT(*) FROM users WHERE role='student'")->fetchColumn();
$total_teachers  = $pdo->query("SELECT COUNT(*) FROM users WHERE role='teacher'")->fetchColumn();
$total_classrooms = $pdo->query("SELECT COUNT(*) FROM classrooms")->fetchColumn();
$total_subjects   = $pdo->query("SELECT COUNT(*) FROM subjects")->fetchColumn();

$users = $pdo->query("SELECT * FROM users ORDER BY role, first_name")->fetchAll();
$subjects = $pdo->query("SELECT * FROM subjects ORDER BY name")->fetchAll();
$classrooms = $pdo->query("
    SELECT c.*, u.first_name, u.last_name
    FROM classrooms c
    LEFT JOIN users u ON c.teacher_id = u.id
    ORDER BY c.name
")->fetchAll();


// ===================================================
// ASSIGN SUBJECTS TO CLASS
// ===================================================
$selected_class_id = $_POST['classroom_id'] ?? 0;
$success_message = $error_message = "";

if (isset($_POST['assign_subjects'])) {
    $subject_ids = $_POST['subject_ids'] ?? [];

    if ($selected_class_id && !empty($subject_ids)) {
        $pdo->beginTransaction();
        try {
            $pdo->prepare("DELETE FROM class_subjects WHERE classroom_id=?")
                ->execute([$selected_class_id]);

            $stmt = $pdo->prepare("
                INSERT INTO class_subjects (classroom_id, subject_id)
                VALUES (?, ?)
            ");

            foreach ($subject_ids as $sid) {
                $stmt->execute([$selected_class_id, $sid]);
            }

            $pdo->commit();
            $success_message = "Subjects assigned!";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "Error: " . $e->getMessage();
        }
    } else {
        $error_message = "Select a class and at least one subject.";
    }
}

// Current subjects for selected class
$current_subjects = [];
if ($selected_class_id) {
    $stmt = $pdo->prepare("
        SELECT subject_id FROM class_subjects WHERE classroom_id=?
    ");
    $stmt->execute([$selected_class_id]);
    $current_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
}


// ===================================================
// ASSIGN TEACHER TO SUBJECT
// ===================================================
if (isset($_POST['assign_subject'])) {
    $teacher_id = $_POST['teacher_id'];
    $subject_id = $_POST['subject_id'];

    // Prevent duplicates
    $check = $pdo->prepare("
        SELECT id FROM teacher_subjects WHERE teacher_id=? AND subject_id=?
    ");
    $check->execute([$teacher_id, $subject_id]);

    if ($check->rowCount() > 0) {
        $message = "Teacher already assigned to this subject.";
        $message_type = "warning";
    } else {
        $pdo->prepare("
            INSERT INTO teacher_subjects (teacher_id, subject_id)
            VALUES (?, ?)
        ")->execute([$teacher_id, $subject_id]);

        $message = "Subject assigned to teacher!";
        $message_type = "success";
    }
}

// Data for teacher assign form
$teachers = $pdo->query("SELECT id, first_name, last_name FROM users WHERE role='teacher'")->fetchAll();
$subjects = $pdo->query("SELECT id, name, code FROM subjects ORDER BY name")->fetchAll();

$assigned = $pdo->query("
    SELECT ts.id, u.first_name, u.last_name, s.name AS subject_name, s.code
    FROM teacher_subjects ts
    JOIN users u ON ts.teacher_id = u.id
    JOIN subjects s ON ts.subject_id = s.id
    ORDER BY u.first_name
")->fetchAll();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" sizes="32x32" href="BCA-Logo.png">
    <link rel="icon" type="image/png" sizes="16x16" href="BCA-Logo.png">
    <title>Admin Dashboard - Bethany Christian Academy</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="major.css" rel="stylesheet">
    <style>
        .sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            min-height: 100vh;
            padding: 0;
            font-size: 12px;
        }
        .sidebar .nav-link {
            color: white;
            padding: 0.5rem 0.5rem;
            border-left: 4px solid transparent;
        }
        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            background: rgba(255,255,255,0.1);
            border-left-color: white;
        }
        .stat-card {
            border-radius: 10px;
            border: none;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .password-toggle {
            cursor: pointer;
            transition: color 0.3s;
        }
        .password-toggle:hover {
            color: #667eea !important;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="d-flex flex-column p-3">
                    <div class="text-center mb-4">
                        <a href="../"><img src="BCA-Logo.png" alt="BCA LOGO" height="100px" width="100px"></a>
                        <h5>Bethany Christian Academy</h5>
                        <small>Administrator Dashboard</small>
                    </div>
                    
                    <ul class="nav nav-pills flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="#dashboard" data-bs-toggle="tab">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="mail/dashboard.php">
                                <i class="fas fa-envelope me-2"></i>Mail
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#users" data-bs-toggle="tab">
                                <i class="fas fa-users me-2"></i>Manage Users
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#subjects" data-bs-toggle="tab">
                                <i class="fas fa-book me-2"></i>Subjects
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="classroom.php">
                                <i class="fas fa-chalkboard me-2"></i>Classrooms
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#sessions" data-bs-toggle="tab">
                                <i class="fas fa-calendar-alt me-2"></i>Sessions & Terms
                            </a>
                        </li>

                        <li class="nav-item">
                            <a class="nav-link" href="assign_students_subjects.php">
                                <i class="fas fa-user-plus me-2" ></i>Assign Students Subjects
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="assign_subjects_class.php">
                                <i class="fas fa-chalkboard me-2"></i>Assign Class Subjects
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="assign_teacher_classroom.php">
                                <i class="fas fa-user-tie me-2"></i>Assign Teacher to Classroom
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="assign_teacher_subjects.php">
                                <i class="fas fa-user-tie me-2"></i>Assign subjects to teachers
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/BCA/student-grades-management-system/CBT-EXAM/admin/manage_exam.php">
                                <i class="fas fa-edit me-2"></i>Computer-Based Exam
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="logout.php">
                                <i class="fas fa-sign-out-alt me-2"></i>Logout
                            </a>
                        </li>
                        <button id="themeToggle" class="toggle-btn">
                            <i class="fas fa-moon"></i> <div>Dark Mode</div>
                        </button>
                    </ul>
                    <script src="dark.js"></script>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 ms-sm-auto px-4 py-4">
                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="tab-content">
                    <!-- Dashboard Tab -->
                    <div class="tab-pane fade show active" id="dashboard">
                        <div class="d-flex justify-content-between align-items-center mb-4 student-inner">
                            <h2>Admin Dashboard</h2>
                            <div class="d-flex align-items-center mb-4 p-3 bg-white rounded shadow-sm border">
                                <div class="me-3">
                                        <?php if (!empty($user['photo'])): ?>
                                        <img src="data:image/jpeg;base64,<?php echo $photo_src; ?>" 
                                        alt="User Photo" 
                                        style="width:40px; height:40px; border-radius:50%; object-fit:cover;">
                                        <?php else: ?>
                                        <img src="user.png" 
                                        alt="Default Photo" 
                                        style="width:40px; height:40px; border-radius:50%; object-fit:cover;">
                                            <?php endif; ?>
                                </div>
                                <div>
                                    <h5 class="mb-1 fw-bold text-primary">
                                        <?= htmlspecialchars($_SESSION['first_name'] . ' ' . $_SESSION['last_name']) ?>
                                    </h5>
                                </div>
                            </div>
                        </div>

                        <!-- Statistics Cards -->
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="card stat-card bg-primary text-white">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h4><?php echo $total_students; ?></h4>
                                                <p>Total Students</p>
                                            </div>
                                            <i class="fas fa-user-graduate fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card stat-card bg-success text-white">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h4><?php echo $total_teachers; ?></h4>
                                                <p>Total Teachers</p>
                                            </div>
                                            <i class="fas fa-chalkboard-teacher fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card stat-card bg-warning text-dark">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h4><?php echo $total_classrooms; ?></h4>
                                                <p>Classrooms</p>
                                            </div>
                                            <i class="fas fa-chalkboard fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card stat-card bg-info text-white">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <div>
                                                <h4><?php echo $total_subjects; ?></h4>
                                                <p>Subjects</p>
                                            </div>
                                            <i class="fas fa-book fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Recent Activity -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="col-md-12">
                        <div class="card ">
                            <div class="card-header">
                                <h5>Recent Users</h5>
                            </div>
                            <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-sm" id="active-users-table">
                                                <thead>
                                                    <tr>
                                                        <th>Photo</th>
                                                        <th>Name</th>
                                                        <th>Role</th>
                                                        <th>Last Login</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                   <?php
                                                    // Fetch last 5 logged in users
                                                    $stmt = $pdo->query("SELECT * FROM users ORDER BY last_login DESC LIMIT 5");
                                                    $recentUsers = $stmt->fetchAll();
                                                    
                                                    foreach ($recentUsers as $user):
                                                    ?>
                                                    <tr>
                                                        <td>
                                                            <?php if (!empty($user['photo'])): ?>
                                                                <img src="data:image/jpeg;base64,<?= base64_encode($user['photo']); ?>" 
                                                                    alt="User Photo" 
                                                                    style="width:40px; height:40px; border-radius:50%; object-fit:cover;">
                                                            <?php else: ?>
                                                                <img src="user.png" 
                                                                    alt="Default Photo" 
                                                                    style="width:40px; height:40px; border-radius:50%; object-fit:cover;">
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></td>
                                                        <td><span class="badge bg-success"><?= htmlspecialchars($user['role']); ?></span></td>
                                                        <td><?= formatLastLogin($user['last_login']); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    <?php if (empty($activeUsers)): ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>


                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5>Classrooms Overview</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Classroom</th>
                                                        <th>Teacher</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach(array_slice($classrooms, 0, 5) as $classroom): ?>
                                                    <tr>
                                                        <td><?php echo $classroom['name']; ?></td>
                                                        <td><?php echo $classroom['first_name'] . ' ' . $classroom['last_name']; ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Users Tab -->
                    <div class="tab-pane fade" id="users">
                        <h2 class="mb-4">Manage Users</h2>
                        
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5>Add New User</h5>
                            </div>
                            <div class="card-body">
                                <form method="POST" enctype="multipart/form-data">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <input type="text" class="form-control mb-3" name="first_name" placeholder="First Name" required>
                                        </div>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control mb-3" name="last_name" placeholder="Last Name" required>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <input type="text" class="form-control mb-3" name="username" placeholder="Username" required>
                                        </div>
                                        <div class="col-md-4">
                                            <input type="email" class="form-control mb-3" name="email" placeholder="Email">
                                        </div>
                                        <div class="col-md-4">
                                            <select class="form-select mb-3" name="role" required>
                                                <option value="">Select Role</option>
                                                <option value="admin">Admin</option>
                                                <option value="teacher">Teacher</option>
                                                <option value="student">Student</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                        <label for="photo" class="form-label">Profile Photo</label>
                                            <input type="file" name="photo" id="photo" class="form-control" accept="image/*">
                                        </div>
                                        <div class="col-md-6">
                                            <label for="photo" class="form-label">Date of birth</label>
                                            <input type="date" class="form-control mb-3" name="date_of_birth" placeholder="Date of birth">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="input-group mb-3">
                                                <input type="password" class="form-control" name="password" id="new_password" placeholder="Password" required>
                                                <span class="input-group-text password-toggle" onclick="togglePassword('new_password', 'new_password_icon')">
                                                    <i class="fas fa-eye" id="new_password_icon"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <button type="submit" name="add_user" class="btn btn-primary w-100">Add User</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5>All Users</h5>
                                <input type="text" id="userSearch" class="form-control form-control-sm w-50" placeholder="Search users...">
                            </div>
                            <div class="card-body">
                                <div class="table-responsive" id="userTableContainer">
                                    <!-- Table will load here dynamically -->
                                </div>
                            </div>
                        </div>

                        <script>
                        // Load all users initially
                        function loadUsers(query = '') {
                            fetch('search_users.php?q=' + encodeURIComponent(query))
                                .then(response => response.text())
                                .then(data => {
                                    document.getElementById('userTableContainer').innerHTML = data;
                                });
                        }

                        // Initial load
                        loadUsers();

                        // Search event
                        document.getElementById('userSearch').addEventListener('keyup', function() {
                            const query = this.value.trim();
                            loadUsers(query);
                        });
                        </script>
                    </div>

                    <!-- Subjects Tab -->
                    <div class="tab-pane fade" id="subjects">
                        <h2 class="mb-4">Manage Subjects</h2>
                        
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5>Add New Subject</h5>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <input type="text" class="form-control mb-3" name="name" placeholder="Subject Name" required>
                                        </div>
                                        <div class="col-md-4">
                                            <input type="text" class="form-control mb-3" name="code" placeholder="Subject Code" required>
                                        </div>
                                        <div class="col-md-4">
                                            <input type="text" class="form-control mb-3" name="description" placeholder="Description">
                                        </div>
                                    </div>
                                    <button type="submit" name="add_subject" class="btn btn-primary">Add Subject</button>
                                </form>
                            </div>
                        </div>

                        <div class="card">
                            <div class="card-header">
                                <h5>All Subjects</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Name</th>
                                                <th>Code</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach($subjects as $subject): ?>
                                            <tr>
                                                <td><?php echo $subject['id']; ?></td>
                                                <td><?php echo $subject['name']; ?></td>
                                                <td><?php echo $subject['code']; ?></td>
                                                <td>
                                                    <button class="btn btn-sm-primary" data-bs-toggle="modal" data-bs-target="#editSubjectModal"
                                                            data-id="<?php echo $subject['id']; ?>"
                                                            data-name="<?php echo $subject['name']; ?>"
                                                            data-code="<?php echo $subject['code']; ?>">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <a href="?action=delete_subject&id=<?php echo $subject['id']; ?>" 
                                                       class="btn btn-sm-danger"
                                                       onclick="return confirm('Are you sure you want to delete this subject? This will also delete all grades associated with it.')">
                                                        <i class="fas fa-trash"></i> 
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Assign Teacher to Subject Tab -->
                    <div class="tab-pane fade" id="assign_teacher_subject">
                        <h2 class="mb-4">Assign Teacher to Subject</h2>
                        <div class="container mt-5">
                                <!-- Assignment Form -->
                                <div class="card mb-4">
                                    <div class="card-header bg-primary text-white">Assign a Teacher</div>
                                    <div class="card-body">
                                        <form method="POST" class="row g-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Teacher</label>
                                                <select name="teacher_id" class="form-select" required>
                                                    <option value="">Select teacher...</option>
                                                    <?php foreach ($teachers as $t): ?>
                                                        <option value="<?= $t['id'] ?>"><?= $t['first_name'].' '.$t['last_name'] ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Subject</label>
                                                <select name="subject_id" class="form-select" required>
                                                    <option value="">Select subject...</option>
                                                    <?php foreach ($subjects as $s): ?>
                                                        <option value="<?= $s['id'] ?>"><?= $s['name'].' ('.$s['code'].')' ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-12">
                                                <button type="submit" name="assign_subject" class="btn btn-success"><i class="fas fa-plus-circle"></i> Assign Subject</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>

                                <!-- Assigned Teachers Table -->
                                <div class="card">
                                    <div class="card-header bg-info text-white">Assigned Teachers</div>
                                    <div class="card-body table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Teacher</th>
                                                    <th>Subject</th>
                                                    <th>Code</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (count($assigned) > 0): ?>
                                                    <?php foreach ($assigned as $i => $row): ?>
                                                        <tr>
                                                            <td><?= $i+1 ?></td>
                                                            <td><?= $row['first_name'].' '.$row['last_name'] ?></td>
                                                            <td><?= $row['subject_name'] ?></td>
                                                            <td><?= $row['code'] ?></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr><td colspan="4" class="text-center">No teachers assigned yet.</td></tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

                            </div>
                    </div>


                    <!-- Sessions and Terms management-->
                    <div class="tab-pane fade" id="sessions">
                    <h2 class="mb-4">Manage Academic Sessions & Terms</h2>

                    <!-- Create new session -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5>Create New Session</h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <div class="row">
                                    <div class="col-md-6">
                                        <input type="text" name="session_name" class="form-control mb-3" placeholder="Session Name" required>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="date" name="start_date" class="form-control mb-3" placeholder="Start Date" required>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="date" name="end_date" class="form-control mb-3" placeholder="End Date" required>
                                    </div>
                                </div>
                                <button type="submit" name="add_session" class="btn btn-primary">Add Session</button>
                            </form>
                        </div>
                    </div>

                    <!-- List sessions -->
                    <div class="card">
                        <div class="card-header">
                            <h5>All Sessions</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Duration</th>
                                        <th>Current Session</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($sessions as $s): ?>
                                    <tr>
                                        <td><?= $s['id']; ?></td>
                                        <td><?= htmlspecialchars($s['name']); ?></td>
                                        <td><?= $s['start_date']; ?> - <?= $s['end_date']; ?></td>
                                        <td><?= $s['is_active'] ? '<span class="badge bg-success">Active</span>' : ''; ?></td>
                                        <td>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="session_id" value="<?= $s['id']; ?>">
                                                <button type="submit" name="activate_session" class="btn btn-sm btn-outline-primary">
                                                    Set Active
                                                </button>
                                            </form>
                                            <a href="?delete_session=<?= $s['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this session?')">Delete</a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Terms for current session -->
                    <?php if($active_session): ?>
                    <div class="card mt-4">
                        <div class="card-header">
                            <h5>Manage Terms for <?= htmlspecialchars($active_session['name']); ?></h5>
                        </div>
                        <div class="card-body">
                            <form method="POST" class="mb-3">
                                <div class="row">
                                    <div class="col-md-8">
                                        <input type="text" name="term_name" class="form-control mb-3" placeholder="Term Name (e.g. First Term)" required>
                                    </div>
                                    <div class="col-md-4">
                                        <button type="submit" name="add_term" class="btn btn-primary w-100">Add Term</button>
                                    </div>
                                </div>
                            </form>

                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Term</th>
                                        <th>Active</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($terms as $t): ?>
                                    <tr>
                                        <td><?= $t['id']; ?></td>
                                        <td><?= htmlspecialchars($t['name']); ?></td>
                                        <td><?= $t['is_active'] ? '<span class="badge bg-success">Active</span>' : ''; ?></td>
                                        <td>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="term_id" value="<?= $t['id']; ?>">
                                                <button type="submit" name="activate_term" class="btn btn-sm btn-outline-primary">Set Active</button>
                                            </form>
                                            <a href="?delete_term=<?= $t['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this term?')">Delete</a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                    <!-- Classrooms Tab -->
                    <div class="tab-pane fade" id="classrooms">
                        <h2 class="mb-4">Manage Classrooms</h2>
                        
                        <div class="card">
                            <div class="card-header">
                                <h5>All Classrooms</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Name</th>
                                                <th>Description</th>
                                                <th>Teacher</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach($classrooms as $classroom): ?>
                                            <tr>
                                                <td><?php echo $classroom['id']; ?></td>
                                                <td><?php echo $classroom['name']; ?></td>
                                                <td><?php echo $classroom['description']; ?></td>
                                                <td><?php echo $classroom['first_name'] . ' ' . $classroom['last_name']; ?></td>
                                                <td>
                                                    <button class="btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-edit"></i> Edit
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-info">
                                                        <i class="fas fa-users"></i> View Students
                                                    </button>
                                                    <form method="POST" style="display:inline;">
                                                        <input type="hidden" name="classroom_id" value="<?php echo $classroom['id']; ?>">
                                                        <button type="submit" name="promote_class" 
                                                                class="btn btn-sm btn-outline-success"
                                                                onclick="return confirm('Are you sure you want to promote all students in this class?')">
                                                            Promote
                                                        </button>
                                                    </form>
                                                    <a href="?action=delete_classroom&id=<?php echo $classroom['id']; ?>" 
                                                       class="btn btn-sm btn-outline-danger"
                                                       onclick="return confirm('Are you sure you want to delete this classroom? This will also delete all grades and student associations.')">
                                                        <i class="fas fa-trash"></i> Delete
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                    <!-- Footer -->
                    <footer class="mt-5">
                        <div class="container py-3 d-flex flex-column flex-md-row justify-content-between align-items-center">
                            <div>
                                &copy; <?= date('Y') ?> Bethany Christian Academy *Designed by Peter Danye. All rights reserved.
                            </div>
                            <div>
                                <a href="#" class="text-decoration-none me-3">Privacy Policy</a>
                                <a href="#" class="text-decoration-none">Terms of Service</a>
                            </div>
                        </div>
                    </footer>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">Edit User</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>

                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        <input type="hidden" name="user_id" id="edit_user_id">
                        <input type="hidden" id="edit_user_status">

                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" class="form-control" name="username" id="edit_username" required>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">First Name</label>
                                <input type="text" class="form-control" name="first_name" id="edit_first_name" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Last Name</label>
                                <input type="text" class="form-control" name="last_name" id="edit_last_name" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Profile Photo</label>
                            <input type="file" name="photo" class="form-control" accept="image/*">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" id="edit_email">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Birth Date</label>
                            <input type="date" class="form-control" name="date_of_birth" id="edit_date_of_birth">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Role</label>
                            <select class="form-select" name="role" id="edit_role" required>
                                <option value="admin">Admin</option>
                                <option value="teacher">Teacher</option>
                                <option value="student">Student</option>
                            </select>
                        </div>

                        <!-- Account Status -->
                        <div class="alert alert-warning d-flex justify-content-between align-items-center">
                            <span>Account Status: <strong id="statusLabel"></strong></span>
                            <button type="button" id="toggleStatusBtn" class="btn btn-sm"></button>
                        </div>

                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            Cancel
                        </button>
                        <button type="submit" name="update_user" class="btn btn-primary">
                            Update User
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <!-- Change Password Modal -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Change Password</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="user_id" id="password_user_id">
                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" class="form-control" id="password_username" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">New Password</label>
                            <div class="input-group">
                                <input type="password" class="form-control" name="new_password" id="change_password" required>
                                <span class="input-group-text password-toggle" onclick="togglePassword('change_password', 'change_password_icon')">
                                    <i class="fas fa-eye" id="change_password_icon"></i>
                                </span>
                            </div>
                            <div class="form-text">Password must be at least 6 characters long.</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Confirm Password</label>
                            <div class="input-group">
                                <input type="password" class="form-control" name="confirm_password" id="confirm_password" required>
                                <span class="input-group-text password-toggle" onclick="togglePassword('confirm_password', 'confirm_password_icon')">
                                    <i class="fas fa-eye" id="confirm_password_icon"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="update_password" class="btn btn-primary">Change Password</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Subject Modal -->
    <div class="modal fade" id="editSubjectModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Subject</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="subject_id" id="edit_subject_id">
                        <div class="mb-3">
                            <label class="form-label">Subject Name</label>
                            <input type="text" class="form-control" name="name" id="edit_subject_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Subject Code</label>
                            <input type="text" class="form-control" name="code" id="edit_subject_code" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <input type="text" class="form-control" name="description" id="edit_subject_description">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="update_subject" class="btn btn-primary">Update Subject</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Activate tab from URL hash
        document.addEventListener('DOMContentLoaded', function() {
            var triggerTabList = [].slice.call(document.querySelectorAll('a[data-bs-toggle="tab"]'))
            triggerTabList.forEach(function (triggerEl) {
                var tabTrigger = new bootstrap.Tab(triggerEl)
                triggerEl.addEventListener('click', function (event) {
                    event.preventDefault()
                    tabTrigger.show()
                })
            });

            // Edit User Modal
            var editUserModal = document.getElementById('editUserModal');

            editUserModal.addEventListener('show.bs.modal', function (event) {
                var button = event.relatedTarget;

                // Fetch user data from data-* attributes
                var userId = button.getAttribute('data-id');
                var username = button.getAttribute('data-username');
                var firstName = button.getAttribute('data-firstname');
                var lastName = button.getAttribute('data-lastname');
                var email = button.getAttribute('data-email');
                var date_of_birth = button.getAttribute('data-date_of_birth');
                var role = button.getAttribute('data-role');
                var status = button.getAttribute('data-status'); // Add this attribute to your table row

                var modal = this;
                modal.querySelector('#edit_user_id').value = userId;
                modal.querySelector('#edit_username').value = username;
                modal.querySelector('#edit_first_name').value = firstName;
                modal.querySelector('#edit_last_name').value = lastName;
                modal.querySelector('#edit_email').value = email;
                modal.querySelector('#edit_date_of_birth').value = date_of_birth;
                modal.querySelector('#edit_role').value = role;
                modal.querySelector('#edit_user_status').value = status;

                // Status label and toggle button
                var statusLabel = modal.querySelector('#statusLabel');
                var toggleBtn = modal.querySelector('#toggleStatusBtn');
                statusLabel.textContent = status.toUpperCase();

                // Prevent self-disable (replace 1 with current logged-in user ID)
                var currentUserId = <?= (int)$_SESSION['user_id'] ?>;
                if (parseInt(userId) === currentUserId) {
                    toggleBtn.style.display = 'none';
                } else {
                    toggleBtn.style.display = 'inline-block';
                    if (status === 'active') {
                        toggleBtn.textContent = 'Disable Account';
                        toggleBtn.className = 'btn btn-danger btn-sm';
                        toggleBtn.onclick = function() { toggleUser(userId, 'disable'); };
                    } else {
                        toggleBtn.textContent = 'Enable Account';
                        toggleBtn.className = 'btn btn-success btn-sm';
                        toggleBtn.onclick = function() { toggleUser(userId, 'enable'); };
                    }
                }
            });

            // Function to redirect to toggle_user.php
            function toggleUser(userId, action) {
                if (!confirm(`Are you sure you want to ${action} this account?`)) {
                    return;
                }
                window.location.href = `toggle_user.php?id=${userId}&action=${action}`;
            }


            // Change Password Modal
            var changePasswordModal = document.getElementById('changePasswordModal')
            changePasswordModal.addEventListener('show.bs.modal', function (event) {
                var button = event.relatedTarget
                var userId = button.getAttribute('data-id')
                var username = button.getAttribute('data-username')
                
                var modal = this
                modal.querySelector('#password_user_id').value = userId
                modal.querySelector('#password_username').value = username
            })

            // Edit Subject Modal
            var editSubjectModal = document.getElementById('editSubjectModal')
            editSubjectModal.addEventListener('show.bs.modal', function (event) {
                var button = event.relatedTarget
                var subjectId = button.getAttribute('data-id')
                var name = button.getAttribute('data-name')
                var code = button.getAttribute('data-code')
                var description = button.getAttribute('data-description')
                
                var modal = this
                modal.querySelector('#edit_subject_id').value = subjectId
                modal.querySelector('#edit_subject_name').value = name
                modal.querySelector('#edit_subject_code').value = code
                modal.querySelector('#edit_subject_description').value = description
            })
        });

        // Password toggle functionality
        function togglePassword(passwordFieldId, iconId) {
            var passwordField = document.getElementById(passwordFieldId);
            var icon = document.getElementById(iconId);
            
            if (passwordField.type === "password") {
                passwordField.type = "text";
                icon.classList.remove("fa-eye");
                icon.classList.add("fa-eye-slash");
            } else {
                passwordField.type = "password";
                icon.classList.remove("fa-eye-slash");
                icon.classList.add("fa-eye");
            }
        }

        // Password strength indicator (optional enhancement)
        function checkPasswordStrength(password) {
            var strength = 0;
            if (password.length >= 6) strength++;
            if (password.match(/[a-z]+/)) strength++;
            if (password.match(/[A-Z]+/)) strength++;
            if (password.match(/[0-9]+/)) strength++;
            if (password.match(/[$@#&!]+/)) strength++;
            
            return strength;
        }
    </script>
</body>
</html>