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

error_reporting(0);
ini_set('display_errors', 0);

// 🚀 كود التصليح الذاتي (Auto-Patch): إضافة أعمدة الشفهي برمجياً 🚀
$check_col = $conn->query("SHOW COLUMNS FROM control_grades LIKE 'oral_data'");
if ($check_col && $check_col->num_rows == 0) {
    $conn->query("ALTER TABLE `control_grades` ADD `oral_data` TEXT NULL DEFAULT NULL");
}
$check_col2 = $conn->query("SHOW COLUMNS FROM control_grades LIKE 'final_oral'");
if ($check_col2 && $check_col2->num_rows == 0) {
    $conn->query("ALTER TABLE `control_grades` ADD `final_oral` FLOAT NULL DEFAULT NULL");
}

$allowed_roles = ['teacher', 'admin'];
if (!isset($_SESSION['loggedin']) || !in_array($_SESSION['role'], $allowed_roles)) {
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => 'غير مصرح لك بالدخول']); 
    exit;
}

$action = $_POST['action'] ?? '';
$school_name = $conn->real_escape_string($_SESSION['school_name'] ?? 'مستقل');

$t_display_name = $conn->real_escape_string($_POST['display_name'] ?? $_SESSION['display_name'] ?? '');
$t_teacher_name = $conn->real_escape_string($_POST['teacher_name'] ?? $_SESSION['teacher_name'] ?? '');

if (empty($t_teacher_name) && isset($_SERVER['HTTP_REFERER'])) {
    if (preg_match('/teacher_([A-Z0-9\-]+)/', $_SERVER['HTTP_REFERER'], $matches)) {
        $t_teacher_name = $conn->real_escape_string('teacher_' . $matches[1]);
    }
}

