<?php
session_start();
include 'db.php';

if (!isset($_SESSION['teacher_id'])) {
    header("Location: login.php");
    exit();
}

date_default_timezone_set('Asia/Baghdad');

$teacher_id      = isset($_POST['teacher_id']) ? (int)$_POST['teacher_id'] : 0;
$teacher_name    = isset($_POST['teacher_name']) ? mysqli_real_escape_string($conn, $_POST['teacher_name']) : 'مدرّس';
$teacher_subject = isset($_POST['teacher_subject']) ? mysqli_real_escape_string($conn, $_POST['teacher_subject']) : '';

$stage      = isset($_POST['stage']) ? mysqli_real_escape_string($conn, $_POST['stage']) : '';
$class      = isset($_POST['class']) ? mysqli_real_escape_string($conn, $_POST['class']) : '';
$exam_type  = isset($_POST['exam_type']) ? mysqli_real_escape_string($conn, $_POST['exam_type']) : '';
$exam_month = isset($_POST['exam_month']) ? mysqli_real_escape_string($conn, $_POST['exam_month']) : '';
$topics     = isset($_POST['topics']) ? mysqli_real_escape_string($conn, $_POST['topics']) : '';

if ($stage == '' || $class == '' || $exam_type == '' || $topics == '') {
    die("يرجى إدخال جميع الحقول المطلوبة.");
}

$created_at = date('Y-m-d H:i:s');

// إدخال في جدول exam_topics (المعزول)
$sql = "INSERT INTO exam_topics
        (teacher_id, teacher_name, teacher_subject, stage, class, exam_type, exam_month, topics, created_at)
        VALUES
        ($teacher_id, '$teacher_name', '$teacher_subject', '$stage', '$class', '$exam_type', '$exam_month', '$topics', '$created_at')";

$ins = mysqli_query($conn, $sql);

if ($ins) {
    echo "<script>alert('تم حفظ المادة الداخلة بالامتحان ✔'); window.location.href='exam_topics.php';</script>";
} else {
    echo "حدث خطأ أثناء الحفظ: " . mysqli_error($conn);
}
?>
