<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Teachers Management
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();

requireAdmin();

if (isPost()) { requireCsrf(); }

$success = flash('success') ?: '';
$error = '';
$admin = currentAdmin($pdo);

if (isPost()) {
    requireCsrf();
    $action = (string)($_POST['action'] ?? '');

    try {
        if ($action === 'add_teacher') {
            $fullName = trim((string)($_POST['full_name'] ?? ''));
            $email = strtolower(trim((string)($_POST['email'] ?? '')));
            $password = (string)($_POST['password'] ?? '');
            $whatsapp = trim((string)($_POST['whatsapp'] ?? ''));
            $status = (string)($_POST['status'] ?? 'active');

            if ($fullName === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new RuntimeException('Enter a valid teacher name and email.');
            }
            if (strlen($password) < 10) {
                throw new RuntimeException('The temporary password must contain at least 10 characters.');
            }
            if (!in_array($status, ['active', 'inactive'], true)) {
                throw new RuntimeException('Invalid teacher status.');
            }
            if (safeFetch($pdo, 'SELECT id FROM core_teachers WHERE LOWER(email)=LOWER(?) LIMIT 1', [$email])) {
                throw new RuntimeException('This email is already registered.');
            }

            mustExecute(
                $pdo,
                'INSERT INTO core_teachers (name,full_name,email,password,whatsapp,status,created_at) VALUES (?,?,?,?,?,?,NOW())',
                [$fullName, $fullName, $email, password_hash($password, PASSWORD_DEFAULT), $whatsapp ?: null, $status]
            );
            logActivity($pdo, 'admin', (int)($admin['id'] ?? 0), 'Teacher created', 'Created teacher: ' . $email);
            flash('success', 'Teacher account created successfully.');
            redirect('admin/teachers.php');
        }

        if ($action === 'toggle_status') {
            $teacherId = (int)($_POST['teacher_id'] ?? 0);
            $teacherRow = safeFetch($pdo, 'SELECT id,status FROM core_teachers WHERE id=?', [$teacherId]);
            if (!$teacherRow) {
                throw new RuntimeException('Teacher not found.');
            }
            $newStatus = $teacherRow['status'] === 'active' ? 'inactive' : 'active';
            mustExecute($pdo, 'UPDATE core_teachers SET status=? WHERE id=?', [$newStatus, $teacherId]);
            logActivity($pdo, 'admin', (int)($admin['id'] ?? 0), 'Teacher status changed', 'Teacher ID ' . $teacherId . ' set to ' . $newStatus);
            flash('success', 'Teacher status updated.');
            redirect('admin/teachers.php');
        }

        if ($action === 'reset_password') {
            $teacherId = (int)($_POST['teacher_id'] ?? 0);
            $password = (string)($_POST['new_password'] ?? '');
            if ($teacherId <= 0 || strlen($password) < 10) {
                throw new RuntimeException('Select a teacher and use a password of at least 10 characters.');
            }
            if (!safeFetch($pdo, 'SELECT id FROM core_teachers WHERE id=?', [$teacherId])) {
                throw new RuntimeException('Teacher not found.');
            }
            mustExecute($pdo, 'UPDATE core_teachers SET password=? WHERE id=?', [password_hash($password, PASSWORD_DEFAULT), $teacherId]);
            logActivity($pdo, 'admin', (int)($admin['id'] ?? 0), 'Teacher password reset', 'Teacher ID ' . $teacherId);
            flash('success', 'Teacher password reset successfully.');
            redirect('admin/teachers.php');
        }

        if ($action === 'delete') {
            $teacherId = (int)($_POST['delete_id'] ?? 0);
            if ($teacherId <= 0) {
                throw new RuntimeException('Invalid teacher.');
            }
            $related = 0;
            foreach (['core_courses' => 'teacher_id', 'core_sessions' => 'teacher_id', 'core_materials' => 'teacher_id', 'core_homework' => 'teacher_id', 'core_exams' => 'teacher_id'] as $table => $column) {
                if (tableExists($pdo, $table) && columnExists($pdo, $table, $column)) {
                    $related += safeCount($pdo, "SELECT COUNT(*) FROM `$table` WHERE `$column`=?", [$teacherId]);
                }
            }
            if ($related > 0) {
                throw new RuntimeException('This teacher has academic records. Disable the account instead of deleting it.');
            }
            mustExecute($pdo, 'DELETE FROM core_teachers WHERE id=?', [$teacherId]);
            logActivity($pdo, 'admin', (int)($admin['id'] ?? 0), 'Teacher deleted', 'Deleted teacher ID ' . $teacherId);
            flash('success', 'Teacher deleted successfully.');
            redirect('admin/teachers.php');
        }
    } catch (Throwable $e) {
        error_log('[SMI teachers] ' . $e->getMessage());
        $error = APP_DEBUG ? $e->getMessage() : $e->getMessage();
    }
}

