<?php
include_once 'db_connect.php'; 

// 1. جلب بيانات المدرسة
$school = $conn->query("SELECT school_name, school_logo FROM schools LIMIT 1")->fetch_assoc();
$current_school = $school['school_name'] ?? 'المدرسة';
$logo = !empty($school['school_logo']) ? $school['school_logo'] : 'logo.png'; 

$filter_type = $_GET['filter'] ?? 'all'; 
$filter_value = $_GET['value'] ?? '';
$day_filter = $_GET['day'] ?? 'all'; 

// 2. قاموس الأسماء الحقيقية للمدرسين
$real_teacher_names = [];
$t_query = $conn->query("SELECT teacher_name, display_name FROM teachers WHERE school_name = '$current_school'");
if ($t_query) {
    while ($t_row = $t_query->fetch_assoc()) {
        $real_teacher_names[$t_row['teacher_name']] = $t_row['display_name'];
    }
}

// 3. 🚀 دمج الوسوم والجداول المولدة ببساطة شديدة (بدون تفكيك معقد) 🚀
$all_classes = [];
$c_res = $conn->query("
    SELECT DISTINCT stage_name, department_name, section_name FROM generated_schedules WHERE school_name = '$current_school'
    UNION
    SELECT DISTINCT stage_name, department_name, section_name FROM school_tags WHERE school_name = '$current_school'
");

if($c_res) {
    while($row = $c_res->fetch_assoc()) {
        // نأخذ القيم كما هي من قاعدة البيانات ونجمعها
        $stage = trim($row['stage_name']);
        $dept = trim($row['department_name']);
        $sec = trim($row['section_name']);
        
        $parts = [];
        if (!empty($stage)) $parts[] = $stage;
        if (!empty($dept)) $parts[] = $dept;
        if (!empty($sec)) $parts[] = $sec;
        
        $full_name = implode(' - ', $parts); 
        
        // منع التكرار
        $exists = false;
        foreach($all_classes as $ac) { if($ac['match_key'] === $full_name) { $exists = true; break; } }
        
        if(!$exists && !empty($full_name)) {
            $all_classes[] = [
                'display_name' => $full_name,
                'match_key' => $full_name
            ];
        }
    }
}

// ترتيب الأبجدية
usort($all_classes, function($a, $b) { return strcmp($a['match_key'], $b['match_key']); });

$display_classes = [];
if ($filter_type === 'class' && !empty($filter_value)) {
    foreach ($all_classes as $c) {
        if ($c['display_name'] === $filter_value) { $display_classes[] = $c; }
    }
} else {
    $display_classes = $all_classes;
}

// 4. بناء الاستعلام لجلب الحصص
$query = "SELECT * FROM generated_schedules WHERE school_name = '$current_school'";

if ($day_filter !== 'all') { $query .= " AND day_of_week = '" . $conn->real_escape_string($day_filter) . "'"; }
if ($filter_type === 'teacher' && !empty($filter_value)) { $query .= " AND teacher_name = '" . $conn->real_escape_string($filter_value) . "'"; } 
elseif ($filter_type === 'class' && !empty($filter_value)) {
    // 🚀 تحديث الفلتر ليتطابق مع طريقة الحفظ الجديدة 🚀
    // نبحث باستخدام LIKE لضمان التقاط المرحلة حتى لو كانت مدمجة في حقل واحد
    $query .= " AND CONCAT(IFNULL(stage_name,''), ' - ', IFNULL(department_name,''), ' - ', IFNULL(section_name,'')) LIKE '%" . $conn->real_escape_string($filter_value) . "%'";
}
$schedules = $conn->query($query);

// 5. وضع البيانات في المصفوفة (مطابقة دقيقة 100%)
$matrix = [];
if($schedules) {
    while($row = $schedules->fetch_assoc()) {
        $stage = trim($row['stage_name']);
        $dept = trim($row['department_name']);
        $sec = trim($row['section_name']);
        
        $parts = [];
        if (!empty($stage)) $parts[] = $stage;
        if (!empty($dept)) $parts[] = $dept;
        if (!empty($sec)) $parts[] = $sec;
        
        $match_key = implode(' - ', $parts);
        
        $p_num = (int)trim($row['period_number']); 
        $matrix[$row['day_of_week']][$p_num][$match_key] = $row;
    }
}

$days_array = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'السبت'];
if($day_filter !== 'all') { $days_array = [$day_filter]; }

