<?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;
$errors = [];
$success_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'];
$grades_list = ['المرحلة الأولى', 'المرحلة الثانية', 'المرحلة الثالثة', 'المرحلة الرابعة', 'المرحلة الخامسة'];

// تحويل النص إلى رقم لمطابقته مع جدول المحاضرات
$grades_map = [
    'المرحلة الأولى' => 1,
    'المرحلة الثانية' => 2,
    'المرحلة الثالثة' => 3,
    'المرحلة الرابعة' => 4,
    'المرحلة الخامسة' => 5
];

// --- معالجة حالة التعديل (?edit=ID) ---
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT Department_ID, Grade FROM schedule WHERE Schedule_ID = ? LIMIT 1");
    $stmt->execute([$edit_id]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($res) {
        $_GET['department_id'] = $res['Department_ID'];
        $_GET['grade'] = $res['Grade'];
        $pageTitle = 'تعديل جدول دراسي';
    }
}

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

// --- جلب البيانات الأساسية للجدول ---
$departments = $pdo->query("SELECT Departement_ID, Departement FROM departemenets ORDER BY Departement ASC")->fetchAll(PDO::FETCH_ASSOC);

$lectures = [];
$teachers = [];
$halls = [];
$existing_schedule = [];

if (!empty($selected_dept) && !empty($selected_grade)) {
    
    // 1. جلب المواد (هنا تم استخدام التحويل الرقمي للمرحلة)
    $numeric_grade = $grades_map[$selected_grade] ?? 0;
    $stmt = $pdo->prepare("SELECT Lecture_ID, Lecture_Name FROM lectures WHERE Department_ID = ? AND Grade = ?");
    $stmt->execute([$selected_dept, $numeric_grade]);
    $lectures = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 2. جلب التدريسيين
    $stmt = $pdo->prepare("SELECT Teacher_ID, Teacher FROM faculty WHERE Department_ID = ? OR College_ID IN (SELECT College_ID FROM departemenets WHERE Departement_ID = ?)");
    $stmt->execute([$selected_dept, $selected_dept]);
    $teachers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 3. جلب القاعات والمختبرات
    $stmt = $pdo->prepare("SELECT Hall_ID, Hall_Name, Type FROM halls WHERE Department_ID = ?");
    $stmt->execute([$selected_dept]);
    $halls = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 4. جلب الجدول الحالي لملء الحقول مسبقاً
    $stmt = $pdo->prepare("SELECT * FROM schedule WHERE Department_ID = ? AND Grade = ?");
    $stmt->execute([$selected_dept, $selected_grade]);
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($records as $row) {
        $existing_schedule[$row['Day']][$row['Time_Slot']] = $row;
    }
}

// --- معالجة الحفظ (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $dept_id = $_POST['department_id'] ?? '';
    $grade = $_POST['grade'] ?? '';
    $schedule_inputs = $_POST['schedule'] ?? [];

    if (empty($dept_id) || empty($grade)) {
        $errors[] = 'يرجى تحديد القسم والمرحلة أولاً.';
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            $del_stmt = $pdo->prepare("DELETE FROM schedule WHERE Department_ID = ? AND Grade = ?");
            $del_stmt->execute([$dept_id, $grade]);

            $ins_stmt = $pdo->prepare("INSERT INTO schedule (Department_ID, Grade, Day, Time_Slot, Lecture_ID, Teacher_ID, Hall_ID) VALUES (?, ?, ?, ?, ?, ?, ?)");

            foreach ($days as $day) {
                foreach ($times as $time) {
                    $cell = $schedule_inputs[$day][$time] ?? [];
                    $l_id = !empty($cell['lecture_id']) ? $cell['lecture_id'] : null;
                    $t_id = !empty($cell['teacher_id']) ? $cell['teacher_id'] : null;
                    $h_id = !empty($cell['hall_id']) ? $cell['hall_id'] : null;

                    if ($l_id || $t_id || $h_id) {
                        $ins_stmt->execute([$dept_id, $grade, $day, $time, $l_id, $t_id, $h_id]);
                    }
                }
            }

            $pdo->commit();
            $_SESSION['success_message'] = 'تم حفظ الجدول الدراسي بنجاح!';
            header("Location: index.php?department_id={$dept_id}&grade=" . urlencode($grade));
            exit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = 'حدث خطأ أثناء حفظ الجدول: ' . $e->getMessage();
        }
    }
}
?>