if ($action === 'fetch_for_gradebook') {
    $stage = $conn->real_escape_string($_POST['stage']);
    $dept = $conn->real_escape_string($_POST['dept']);
    $section = $conn->real_escape_string($_POST['section']);
    $subject = $conn->real_escape_string($_POST['subject']);
    
    $sql = "SELECT s.student_id, s.student_name, s.department as student_dept, s.branch as student_branch,
                   cg.month_1, cg.month_2, cg.month_3, cg.term_1, cg.mid_year, 
                   cg.month_4, cg.month_5, cg.month_6, cg.term_2, 
                   cg.annual_effort, cg.final_exam, cg.final_oral, cg.final_grade, cg.makeup_exam, cg.final_after_makeup, cg.oral_data
            FROM students s
            LEFT JOIN control_grades cg ON s.student_id = cg.student_id AND cg.subject_name = '$subject'
            WHERE (s.school_name = '$school_name' OR '$school_name' = 'مستقل')";
            
    if (!empty($stage) && $stage !== 'عام' && $stage !== '-- اختر --') {
        $sql .= " AND s.stage LIKE '%$stage%'";
    }
    
    if (!empty($dept) && $dept !== 'عام') {
        $sql .= " AND s.department LIKE '%$dept%'";
    }
    
    if (!empty($section) && $section !== 'الكل' && $section !== 'عام') {
        $sql .= " AND s.branch = '$section'";
    }
    
    $sql .= " ORDER BY s.student_name ASC";

    $result = $conn->query($sql);
    $students = [];
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $cleaned_row = [
                'student_id' => $row['student_id'],
                'student_name' => $row['student_name'],
                'student_dept' => $row['student_dept'],
                'student_branch' => $row['student_branch'],
                'month_1' => isset($row['month_1']) ? round((float)$row['month_1']) : '',
                'month_2' => isset($row['month_2']) ? round((float)$row['month_2']) : '',
                'month_3' => isset($row['month_3']) ? round((float)$row['month_3']) : '',
                'term_1' => isset($row['term_1']) ? round((float)$row['term_1']) : '',
                'mid_year' => isset($row['mid_year']) ? round((float)$row['mid_year']) : '',
                'month_4' => isset($row['month_4']) ? round((float)$row['month_4']) : '',
                'month_5' => isset($row['month_5']) ? round((float)$row['month_5']) : '',
                'month_6' => isset($row['month_6']) ? round((float)$row['month_6']) : '',
                'term_2' => isset($row['term_2']) ? round((float)$row['term_2']) : '',
                'annual_effort' => isset($row['annual_effort']) ? round((float)$row['annual_effort']) : '',
                'final_exam' => isset($row['final_exam']) ? round((float)$row['final_exam']) : '',
                'final_oral' => isset($row['final_oral']) ? round((float)$row['final_oral']) : '', // 🚀 شفهي النهائي
                'final_grade' => isset($row['final_grade']) ? round((float)$row['final_grade']) : '',
                'makeup_exam' => isset($row['makeup_exam']) ? round((float)$row['makeup_exam']) : '',
                'final_after_makeup' => isset($row['final_after_makeup']) ? round((float)$row['final_after_makeup']) : '',
                'oral_data' => $row['oral_data'] ?? '' // 🚀 إرسال الشفهي والمسميات
            ];
            $students[] = $cleaned_row;
        }
    }

    echo json_encode(['status' => 'success', 'students' => $students]);
    exit;
} 
elseif ($action === 'submit_control') {
    $stage = $conn->real_escape_string($_POST['stage']);
    $subject = $conn->real_escape_string($_POST['subject']);
    
    $is_submitted = isset($_POST['is_submitted']) ? (int)$_POST['is_submitted'] : 0;
    
    $grades_data = json_decode($_POST['grades_data'], true);

    if (empty($grades_data)) {
        echo json_encode(['status' => 'error', 'message' => 'عذراً، لم تصل أي بيانات للسيرفر.']); 
        exit;
    }

    $actual_teacher = !empty($t_display_name) ? $t_display_name : $t_teacher_name;
    $success_count = 0;
    
    // إدخال البيانات وتحديثها مع شفهي النهائي
    $stmt = $conn->prepare("INSERT INTO control_grades 
        (student_id, school_name, teacher_name, subject_name, stage, department, section, 
         month_1, month_2, month_3, term_1, mid_year, month_4, month_5, month_6, term_2, 
         annual_effort, final_exam, final_oral, final_grade, makeup_exam, final_after_makeup, is_submitted, oral_data) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
        teacher_name=VALUES(teacher_name), stage=VALUES(stage), department=VALUES(department), section=VALUES(section),
        month_1=VALUES(month_1), month_2=VALUES(month_2), month_3=VALUES(month_3), term_1=VALUES(term_1), mid_year=VALUES(mid_year), 
        month_4=VALUES(month_4), month_5=VALUES(month_5), month_6=VALUES(month_6), term_2=VALUES(term_2), 
        annual_effort=VALUES(annual_effort), final_exam=VALUES(final_exam), final_oral=VALUES(final_oral), final_grade=VALUES(final_grade), 
        makeup_exam=VALUES(makeup_exam), final_after_makeup=VALUES(final_after_makeup), is_submitted=VALUES(is_submitted), oral_data=VALUES(oral_data)
    ");

    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'خطأ في قاعدة البيانات. تأكد من وجود الجداول.']); 
        exit;
    }

    foreach ($grades_data as $g) {
        $actual_dept = $g['actual_dept'] ?? 'عام';
        $actual_section = $g['actual_section'] ?? 'الكل';

        $m1 = $g['m1'] !== '' ? floatval($g['m1']) : null;
        $m2 = $g['m2'] !== '' ? floatval($g['m2']) : null;
        $m3 = $g['m3'] !== '' ? floatval($g['m3']) : null;
        $t1 = $g['t1'] !== '' ? floatval($g['t1']) : null;
        
        $mid = $g['mid'] !== '' ? floatval($g['mid']) : null;
        
        $m4 = $g['m4'] !== '' ? floatval($g['m4']) : null;
        $m5 = $g['m5'] !== '' ? floatval($g['m5']) : null;
        $m6 = $g['m6'] !== '' ? floatval($g['m6']) : null;
        $t2 = $g['t2'] !== '' ? floatval($g['t2']) : null;
        
        $ann = $g['annual'] !== '' ? floatval($g['annual']) : null;
        $fin_ex = $g['fin_ex'] !== '' ? floatval($g['fin_ex']) : null; // تحريري النهائي
        $fin_oral = $g['fin_oral'] !== '' ? floatval($g['fin_oral']) : null; // 🚀 شفهي النهائي
        $fin_g = $g['fin_g'] !== '' ? floatval($g['fin_g']) : null;
        $mk = $g['mk'] !== '' ? floatval($g['mk']) : null;
        $aft_mk = $g['after_mk'] !== '' ? floatval($g['after_mk']) : null;
        
        // 🚀 استقبال بيانات ومسميات الشفهي 🚀
        $oral_data = !empty($g['oral_data']) ? $g['oral_data'] : null;

        $stmt->bind_param("sssssssdddddddddddddddis", 
            $g['student_id'], $school_name, $actual_teacher, $subject, $stage, $actual_dept, $actual_section,
            $m1, $m2, $m3, $t1, $mid, $m4, $m5, $m6, $t2, $ann, $fin_ex, $fin_oral, $fin_g, $mk, $aft_mk, $is_submitted, $oral_data
        );
        if ($stmt->execute()) { $success_count++; }
    }

    if ($is_submitted == 1) {
        $msg = "تم الحفظ واعتماد درجات ($success_count) طالب للكنترول بنجاح!";
    } else {
        $msg = "تم حفظ المسودة بنجاح. بيانات ($success_count) طالب محفوظة ولن تراها الإدارة إلا بعد الاعتماد.";
    }

    echo json_encode(['status' => 'success', 'message' => $msg]);
    exit;
}
?>