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

$response = ['status' => 'error', 'message' => 'إجراء غير صالح.'];

// 1. إنشاء الجدول تلقائياً في قاعدة البيانات إذا لم يكن موجوداً
$conn->query("CREATE TABLE IF NOT EXISTS academic_requests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    school_name VARCHAR(150),
    teacher_name VARCHAR(150),
    req_type VARCHAR(50), 
    subject_class VARCHAR(255),
    content TEXT,
    status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    // استقبال الطلب من المدرس
    if ($action === 'submit_request') {
        $teacher = $conn->real_escape_string($_POST['teacher_name']);
        $school = $conn->real_escape_string($_SESSION['school_name'] ?? 'مستقل');
        $req_type = $conn->real_escape_string($_POST['req_type']);
        $subject_class = $conn->real_escape_string($_POST['subject_class']);
        $content = $conn->real_escape_string($_POST['content']);

        if (empty($content)) throw new Exception("المحتوى فارغ!");

        $sql = "INSERT INTO academic_requests (school_name, teacher_name, req_type, subject_class, content, status) 
                VALUES ('$school', '$teacher', '$req_type', '$subject_class', '$content', 'pending')";
        
        if ($conn->query($sql)) {
            $response = ['status' => 'success', 'message' => "تم إرسال ($req_type) للإدارة بنجاح."];
        } else { throw new Exception("خطأ في قاعدة البيانات."); }
    }
    
    // جلب الطلبات للمدير
    elseif ($action === 'get_admin_requests') {
        $school = $conn->real_escape_string($_SESSION['school_name'] ?? '');
        $sql = "SELECT * FROM academic_requests WHERE school_name = '$school' ORDER BY id DESC";
        $res = $conn->query($sql);
        $data = [];
        if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        $response = ['status' => 'success', 'data' => $data];
    }

    // جلب الطلبات للمدرس (أرشيفه الخاص)
    elseif ($action === 'get_teacher_plans') {
        $teacher = $conn->real_escape_string($_GET['teacher_name'] ?? '');
        $school = $conn->real_escape_string($_SESSION['school_name'] ?? '');
        $sql = "SELECT * FROM academic_requests WHERE teacher_name = '$teacher' AND school_name = '$school' ORDER BY id DESC";
        $res = $conn->query($sql);
        $data = [];
        if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        $response = ['status' => 'success', 'data' => $data];
    }
    
    // الإدارة تغير الحالة (موافقة / رفض)
    elseif ($action === 'update_status') {
        $id = intval($_POST['request_id']);
        $new_status = $conn->real_escape_string($_POST['status']);
        if ($conn->query("UPDATE academic_requests SET status = '$new_status' WHERE id = $id")) {
            $response = ['status' => 'success', 'message' => 'تم تحديث حالة الطلب.'];
        }
    }

    // المدرس يحذف خطته
    elseif ($action === 'delete_plan') {
        $id = intval($_POST['request_id']);
        if ($conn->query("DELETE FROM academic_requests WHERE id = $id")) {
            $response = ['status' => 'success'];
        }
    }

} catch (Exception $e) { $response = ['status' => 'error', 'message' => $e->getMessage()]; }

echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
?>