<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'مكونات الدرجات';
include '../../includes/header.php';

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

if (!hasPermission('manage_score_components')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لإدارة مكونات الدرجات.';
    header('Location: ../../index.php');
    exit();
}

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

// Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'add') {
            $stmt = $pdo->prepare("INSERT INTO score_components (Lecture_ID, Component_Name, Max_Score, display_order) VALUES (?, ?, ?, ?)");
            $stmt->execute([$_POST['lecture_id'], $_POST['name'], $_POST['max_score'], $_POST['order']]);
            $_SESSION['success_message'] = 'تم إضافة المكون بنجاح.';
        } elseif ($action === 'edit') {
            $stmt = $pdo->prepare("UPDATE score_components SET Component_Name = ?, Max_Score = ?, display_order = ? WHERE Component_ID = ?");
            $stmt->execute([$_POST['name'], $_POST['max_score'], $_POST['order'], $_POST['component_id']]);
            $_SESSION['success_message'] = 'تم التعديل بنجاح.';
        } elseif ($action === 'delete') {
            $pdo->beginTransaction();
            $pdo->prepare("DELETE FROM student_scores WHERE Component_ID = ?")->execute([$_POST['component_id']]);
            $pdo->prepare("DELETE FROM score_components WHERE Component_ID = ?")->execute([$_POST['component_id']]);
            $pdo->commit();
            $_SESSION['success_message'] = 'تم حذف المكون وجميع الدرجات المرتبطة به.';
        }
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
        $_SESSION['error_message'] = $e->getMessage();
    }
    header("Location: score_components.php?college_id=" . ($_POST['college_id'] ?? '') . "&department_id=" . ($_POST['department_id'] ?? '') . "&lecture_id=" . ($_POST['lecture_id'] ?? ''));
    exit();
}

$colleges = $pdo->query("SELECT College_ID, College FROM colleges ORDER BY College ASC")->fetchAll(PDO::FETCH_ASSOC);
$departments = $pdo->query("SELECT Departement_ID, College_ID, Departement FROM departemenets ORDER BY Departement ASC")->fetchAll(PDO::FETCH_ASSOC);

$sel_col = $_GET['college_id'] ?? '';
$sel_dept = $_GET['department_id'] ?? '';
$sel_lec = $_GET['lecture_id'] ?? '';

