<?php
// admin/users/edit_teacher.php
$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// --- UPDATED AUTH CHECK ---
// Allow both admin and subadmin to access this page
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../../auth/login.php");
    exit();
}

// Get Teacher ID
if (!isset($_GET['id'])) { header("Location: teachers.php"); exit(); }
$id = (int)$_GET['id'];

// Handle Update Logic
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_teacher'])) {
    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $section_id = !empty($_POST['section_id']) ? $_POST['section_id'] : null;
    $class_id = !empty($_POST['class_id']) ? $_POST['class_id'] : null;

    $sql = "UPDATE users SET fullname = ?, email = ?, section_id = ?, class_id = ? WHERE id = ? AND role = 'teacher'";
    $stmt = $pdo->prepare($sql);
    
    if ($stmt->execute([$fullname, $email, $section_id, $class_id, $id])) {
        $success = "Teacher details updated successfully!";
    } else {
        $error = "Failed to update teacher.";
    }
}

// Fetch current teacher details
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? AND role = 'teacher'");
$stmt->execute([$id]);
$teacher = $stmt->fetch();

if (!$teacher) { die("Teacher not found."); }

// Fetch sections and classes for dropdowns
$sections = $pdo->query("SELECT * FROM sections ORDER BY id ASC")->fetchAll();
$classes = $pdo->query("SELECT c.*, s.section_name FROM classes c JOIN sections s ON c.section_id = s.id ORDER BY s.id, c.class_name ASC")->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Teacher | Management</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background: #f4f4f4; padding: 40px; }
        .edit-card { background: white; padding: 30px; border-radius: 8px; max-width: 500px; margin: auto; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; }
        input, select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .btn-update { background: #3498db; color: white; border: none; padding: 12px; width: 100%; border-radius: 4px; cursor: pointer; font-weight: bold; font-size: 16px; margin-top: 10px; }
        .btn-update:hover { background: #2980b9; }
        .back-btn { text-decoration: none; color: #7f8c8d; font-size: 14px; display: block; margin-bottom: 20px; }
    </style>
</head>
<body>

<div class="edit-card">
    <a href="teachers.php" class="back-btn">← Cancel and Go Back</a>
    <h2>Edit Teacher Details</h2>

    <?php if(isset($success)) echo "<p style='color:green; font-weight:bold;'>$success</p>"; ?>
    <?php if(isset($error)) echo "<p style='color:red;'>$error</p>"; ?>

    <form method="POST">
        <div class="form-group">
            <label>Full Name</label>
            <input type="text" name="fullname" value="<?= htmlspecialchars($teacher['fullname']) ?>" required>
        </div>

        <div class="form-group">
            <label>Email Address</label>
            <input type="email" name="email" value="<?= htmlspecialchars($teacher['email']) ?>" required>
        </div>

        <div class="form-group">
            <label>Assigned Section</label>
            <select name="section_id">
                <option value="">-- No Section --</option>
                <?php foreach($sections as $sec): ?>
                    <option value="<?= $sec['id'] ?>" <?= $teacher['section_id'] == $sec['id'] ? 'selected' : '' ?>>
                        <?= $sec['section_name'] ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label>Assigned Class</label>
            <select name="class_id">
                <option value="">-- No Class --</option>
                <?php foreach($classes as $cl): ?>
                    <option value="<?= $cl['id'] ?>" <?= $teacher['class_id'] == $cl['id'] ? 'selected' : '' ?>>
                        <?= $cl['class_name'] ?> (<?= $cl['section_name'] ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <button type="submit" name="update_teacher" class="btn-update">Update Teacher Info</button>
    </form>
</div>

</body>
</html>