<?php
// تفعيل عرض الأخطاء للتطوير
ini_set('display_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'الجداول الدراسية';
include '../../includes/header.php';

if (session_status() == PHP_SESSION_NONE) { session_start(); }
checkLogin();

$db = getDB();
$pdo = method_exists($db, 'getConnection') ? $db->getConnection() : $db;

$departments_list = [];
$schedule_data = [];
$selected_dept = $_GET['department_id'] ?? '';
$selected_grade = $_GET['grade'] ?? '';
$error_msg = '';

$days = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس'];
$times = ['8:30-9:30', '9:30-10:30', '10:30-11:30', '11:30-12:30', '12:30-1:30', '1:30-2:30'];

try {
    $dept_sql = "SELECT Departement_ID, Departement FROM departemenets ORDER BY Departement ASC";
    $stmt_dept = $pdo->prepare($dept_sql);
    $stmt_dept->execute();
    $departments_list = $stmt_dept->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($selected_dept) && !empty($selected_grade)) {
        
        $sql = "SELECT s.*, l.Lecture_Name, f.Teacher AS Teacher, h.Hall_Name 
                FROM schedule s
                LEFT JOIN lectures l ON s.Lecture_ID = l.Lecture_ID
                LEFT JOIN faculty f ON s.Teacher_ID = f.Teacher_ID
                LEFT JOIN halls h ON s.Hall_ID = h.Hall_ID
                WHERE s.Department_ID = ? AND s.Grade = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$selected_dept, $selected_grade]);
        $records = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (is_array($records) && !empty($records)) {
            foreach ($records as $row) {
                $d = trim($row['Day']);
                $t = trim($row['Time_Slot']);
                $schedule_data[$d][$t] = $row;
            }
        }
    }
} catch (Exception $e) {
    $error_msg = $e->getMessage();
}
?>