$lectures = [];
if (!empty($sel_dept)) {
    $stmt = $pdo->prepare("SELECT Lecture_ID, Lecture_Name, Grade FROM lectures WHERE Department_ID = ?");
    $stmt->execute([$sel_dept]);
    $lectures = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$components = [];
$total_max = 0;
if (!empty($sel_lec)) {
    $stmt = $pdo->prepare("SELECT * FROM score_components WHERE Lecture_ID = ? ORDER BY display_order ASC");
    $stmt->execute([$sel_lec]);
    $components = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($components as $c) $total_max += $c['Max_Score'];
}
?>

<div class="content-area">
    <div class="page-header d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="page-title">مكونات الدرجات</h2>
            <p class="page-subtitle text-muted">تحديد مكونات وأوزان الدرجات لكل مادة</p>
        </div>
    </div>

    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm border-0 mb-4">
        <div class="card-body">
            <form method="GET" action="" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">الكلية</label>
                    <select class="form-select" id="college_id" name="college_id" onchange="filterData()">
                        <option value="">-- اختر --</option>
                        <?php foreach ($colleges as $c): ?>
                            <option value="<?= $c['College_ID'] ?>" <?= $sel_col == $c['College_ID'] ? 'selected' : '' ?>><?= htmlspecialchars($c['College']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">القسم</label>
                    <select class="form-select" id="department_id" name="department_id" onchange="this.form.submit()" required>
                        <option value="">-- اختر --</option>
                        <?php foreach ($departments as $d): ?>
                            <?php if ($d['College_ID'] == $sel_col || $sel_col == ''): ?>
                                <option value="<?= $d['Departement_ID'] ?>" <?= $sel_dept == $d['Departement_ID'] ? 'selected' : '' ?>><?= htmlspecialchars($d['Departement']) ?></option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">المادة</label>
                    <select class="form-select" name="lecture_id" onchange="this.form.submit()" required>
                        <option value="">-- اختر --</option>
                        <?php foreach ($lectures as $l): ?>
                            <option value="<?= $l['Lecture_ID'] ?>" <?= $sel_lec == $l['Lecture_ID'] ? 'selected' : '' ?>><?= htmlspecialchars($l['Lecture_Name']) ?> (المرحلة <?= $l['Grade'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">عرض</button>
                </div>
            </form>
        </div>
    </div>

    <?php if (!empty($sel_lec)): ?>
        <?php if ($total_max > 100): ?>
            <div class="alert alert-warning">تنبيه: مجموع الدرجات الحالية (<?= $total_max ?>) يتجاوز 100.</div>
        <?php endif; ?>

        <div class="card shadow-sm border-0 mb-4">
            <div class="card-body p-0 table-responsive">
                <table class="table table-hover align-middle table-striped mb-0 text-center">
                    <thead class="table-light">
                        <tr>
                            <th>الترتيب</th>
                            <th>اسم المكوّن</th>
                            <th>الدرجة القصوى</th>
                            <th>إجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($components as $c): ?>
                            <tr>
                                <td><?= $c['display_order'] ?></td>
                                <td class="fw-bold"><?= htmlspecialchars($c['Component_Name']) ?></td>
                                <td class="text-primary fw-bold"><?= $c['Max_Score'] ?></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal<?= $c['Component_ID'] ?>"><i class="fas fa-edit"></i></button>
                                    <button class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteModal<?= $c['Component_ID'] ?>"><i class="fas fa-trash"></i></button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <div class="card-footer bg-light p-3">
                <form method="POST" class="row g-2 align-items-end">
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="college_id" value="<?= $sel_col ?>">
                    <input type="hidden" name="department_id" value="<?= $sel_dept ?>">
                    <input type="hidden" name="lecture_id" value="<?= $sel_lec ?>">
                    <div class="col-md-4">
                        <label class="form-label small">اسم المكوّن الجديد (مثال: midterm)</label>
                        <input type="text" name="name" class="form-control form-control-sm" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small">الدرجة القصوى</label>
                        <input type="number" name="max_score" class="form-control form-control-sm" min="1" max="100" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small">الترتيب</label>
                        <input type="number" name="order" class="form-control form-control-sm" value="<?= count($components)+1 ?>" required>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-success btn-sm w-100"><i class="fas fa-plus"></i> إضافة</button>
                    </div>
                </form>
            </div>
        </div>

        <?php foreach ($components as $c): ?>
            <div class="modal fade" id="editModal<?= $c['Component_ID'] ?>" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content text-start">
                        <form method="POST">
                            <div class="modal-header">
                                <h5 class="modal-title">تعديل المكوّن</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" name="action" value="edit">
                                <input type="hidden" name="component_id" value="<?= $c['Component_ID'] ?>">
                                <input type="hidden" name="college_id" value="<?= $sel_col ?>">
                                <input type="hidden" name="department_id" value="<?= $sel_dept ?>">
                                <input type="hidden" name="lecture_id" value="<?= $sel_lec ?>">
                                
                                <div class="mb-3">
                                    <label class="form-label">الاسم</label>
                                    <input type="text" class="form-control" name="name" value="<?= htmlspecialchars($c['Component_Name']) ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">الدرجة القصوى</label>
                                    <input type="number" class="form-control" name="max_score" value="<?= $c['Max_Score'] ?>" min="1" max="100" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">الترتيب</label>
                                    <input type="number" class="form-control" name="order" value="<?= $c['display_order'] ?>" required>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                                <button type="submit" class="btn btn-primary">حفظ</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="deleteModal<?= $c['Component_ID'] ?>" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content text-start">
                        <form method="POST">
                            <div class="modal-header bg-danger text-white">
                                <h5 class="modal-title">تأكيد الحذف</h5>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="component_id" value="<?= $c['Component_ID'] ?>">
                                <input type="hidden" name="college_id" value="<?= $sel_col ?>">
                                <input type="hidden" name="department_id" value="<?= $sel_dept ?>">
                                <input type="hidden" name="lecture_id" value="<?= $sel_lec ?>">
                                <p>سيتم حذف المكوّن <strong><?= htmlspecialchars($c['Component_Name']) ?></strong> وكافة الدرجات المرتبطة به. هل أنت متأكد؟</p>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                                <button type="submit" class="btn btn-danger">نعم، احذف</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>

    <?php endif; ?>
</div>

<script>
const allDepts = <?php echo json_encode($departments); ?>;
function filterData() {
    let col = document.getElementById('college_id').value;
    let dept = document.getElementById('department_id');
    dept.innerHTML = '<option value="">-- اختر --</option>';
    allDepts.forEach(d => {
        if (!col || d.College_ID == col) {
            let opt = document.createElement('option');
            opt.value = d.Departement_ID;
            opt.textContent = d.Departement;
            dept.appendChild(opt);
        }
    });
}
</script>

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