/*
|--------------------------------------------------------------------------
| Search
|--------------------------------------------------------------------------
*/

$search =
    trim($_GET['search'] ?? '');

$teachers = [];

if ($search !== '') {

    $stmt = $pdo->prepare("

        SELECT *
        FROM core_teachers

        WHERE
            full_name LIKE ?
            OR email LIKE ?

        ORDER BY id DESC

    ");

    $stmt->execute([

        "%{$search}%",
        "%{$search}%"

    ]);

} else {

    $stmt = $pdo->query("

        SELECT *
        FROM core_teachers

        ORDER BY id DESC

    ");
}

$teachers =
    $stmt->fetchAll();

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta
name="viewport"
content="width=device-width, initial-scale=1.0">

<title>
Teachers Management
</title>

<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
rel="stylesheet">

<style>

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body{
    font-family:'Inter',sans-serif;
    background:#f1f5f9;
    color:#0f172a;
}

.page{
    padding:34px;
}

.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:30px;
    gap:20px;
}

.page-title{
    font-size:42px;
    font-weight:900;
}

.back-btn{
    background:#dbeafe;
    color:#1d4ed8;
    text-decoration:none;
    padding:14px 20px;
    border-radius:18px;
    font-weight:900;
}

.grid{
    display:grid;
    grid-template-columns:420px 1fr;
    gap:26px;
}

.card{
    background:#fff;
    border-radius:34px;
    padding:30px;
    border:1px solid #e2e8f0;
    box-shadow:0 18px 45px rgba(15,23,42,0.05);
}

.card h2{
    font-size:30px;
    margin-bottom:22px;
    font-weight:900;
}

.form-group{
    margin-bottom:18px;
}

.form-group label{
    display:block;
    margin-bottom:10px;
    font-weight:800;
}

.form-control{
    width:100%;
    padding:16px;
    border-radius:18px;
    border:1px solid #cbd5e1;
    outline:none;
    font-size:14px;
}

.submit-btn{
    width:100%;
    border:none;
    background:linear-gradient(135deg,#7c3aed,#5b21b6);
    color:#fff;
    padding:18px;
    border-radius:20px;
    font-weight:900;
    cursor:pointer;
}

.search-box{
    margin-bottom:24px;
}

.table-wrap{
    overflow:auto;
}

table{
    width:100%;
    border-collapse:collapse;
}

table th{
    background:#f8fafc;
    padding:18px;
    text-align:left;
    font-size:13px;
    text-transform:uppercase;
    color:#64748b;
}

table td{
    padding:18px;
    border-top:1px solid #e2e8f0;
    font-size:14px;
}

.badge{
    display:inline-block;
    padding:8px 12px;
    border-radius:999px;
    background:#ede9fe;
    color:#6d28d9;
    font-size:12px;
    font-weight:900;
}

.action-btn{
    padding:10px 14px;
    border-radius:14px;
    text-decoration:none;
    font-size:12px;
    font-weight:900;
}

.delete-btn{
    background:#fee2e2;
    color:#b91c1c;
}

.alert{
    padding:18px;
    border-radius:18px;
    margin-bottom:24px;
    font-weight:800;
}

.alert-success{
    background:#dcfce7;
    color:#166534;
}

.alert-danger{
    background:#fee2e2;
    color:#991b1b;
}

@media(max-width:1100px){

    .grid{
        grid-template-columns:1fr;
    }
}

</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="page-title">
            Teachers Management
        </h1>

        <a
        href="dashboard.php"
        class="back-btn">

            ← Dashboard

        </a>

    </div>

    <?php if($success): ?>

        <div class="alert alert-success">

            <?php echo e($success); ?>

        </div>

    <?php endif; ?>

    <?php if($error): ?>

        <div class="alert alert-danger">

            <?php echo e($error); ?>

        </div>

    <?php endif; ?>

    <div class="grid">

        <div class="card">

            <h2>

                Add Teacher

            </h2>

            <form method="POST">
<?php echo csrfField(); ?>

                <input
                type="hidden"
                name="action"
                value="add_teacher">

                <div class="form-group">

                    <label>
                        Full Name
                    </label>

                    <input
                    type="text"
                    name="full_name"
                    class="form-control"
                    required>

                </div>

                <div class="form-group">

                    <label>
                        Email
                    </label>

                    <input
                    type="email"
                    name="email"
                    class="form-control"
                    required>

                </div>

                <div class="form-group">

                    <label>
                        Password
                    </label>

                    <input
                    type="text"
                    name="password"
                    class="form-control"
                    required>

                </div>

                <div class="form-group">

                    <label>
                        WhatsApp
                    </label>

                    <input
                    type="text"
                    name="whatsapp"
                    class="form-control">

                </div>

                <button
                type="submit"
                class="submit-btn">

                    Add Teacher

                </button>

            </form>

        </div>

        <div class="card">

            <h2>

                Teachers List

            </h2>

            <form
            method="GET"
            class="search-box">

                <input
                type="text"
                name="search"
                class="form-control"
                placeholder="Search teachers..."
                value="<?php echo e($search); ?>">

            </form>

            <div class="table-wrap">

                <table>

                    <thead>

                        <tr>

                            <th>Name</th>
                            <th>Email</th>
                            <th>Status</th>
                            <th>Actions</th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php if($teachers): ?>

                            <?php foreach($teachers as $teacher): ?>

                                <tr>

                                    <td>

                                        <?php
                                        echo e(
                                            $teacher['full_name']
                                            ?? $teacher['name']
                                        );
                                        ?>

                                    </td>

                                    <td>

                                        <?php
                                        echo e(
                                            $teacher['email']
                                        );
                                        ?>

                                    </td>

                                    <td>

                                        <span class="badge">

                                            <?php
                                            echo e(
                                                ucfirst(
                                                    $teacher['status']
                                                    ?? 'active'
                                                )
                                            );
                                            ?>

                                        </span>

                                    </td>

                                    <td>

                                        <form method="post" style="display:inline">
<?php echo csrfField(); ?>
<input type="hidden" name="action" value="toggle_status">
<input type="hidden" name="teacher_id" value="<?php echo e((string)$teacher['id']); ?>">
<button type="submit" class="action-btn view-btn"><?php echo ($teacher['status'] ?? 'active') === 'active' ? 'Disable' : 'Activate'; ?></button>
</form>
<details style="display:inline-block;margin:4px 0"><summary class="action-btn view-btn" style="cursor:pointer">Reset password</summary><form method="post" style="padding:10px;background:#f8fafc;border-radius:12px;min-width:220px"><?php echo csrfField(); ?><input type="hidden" name="action" value="reset_password"><input type="hidden" name="teacher_id" value="<?php echo e((string)$teacher['id']); ?>"><input class="form-control" type="password" name="new_password" minlength="10" placeholder="New password" required><button type="submit" class="action-btn view-btn" style="border:0;margin-top:6px">Save</button></form></details>
<form method="post" style="display:inline" onsubmit="return confirm('Delete this teacher only if no academic records exist?')">
<?php echo csrfField(); ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="delete_id" value="<?php echo e((string)$teacher['id']); ?>">
<button type="submit" class="action-btn delete-btn">Delete</button>
</form>

                                    </td>

                                </tr>

                            <?php endforeach; ?>

                        <?php else: ?>

                            <tr>

                                <td colspan="4">

                                    No teachers found.

                                </td>

                            </tr>

                        <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>

</div>

</body>
</html>