<style>
    .table-excel { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
    .table-excel th, .table-excel td { border: 2px solid #a0a0a0 !important; text-align: center; vertical-align: middle; padding: 0.4rem; }
    .bg-dark-green { background-color: #198754 !important; color: white; font-weight: bold; }
    .bg-light-green { background-color: #90EE90 !important; font-weight: bold; width: 10%; }
    .bg-light-gray { background-color: #f8f9fa !important; width: 12%; font-weight: bold; }
    .bg-white-data { background-color: #ffffff !important; }
    .bg-empty { background-color: #f1f3f5 !important; color: #adb5bd; }
</style>

<div class="content-area">
    <div class="page-header d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="page-title">الجداول الدراسية</h2>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="../../index.php">الرئيسية</a></li>
                    <li class="breadcrumb-item active">عرض الجدول الأسبوعي</li>
                </ol>
            </nav>
        </div>
        <a href="add_schedule.php" class="btn btn-primary"><i class="fas fa-plus me-2"></i>إضافة جدول</a>
    </div>

    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle me-2"></i> <?= $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-times-circle me-2"></i> <?= $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" action="" class="row g-3 align-items-end">
                <div class="col-md-5">
                    <label class="form-label fw-bold">القسم الدارسي</label>
                    <select class="form-select" name="department_id" required>
                        <option value="" disabled selected>-- اختر القسم --</option>
                        <?php foreach ($departments_list as $dept): ?>
                            <option value="<?= $dept['Departement_ID'] ?>" <?= ($selected_dept == $dept['Departement_ID']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($dept['Departement']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-5">
                    <label class="form-label fw-bold">المرحلة الدراسية</label>
                    <select class="form-select" name="grade" required>
                        <option value="" disabled selected>-- اختر المرحلة --</option>
                        <?php 
                        $grades = ['المرحلة الأولى', 'المرحلة الثانية', 'المرحلة الثالثة', 'المرحلة الرابعة', 'المرحلة الخامسة'];
                        foreach ($grades as $g): ?>
                            <option value="<?= $g ?>" <?= ($selected_grade == $g) ? 'selected' : '' ?>><?= $g ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-dark w-100"><i class="fas fa-search me-2"></i>عرض الجدول</button>
                </div>
            </form>
        </div>
    </div>

    <?php if (!empty($selected_dept) && !empty($selected_grade) && empty($error_msg)): ?>
        <div class="card shadow-sm">
            <div class="card-body p-0 table-responsive">
                <table class="table table-excel mb-0">
                    <thead>
                        <tr>
                            <th colspan="6" class="bg-dark-green text-center py-3 fs-5" style="color:white !important;">
                                الجدول الأسبوعي - <?= htmlspecialchars($selected_grade) ?>
                            </th>
                        </tr>
                        <tr class="bg-dark-green">
                            <th>اليوم</th>
                            <th>الساعة</th>
                            <th>المادة</th>
                            <th>التدريسي</th>
                            <th>القاعة</th>
                            <th style="width: 8%;">الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($days as $day): ?>
                            <?php foreach ($times as $index => $time): ?>
                                <?php $cell = $schedule_data[$day][$time] ?? null; ?>
                                <tr>
                                    <?php if ($index === 0): ?>
                                        <td rowspan="6" class="bg-light-green fs-5"><?= $day ?></td>
                                    <?php endif; ?>
                                    
                                    <td class="bg-light-gray" dir="ltr"><?= $time ?></td>
                                    
                                    <?php if ($cell && (!empty($cell['Lecture_ID']) || !empty($cell['Teacher_ID']) || !empty($cell['Hall_ID']))): ?>
                                        <td class="bg-white-data fw-bold text-primary"><?= htmlspecialchars($cell['Lecture_Name'] ?? '---') ?></td>
                                        <td class="bg-white-data"><?= htmlspecialchars($cell['Teacher'] ?? '---') ?></td>
                                        <td class="bg-white-data fw-bold text-danger"><?= htmlspecialchars($cell['Hall_Name'] ?? '---') ?></td>
                                        <td class="bg-white-data">
                                            <a href="add_schedule.php?edit=<?= $cell['Schedule_ID'] ?>" class="btn btn-sm btn-outline-primary" title="تعديل المادة">
                                                <i class="fas fa-pencil-alt"></i>
                                            </a>
                                            <button type="button" class="btn btn-sm btn-outline-danger" title="حذف المادة" 
                                                    data-bs-toggle="modal" 
                                                    data-bs-target="#deleteModal"
                                                    data-id="<?= htmlspecialchars($cell['Schedule_ID']) ?>"
                                                    data-subject="<?= htmlspecialchars($cell['Lecture_Name'] ?? 'غير محدد') ?>"
                                                    data-teacher="<?= htmlspecialchars($cell['Teacher'] ?? 'غير محدد') ?>">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    <?php else: ?>
                                        <td class="bg-empty"></td>
                                        <td class="bg-empty"></td>
                                        <td class="bg-empty"></td>
                                        <td class="bg-empty"></td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteModalLabel">تأكيد الحذف</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>هل أنت متأكد من حذف هذه المحاضرة من الجدول؟</p>
                <div class="alert alert-light border">
                    <strong>المادة:</strong> <span id="del-subject" class="text-primary"></span><br>
                    <strong>التدريسي:</strong> <span id="del-teacher" class="text-dark"></span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <a href="#" id="confirmDeleteBtn" class="btn btn-danger">نعم، احذف</a>
            </div>
        </div>
    </div>
</div>

<script>
// كود JavaScript الآمن الخاص بـ Bootstrap 5 للتعامل مع المودل
document.addEventListener('DOMContentLoaded', function () {
    var deleteModal = document.getElementById('deleteModal');
    if (deleteModal) {
        deleteModal.addEventListener('show.bs.modal', function (event) {
            // الزر الذي قام بفتح المودل
            var button = event.relatedTarget;
            
            // استخراج المعلومات من الـ data-attributes
            var scheduleId = button.getAttribute('data-id');
            var subjectName = button.getAttribute('data-subject');
            var teacherName = button.getAttribute('data-teacher');
            
            // تحديث محتوى المودل
            document.getElementById('del-subject').textContent = subjectName;
            document.getElementById('del-teacher').textContent = teacherName;
            
            // تحديث رابط الحذف في زر التأكيد
            document.getElementById('confirmDeleteBtn').href = 'delete_schedule.php?id=' + scheduleId;
        });
    }
});
</script>

<?php include '../../includes/footer.php'; ?>