<?php
include('db_connection.php');

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // =========================
    // SANITIZE INPUT
    // =========================
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $username = trim($_POST['username']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $subject_id = intval($_POST['subject_id']);
    $role = 'teacher';

    try {
        $conn->begin_transaction();

        // =========================
        // CHECK DUPLICATES
        // =========================
        $check = $conn->prepare("SELECT user_id FROM users WHERE username = ? OR email = ?");
        $check->bind_param("ss", $username, $email);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {
            throw new Exception("Username or Email already exists.");
        }

        // =========================
        // INSERT INTO USERS
        // =========================
        $stmt = $conn->prepare("
            INSERT INTO users (name, username, email, password, role)
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("sssss", $name, $username, $email, $password, $role);
        $stmt->execute();

        $user_id = $stmt->insert_id;

        // =========================
        // INSERT INTO TEACHERS
        // =========================
        $stmt = $conn->prepare("
            INSERT INTO teachers (user_id, name, subject)
            VALUES (?, ?, ?)
        ");
        $stmt->bind_param("isi", $user_id, $name, $subject_id);
        $stmt->execute();

        $teacher_id = $stmt->insert_id;

        // =========================
        // INSERT AVAILABILITY
        // =========================
        if (!empty($_POST['availability'])) {

            $stmt = $conn->prepare("
                INSERT INTO teacher_availability (teacher_id, day, start_time, end_time)
                VALUES (?, ?, ?, ?)
            ");

            foreach ($_POST['availability'] as $day => $times) {

                $start = $times['start'] ?? '';
                $end = $times['end'] ?? '';

                if (!empty($start) && !empty($end)) {
                    $stmt->bind_param("isss", $teacher_id, $day, $start, $end);
                    $stmt->execute();
                }
            }
        }

        // =========================
        // COMMIT
        // =========================
        $conn->commit();

        header("Location: view_teacher.php?success=1");
        exit;

    } catch (Exception $e) {

        $conn->rollback();
        die("Error: " . $e->getMessage());
    }
}
?>