<?php
session_start();
include '../../includes/db_connection.php';

// Header code (from header.php)
if (!isset($_SESSION['user_id'])) {
    header("Location: /school_management/public/index.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>School Management System</title>
    <link rel="stylesheet" href="/school_management/public/css/style.css">
</head>
<body>
<div class="header">
    <h1>School Management System</h1>
    <div class="nav">
        <a href="/school_management/public/dashboard.php">Dashboard</a>
        <a href="/school_management/public/students/students_list.php">Students</a>
        <a href="/school_management/public/teachers/teachers_list.php">Teachers</a>
        <a href="/school_management/public/fees/fee_collection.php">Fees</a>
        <a href="/school_management/public/exam_results/add_exam_result.php">Exams</a>
        <a href="/school_management/public/attendance/record_attendance.php">Attendance</a>
        <a href="/school_management/public/change_password.php">Change Password</a>
        <a href="/school_management/public/logout.php">Logout</a>
    </div>
</div>
<div class="content">

<?php
if ($_SESSION['role'] !== 'Admin') {
    echo "<p style='color:red;'>You do not have permission to view this page.</p>";
    echo "</div></body></html>";
    exit();
}

$teacher_id = $_GET['id'] ?? null;
$teacher = null;
$error = '';

if (!$teacher_id) {
    $error = 'No teacher ID provided.';
} else {
    // Fetch current teacher data
    $sql = "SELECT * FROM teachers WHERE teacher_id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        $error = "Error preparing statement: " . $conn->error;
    } else {
        $stmt->bind_param("i", $teacher_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $teacher = $result->fetch_assoc();
        } else {
            $error = 'Teacher not found.';
        }
        $stmt->close();
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && $teacher_id) {
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $phone_number = $_POST['phone_number'];
    $subject = $_POST['subject'];
    $joining_date = $_POST['joining_date'];
    $class_id = $_POST['class_id'];

    $sql = "UPDATE teachers SET first_name = ?, last_name = ?, email = ?, phone_number = ?, subject = ?, joining_date = ?, class_id = ? WHERE teacher_id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        $error = "Error preparing statement: " . $conn->error;
    } else {
        $stmt->bind_param("ssssssii", $first_name, $last_name, $email, $phone_number, $subject, $joining_date, $class_id, $teacher_id);
        if ($stmt->execute()) {
            echo "<p style='color:green;'>Teacher updated successfully!</p>";
            // Reload the page to show updated data
            $sql_reload = "SELECT * FROM teachers WHERE teacher_id = ?";
            $stmt_reload = $conn->prepare($sql_reload);
            $stmt_reload->bind_param("i", $teacher_id);
            $stmt_reload->execute();
            $result_reload = $stmt_reload->get_result();
            $teacher = $result_reload->fetch_assoc();
            $stmt_reload->close();
        } else {
            $error = "Error updating teacher: " . $stmt->error;
        }
        $stmt->close();
    }
}

$classes_sql = "SELECT class_id, class_name FROM classes ORDER BY class_name";
$classes_result = $conn->query($classes_sql);

?>

<div class="container">
    <h2>Edit Teacher</h2>
    <?php if ($error): ?>
        <p style='color:red;'><?php echo $error; ?></p>
        <p><a href="teachers_list.php">Go back to Teachers List</a></p>
    <?php elseif ($teacher): ?>
        <form action="edit_teacher.php?id=<?php echo htmlspecialchars($teacher_id); ?>" method="POST">
            <input type="hidden" name="teacher_id" value="<?php echo htmlspecialchars($teacher['teacher_id']); ?>">

            <label for="first_name">First Name:</label><br>
            <input type="text" id="first_name" name="first_name" value="<?php echo htmlspecialchars($teacher['first_name']); ?>" required><br><br>

            <label for="last_name">Last Name:</label><br>
            <input type="text" id="last_name" name="last_name" value="<?php echo htmlspecialchars($teacher['last_name']); ?>" required><br><br>

            <label for="email">Email:</label><br>
            <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($teacher['email']); ?>" required><br><br>

            <label for="phone_number">Phone Number:</label><br>
            <input type="text" id="phone_number" name="phone_number" value="<?php echo htmlspecialchars($teacher['phone_number']); ?>" required><br><br>

            <label for="subject">Subject:</label><br>
            <input type="text" id="subject" name="subject" value="<?php echo htmlspecialchars($teacher['subject']); ?>" required><br><br>

            <label for="joining_date">Joining Date:</label><br>
            <input type="date" id="joining_date" name="joining_date" value="<?php echo htmlspecialchars($teacher['joining_date']); ?>" required><br><br>

            <label for="class_id">Class:</label><br>
            <select id="class_id" name="class_id" required>
                <?php
                if ($classes_result->num_rows > 0) {
                    while($row = $classes_result->fetch_assoc()) {
                        $selected = ($row['class_id'] == $teacher['class_id']) ? 'selected' : '';
                        echo "<option value='" . htmlspecialchars($row['class_id']) . "' " . $selected . ">" . htmlspecialchars($row['class_name']) . "</option>";
                    }
                } else {
                    echo "<option value=''>No classes found</option>";
                }
                ?>
            </select><br><br>
            
            <input type="submit" value="Update Teacher">
        </form>
    <?php endif; ?>
</div>

<?php
$conn->close();
?>

<div class="footer">
    <p>&copy; <?php echo date("Y"); ?> School Management System. All Rights Reserved.</p>
</div>
</div>
</body>
</html>