<?php
session_start();
require_once 'db_connect.php';
header('Content-Type: application/json; charset=utf-8');

// إخفاء الأخطاء النصية لكي لا تتعطل رسائل الـ JSON
error_reporting(0);
ini_set('display_errors', 0);

if (!isset($_SESSION['loggedin']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['status' => 'error', 'message' => 'غير مصرح لك']);
    exit;
}

$school_name = $conn->real_escape_string($_SESSION['school_name'] ?? '');
$action = $_POST['action'] ?? '';

if ($action === 'read') {
    $sql = "SELECT * FROM teacher_assignments WHERE school_name = '$school_name' ORDER BY id DESC";
    $result = $conn->query($sql);
    $html = '';
    
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $t_name = htmlspecialchars($row['teacher_name']);
            $subject = htmlspecialchars($row['subject_name']);
            $stage = htmlspecialchars($row['stage']);
            $dept = htmlspecialchars($row['department']);
            $section = htmlspecialchars($row['section']);
            
            $html .= "<tr style='border-bottom: 1px solid rgba(255,255,255,0.05);'>
                        <td style='padding: 15px; font-weight:bold; color:#fff;'>{$t_name}</td>
                        <td style='padding: 15px; color:#3b82f6;'>{$subject}</td>
                        <td style='padding: 15px; color:#cbd5e1;'>{$stage}</td>
                        <td style='padding: 15px; color:#cbd5e1;'>{$dept}</td>
                        <td style='padding: 15px; color:#cbd5e1;'>{$section}</td>
                        <td style='padding: 15px; text-align:center;'>
                            <button onclick=\"openEditAssignmentModal({$id}, '{$row['teacher_id']}', '{$subject}', '{$stage}', '{$dept}', '{$section}')\" class='btn-action' style='background:rgba(59, 130, 246, 0.2); color:#3b82f6; border:1px solid #3b82f6; padding:5px 10px; font-size:12px; margin-left:5px;'><i class='fas fa-edit'></i></button>
                            <button onclick=\"deleteAssignment({$id})\" class='btn-action' style='background:rgba(239, 68, 68, 0.2); color:#ef4444; border:1px solid #ef4444; padding:5px 10px; font-size:12px;'><i class='fas fa-trash'></i></button>
                        </td>
                      </tr>";
        }
    } else {
        $html = "<tr><td colspan='6' style='text-align:center; padding:30px; color:#94a3b8;'>لا توجد توزيعات مسجلة.</td></tr>";
    }
    echo json_encode(['status' => 'success', 'html' => $html]);
} 
elseif ($action === 'create' || $action === 'update') {
    $teacher_id = intval($_POST['teacher_id']);
    $subject = $conn->real_escape_string(trim($_POST['subject']));
    $stage = $conn->real_escape_string(trim($_POST['stage']));
    $department = $conn->real_escape_string(trim($_POST['department']));
    $section = $conn->real_escape_string(trim($_POST['section']));
    
    if (empty($teacher_id) || empty($subject) || empty($stage)) {
        echo json_encode(['status' => 'error', 'message' => 'يرجى تعبئة الحقول الأساسية.']);
        exit;
    }

    $t_res = $conn->query("SELECT display_name, teacher_name FROM teachers WHERE id = $teacher_id LIMIT 1");
    if (!$t_res || $t_res->num_rows == 0) {
        echo json_encode(['status' => 'error', 'message' => 'المدرس غير موجود.']);
        exit;
    }
    $t_row = $t_res->fetch_assoc();
    $display_name = $conn->real_escape_string($t_row['display_name']);
    $teacher_system_name = $conn->real_escape_string($t_row['teacher_name']); 

    if ($action === 'create') {
        $sql = "INSERT INTO teacher_assignments (school_name, teacher_id, teacher_name, subject_name, stage, department, section) 
                VALUES ('$school_name', $teacher_id, '$display_name', '$subject', '$stage', '$department', '$section')";
        $msg = "تم تسجيل التخصيص وربط الطلاب بنجاح!";
    } else {
        $assign_id = intval($_POST['assignment_id']);
        $sql = "UPDATE teacher_assignments SET teacher_id=$teacher_id, teacher_name='$display_name', subject_name='$subject', stage='$stage', department='$department', section='$section' WHERE id=$assign_id AND school_name='$school_name'";
        $msg = "تم التحديث بنجاح!";
    }

    if ($conn->query($sql)) {
        // تحديث جدول الطلاب لربطهم بهذا المدرس
        $update_students = "UPDATE students SET teacher_name = '$teacher_system_name' 
                            WHERE school_name = '$school_name' AND stage = '$stage'";
        if (!empty($department) && $department !== 'عام' && $department !== 'بدون قسم (عام)') {
            $update_students .= " AND department = '$department'";
        }
        $conn->query($update_students); 

        echo json_encode(['status' => 'success', 'message' => $msg]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'فشل الحفظ في قاعدة البيانات.']);
    }
}
elseif ($action === 'delete') {
    $id = intval($_POST['id']);
    $conn->query("DELETE FROM teacher_assignments WHERE id = $id AND school_name = '$school_name'");
    echo json_encode(['status' => 'success', 'message' => 'تم حذف التخصيص.']);
}
?>