// جلب قائمة المدرسين للفلتر العلوي
$teachers_in_db = [];
$t_db_res = $conn->query("SELECT DISTINCT teacher_name FROM generated_schedules WHERE school_name = '$current_school'");
if($t_db_res) { while($row = $t_db_res->fetch_assoc()) { $teachers_in_db[] = $row['teacher_name']; } }
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>جدول الدروس الأسبوعي - <?php echo htmlspecialchars($current_school); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #0f172a; padding: 20px; color: #333; margin: 0; }
        .no-print { background: #1e293b; padding: 20px; border-radius: 12px; margin-bottom: 20px; color: #fff; display: flex; gap: 15px; align-items: center; justify-content: space-between; flex-wrap: wrap; }
        .paper-container { background: #fff; padding: 30px; border-radius: 12px; overflow-x: auto; min-height: 800px; }
        .print-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 3px double #000; padding-bottom: 15px; }
        .print-header .side-text { font-weight: bold; font-size: 16px; color: #b91c1c; }
        .print-header .center-title { text-align: center; }
        .print-header img { width: 80px; height: 80px; object-fit: contain; }
        .print-header h2 { margin: 10px 0 0 0; font-size: 24px; color: #0284c7; }
        table.master-table { width: 100%; border-collapse: collapse; text-align: center; min-width: <?php echo (count($display_classes) <= 2) ? '100%' : '1200px'; ?>; border: 2px solid #000; }
        table.master-table th, table.master-table td { border: 1px solid #000; padding: 10px 4px; font-size: 14px; }
        table.master-table thead th { background: #fef08a; font-weight: bold; color: #000; }
        table.master-table thead tr:nth-child(2) th { background: #e0f2fe; font-size: 13px; }
        .vertical-day { writing-mode: vertical-rl; transform: rotate(180deg); font-weight: bold; background: #dcfce3; font-size: 18px; letter-spacing: 5px; }
        .period-num { font-weight: bold; background: #f3f4f6; width: 40px; }
        .subj { font-weight: bold; color: #b91c1c; font-size: 15px; }
        .teach { font-size: 12px; color: #1d4ed8; margin-top: 4px; font-weight: bold; }
        select, button { padding: 10px; border-radius: 6px; border: 1px solid #ccc; font-size: 14px; }
        .btn-print { background: #16a34a; color: white; border: none; cursor: pointer; font-weight: bold; display: flex; align-items: center; gap: 8px; }
        .btn-print:hover { background: #15803d; }
        @media print {
            body { background: #fff; padding: 0; }
            .no-print { display: none !important; }
            .paper-container { padding: 0; border-radius: 0; overflow: visible; box-shadow: none; }
            table.master-table { min-width: 100%; }
            @page { size: A4 landscape; margin: 10mm; }
        }
    </style>
</head>
<body>

    <div class="no-print">
        <form method="GET" action="" style="display: flex; gap: 15px; align-items: center; width: 100%; flex-wrap: wrap;">
            <div>
                <label>اليوم: </label>
                <select name="day" onchange="this.form.submit()">
                    <option value="all" <?php if($day_filter=='all') echo 'selected'; ?>>كل الأيام (الأسبوع كامل)</option>
                    <?php foreach(['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'السبت'] as $d): ?>
                        <option value="<?= $d ?>" <?= ($day_filter==$d?'selected':'') ?>><?= $d ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label>نوع الفلتر: </label>
                <select name="filter" onchange="this.form.submit()">
                    <option value="all">عرض الجدول العام للمدرسة</option>
                    <option value="teacher" <?= ($filter_type=='teacher'?'selected':'') ?>>جدول مدرس معين</option>
                    <option value="class" <?= ($filter_type=='class'?'selected':'') ?>>جدول صف/شعبة معين</option>
                </select>
            </div>
            
            <?php if($filter_type === 'teacher'): ?>
                <div>
                    <select name="value" onchange="this.form.submit()">
                        <option value="">-- اختر المدرس --</option>
                        <?php foreach($teachers_in_db as $t_id): 
                            $t_name = $real_teacher_names[$t_id] ?? $t_id;
                        ?>
                            <option value="<?= htmlspecialchars($t_id) ?>" <?= ($filter_value==$t_id?'selected':'') ?>><?= htmlspecialchars($t_name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            <?php elseif($filter_type === 'class'): ?>
                <div>
                    <select name="value" onchange="this.form.submit()">
                        <option value="">-- اختر الصف --</option>
                        <?php foreach($all_classes as $c): ?>
                            <option value="<?= htmlspecialchars($c['display_name']) ?>" <?= ($filter_value==$c['display_name']?'selected':'') ?>><?= htmlspecialchars($c['display_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            <?php endif; ?>
            <button type="submit" style="display:none;">تحديث</button>
        </form>
        
        <div style="display: flex; gap: 10px;">
            <button onclick="publishSchedule()" class="btn-print" style="background: #3b82f6;"><i class="fas fa-paper-plane"></i> نشر الجدول</button>
            <button onclick="window.print()" class="btn-print"><i class="fas fa-print"></i> طباعة الجدول</button>
        </div>
    </div>

    <div class="paper-container">
        <div class="print-header">
            <div class="side-text">جدول الدروس</div>
            <div class="center-title">
                <?php if($logo): ?>
                    <img src="<?= htmlspecialchars($logo) ?>" alt="شعار المدرسة">
                <?php endif; ?>
                <h2>جدول الدروس الاسبوعي لمدرسة <?= htmlspecialchars($current_school) ?></h2>
                <?php if($filter_type === 'class' && !empty($filter_value)): ?>
                    <h3 style="margin-top: 5px; color: #16a34a;">للصف: <?= htmlspecialchars($filter_value) ?></h3>
                <?php endif; ?>
            </div>
            <div class="side-text" style="color: #16a34a;">للعام الدراسي (2026 - 2027)</div>
        </div>

        <table class="master-table">
            <thead>
                <tr>
                    <th rowspan="2" style="width: 40px;">اليوم</th>
                    <th rowspan="2" style="width: 40px;">الحصة</th>
                    <?php if(empty($display_classes)): ?>
                        <th>لا توجد بيانات للعرض</th>
                    <?php else: ?>
                        <?php foreach($display_classes as $c): ?>
                            <th><?= htmlspecialchars($c['display_name']) ?></th>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tr>
                <tr>
                    <?php foreach($display_classes as $c): ?>
                        <th>المادة / المعلم</th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($display_classes)): ?>
                    <?php foreach($days_array as $d): ?>
                        <?php for($p=1; $p<=7; $p++): ?>
                            <tr>
                                <?php if($p==1): ?>
                                    <td rowspan="7" class="vertical-day"><?= $d ?></td>
                                <?php endif; ?>
                                
                                <td class="period-num"><?= $p ?></td>
                                
                                <?php foreach($display_classes as $c): 
                                    $cell = $matrix[$d][$p][$c['match_key']] ?? null;
                                ?>
                                    <td>
                                        <?php if($cell): 
                                            $t_id_cell = $cell['teacher_name'];
                                            $t_name_cell = $real_teacher_names[$t_id_cell] ?? $t_id_cell;
                                        ?>
                                            <div class="subj"><?= htmlspecialchars($cell['subject_name']) ?></div>
                                            <div class="teach"><?= htmlspecialchars($t_name_cell) ?></div>
                                        <?php else: ?>
                                            <span style="color: #ccc;">-</span>
                                        <?php endif; ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                        <?php endfor; ?>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="3">لا توجد حصص مسجلة بناءً على الفلتر المختار</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
        
        <div style="display: flex; justify-content: space-between; margin-top: 40px; font-weight: bold; font-size: 18px;">
            <div>مدير المدرسة</div>
            <div>المعاون الإداري</div>
            <div>المشرف الاختصاص</div>
        </div>
    </div>

    <!-- كود الجافاسكريبت الخاص بالنشر -->
    <script>
    function publishSchedule() {
        if(confirm('هل أنت متأكد من نشر هذا الجدول ليظهر في لوحات المدرسين والطلاب المستهدفين وإرسال إشعار لهم؟')) {
            const filterType = '<?= $filter_type ?>';
            const filterValue = '<?= addslashes($filter_value) ?>';

            let fd = new FormData();
            fd.append('filter_type', filterType);
            fd.append('filter_value', filterValue);

            fetch('api/publish_schedule_api.php', {
                method: 'POST',
                body: fd
            })
            .then(res => res.json())
            .then(data => {
                alert(data.message);
            })
            .catch(err => {
                alert('حدث خطأ في الاتصال بالسيرفر');
                console.error(err);
            });
        }
    }
    </script>
</body>
</html>