<style>
    .table-excel { border-collapse: collapse; width: 100%; font-size: 0.85rem; }
    .table-excel th, .table-excel td { border: 2px solid #a0a0a0 !important; text-align: center; vertical-align: middle; padding: 0.25rem; }
    .bg-dark-green { background-color: #198754 !important; color: white; font-weight: bold; }
    .bg-light-green { background-color: #90EE90 !important; font-weight: bold; width: 8%; }
    .bg-light-gray { background-color: #f8f9fa !important; width: 10%; font-weight: bold; }
    .input-cell { background-color: #ADD8E6 !important; padding: 4px !important; }
    .input-cell select.form-select-sm { background-color: transparent; border: none; border-bottom: 1px dashed rgba(0,0,0,0.2); border-radius: 0; margin-bottom: 5px; padding: 2px 4px; font-size: 0.8rem; font-weight: bold; box-shadow: none; cursor: pointer; }
    .input-cell select.form-select-sm:focus { outline: none; border-bottom: 1px solid #000; }
    .input-cell select.form-select-sm:last-child { margin-bottom: 0; border-bottom: none; }
</style>

<div class="content-area">
    <div class="page-header mb-4">
        <h2 class="page-title"><?= $pageTitle ?></h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">الجداول الدراسية</a></li>
                <li class="breadcrumb-item active"><?= $pageTitle ?></li>
            </ol>
        </nav>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $error) echo "<li>" . htmlspecialchars($error) . "</li>"; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm mb-4 border-primary">
        <div class="card-header bg-primary text-white">
            <h6 class="mb-0"><i class="fas fa-filter me-2"></i> الخطوة الأولى: تحديد القسم والمرحلة</h6>
        </div>
        <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 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 foreach ($grades_list 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-outline-primary w-100"><i class="fas fa-sync me-2"></i>تحميل الجدول</button>
                </div>
            </form>
        </div>
    </div>

    <?php if (!empty($selected_dept) && !empty($selected_grade)): ?>
        <div class="card shadow-sm border-success">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                <h6 class="mb-0"><i class="fas fa-table me-2"></i> الخطوة الثانية: إدخال المحاضرات للمرحلة (<?= htmlspecialchars($selected_grade) ?>)</h6>
            </div>
            <div class="card-body p-0">
                <form method="POST" action="">
                    <input type="hidden" name="department_id" value="<?= htmlspecialchars($selected_dept) ?>">
                    <input type="hidden" name="grade" value="<?= htmlspecialchars($selected_grade) ?>">

                    <div class="table-responsive">
                        <table class="table table-excel mb-0">
                            <thead>
                                <tr class="bg-dark-green text-center">
                                    <th>اليوم</th>
                                    <th>الساعة</th>
                                    <th>معلومات المحاضرة (مادة - تدريسي - قاعة)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($days as $day): ?>
                                    <?php foreach ($times as $index => $time): ?>
                                        <?php 
                                            $cell_data = $existing_schedule[$day][$time] ?? [];
                                            $curr_lec = $cell_data['Lecture_ID'] ?? '';
                                            $curr_tech = $cell_data['Teacher_ID'] ?? '';
                                            $curr_hall = $cell_data['Hall_ID'] ?? '';
                                            $base_name = "schedule[{$day}][{$time}]"; 
                                        ?>
                                        <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>
                                            
                                            <td class="input-cell">
                                                <select class="form-select form-select-sm" name="<?= $base_name ?>[lecture_id]">
                                                    <option value="">-- اختر المادة --</option>
                                                    <?php foreach ($lectures as $lec): ?>
                                                        <option value="<?= $lec['Lecture_ID'] ?>" <?= ($curr_lec == $lec['Lecture_ID']) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($lec['Lecture_Name']) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>

                                                <select class="form-select form-select-sm text-primary" name="<?= $base_name ?>[teacher_id]">
                                                    <option value="">-- اختر التدريسي --</option>
                                                    <?php foreach ($teachers as $tech): ?>
                                                        <option value="<?= $tech['Teacher_ID'] ?>" <?= ($curr_tech == $tech['Teacher_ID']) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($tech['Teacher']) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>

                                                <select class="form-select form-select-sm text-danger" name="<?= $base_name ?>[hall_id]">
                                                    <option value="">-- اختر القاعة --</option>
                                                    <?php foreach ($halls as $hall): ?>
                                                        <option value="<?= $hall['Hall_ID'] ?>" <?= ($curr_hall == $hall['Hall_ID']) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($hall['Hall_Name'] . (($hall['Type'] == 1) ? ' (مختبر)' : '')) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="p-3 bg-light border-top d-flex justify-content-end gap-2">
                        <a href="index.php" class="btn btn-secondary px-4">إلغاء</a>
                        <button type="submit" class="btn btn-success px-5"><i class="fas fa-save me-2"></i>حفظ الجدول الأسبوعي</button>
                    </div>
                </form>
            </div>
        </div>
    <?php else: ?>
        <div class="alert alert-info text-center mt-3">
            <i class="fas fa-info-circle fa-2x mb-2"></i><br>
            يرجى تحديد القسم والمرحلة من الأعلى والضغط على "تحميل الجدول" للبدء بإدخال البيانات.
        </div>
    <?php endif; ?>
</div>

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