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

$pageTitle = 'إدخال الدرجات';
include '../../includes/header.php';

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

$is_teacher = !empty($_SESSION['teacher_id']);
$can_edit_all = hasPermission('edit_scores');

// if (!$is_teacher && !$can_edit_all) {
//     header('Location: ../../index.php');
//     exit();
// }

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

$sel_teacher = $is_teacher ? $_SESSION['teacher_id'] : ($_GET['teacher_id'] ?? '');
$sel_lecture = $_GET['lecture_id'] ?? '';
$sel_semester = $_GET['semester'] ?? '1';
$sel_year = $_GET['academic_year'] ?? '2025-2026';

$teachers = [];
$lectures = [];
$components = [];
$students = [];
$existing_scores = [];

try {
    if ($can_edit_all) {
        $teachers = $pdo->query("SELECT Teacher_ID, Teacher FROM faculty ORDER BY Teacher ASC")->fetchAll(PDO::FETCH_ASSOC);
    }

    if (!empty($sel_teacher)) {
        // Fallback: Check schedule, if empty get from lectures where dept matches teacher
        $stmt = $pdo->prepare("SELECT DISTINCT l.Lecture_ID, l.Lecture_Name, d.Departement as dept, l.Grade 
                               FROM schedule s 
                               JOIN lectures l ON s.Lecture_ID = l.Lecture_ID 
                               JOIN departemenets d ON l.Department_ID = d.Departement_ID
                               WHERE s.Teacher_ID = ?");
        $stmt->execute([$sel_teacher]);
        $lectures = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (empty($lectures)) {
            $stmt = $pdo->prepare("SELECT l.Lecture_ID, l.Lecture_Name, d.Departement as dept, l.Grade 
                                   FROM lectures l 
                                   JOIN faculty f ON l.Department_ID = f.Department_ID 
                                   JOIN departemenets d ON l.Department_ID = d.Departement_ID
                                   WHERE f.Teacher_ID = ?");
            $stmt->execute([$sel_teacher]);
            $lectures = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }

    if (!empty($sel_lecture)) {
        // Get components
        $stmt = $pdo->prepare("SELECT * FROM score_components WHERE Lecture_ID = ? ORDER BY display_order ASC");
        $stmt->execute([$sel_lecture]);
        $components = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!empty($components)) {
            // Get Lecture info to find Dept and Grade
            $stmt = $pdo->prepare("SELECT Department_ID, Grade FROM lectures WHERE Lecture_ID = ?");
            $stmt->execute([$sel_lecture]);
            $lec_info = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $grade_map = ['1'=>'المرحلة الأولى','2'=>'المرحلة الثانية','3'=>'المرحلة الثالثة','4'=>'المرحلة الرابعة','5'=>'المرحلة الخامسة'];
            $grade_str = $grade_map[$lec_info['Grade']] ?? 'المرحلة الأولى';

            // Fetch students
            $stmt = $pdo->prepare("SELECT id, full_name FROM students WHERE Departement_ID = ? AND grade_level = ?");
            $stmt->execute([$lec_info['Department_ID'], $grade_str]);
            $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Fetch existing scores
            $stmt = $pdo->prepare("SELECT Student_ID, Component_ID, Score FROM student_scores WHERE Lecture_ID = ? AND Academic_Year = ? AND Semester = ?");
            $stmt->execute([$sel_lecture, $sel_year, $sel_semester]);
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $sc) {
                $existing_scores[$sc['Student_ID']][$sc['Component_ID']] = $sc['Score'];
            }
        }
    }
} catch (Exception $e) {
    $_SESSION['error_message'] = $e->getMessage();
}

// POST Save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['scores'])) {
    try {
        $pdo->beginTransaction();
        $ins = $pdo->prepare("INSERT INTO student_scores (Student_ID, Lecture_ID, Component_ID, Teacher_ID, Academic_Year, Semester, Score, updated_at) 
                              VALUES (?, ?, ?, ?, ?, ?, ?, NOW()) 
                              ON DUPLICATE KEY UPDATE Score = VALUES(Score), updated_at = NOW()");
        
        foreach ($_POST['scores'] as $sid => $comps) {
            foreach ($comps as $cid => $score_val) {
                if ($score_val !== '') { // Only save non-empty
                    $ins->execute([$sid, $sel_lecture, $cid, $sel_teacher, $sel_year, $sel_semester, $score_val]);
                }
            }
        }
        $pdo->commit();
        $_SESSION['success_message'] = 'تم حفظ الدرجات بنجاح!';
        header("Location: teacher_grades.php?teacher_id=$sel_teacher&lecture_id=$sel_lecture&semester=$sel_semester&academic_year=$sel_year");
        exit();
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = $e->getMessage();
    }
}
?>

<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">
                <?php if ($can_edit_all): ?>
                <div class="col-md-3">
                    <label class="form-label">التدريسي</label>
                    <select class="form-select" name="teacher_id" onchange="this.form.submit()" required>
                        <option value="">-- اختر --</option>
                        <?php foreach ($teachers as $t): ?>
                            <option value="<?= $t['Teacher_ID'] ?>" <?= $sel_teacher == $t['Teacher_ID'] ? 'selected' : '' ?>><?= htmlspecialchars($t['Teacher']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>

                <div class="col-md-4">
                    <label class="form-label">المادة</label>
                    <select class="form-select" name="lecture_id" required>
                        <option value="">-- اختر --</option>
                        <?php foreach ($lectures as $l): ?>
                            <option value="<?= $l['Lecture_ID'] ?>" <?= $sel_lecture == $l['Lecture_ID'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($l['Lecture_Name']) ?> (<?= htmlspecialchars($l['dept']) ?> - المرحلة <?= $l['Grade'] ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">الفصل الدراسي</label>
                    <select class="form-select" name="semester" required>
                        <option value="1" <?= $sel_semester == '1' ? 'selected' : '' ?>>الفصل الأول</option>
                        <option value="2" <?= $sel_semester == '2' ? 'selected' : '' ?>>الفصل الثاني</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">العام الدراسي</label>
                    <input type="text" class="form-control" name="academic_year" value="<?= htmlspecialchars($sel_year) ?>" required>
                </div>
                <div class="col-md-1">
                    <button type="submit" class="btn btn-primary w-100">تحميل</button>
                </div>
            </form>
        </div>
    </div>

    <?php if (!empty($sel_lecture)): ?>
        <?php if (empty($components)): ?>
            <div class="alert alert-warning">
                لا يوجد مكونات درجات محددة لهذه المادة. يرجى <a href="score_components.php?lecture_id=<?= $sel_lecture ?>" class="alert-link">تحديد المكونات أولاً</a>.
            </div>
        <?php else: ?>
            <form method="POST" action="" id="gradesForm">
                <div class="card shadow-sm border-0">
                    <div class="card-body p-0 table-responsive">
                        <table class="table table-hover table-striped align-middle mb-0 text-center">
                            <thead class="table-light">
                                <tr>
                                    <th class="text-start ps-3" style="min-width: 200px; position: sticky; right: 0; background: #f8f9fa; z-index: 1;">اسم الطالب</th>
                                    <?php foreach ($components as $c): ?>
                                        <th><?= htmlspecialchars($c['Component_Name']) ?><br><small class="text-muted">(<?= $c['Max_Score'] ?>)</small></th>
                                    <?php endforeach; ?>
                                    <th class="bg-light">المجموع</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($students as $s): ?>
                                    <tr data-student-id="<?= $s['id'] ?>">
                                        <td class="text-start ps-3 fw-bold" style="position: sticky; right: 0; background: #fff; z-index: 1;"><?= htmlspecialchars($s['full_name']) ?></td>
                                        <?php $row_sum = 0; ?>
                                        <?php foreach ($components as $c): 
                                            $val = $existing_scores[$s['id']][$c['Component_ID']] ?? '';
                                            if ($val !== '') $row_sum += (float)$val;
                                        ?>
                                            <td>
                                                <input type="number" step="0.5" min="0" max="<?= $c['Max_Score'] ?>" 
                                                       name="scores[<?= $s['id'] ?>][<?= $c['Component_ID'] ?>]" 
                                                       value="<?= $val ?>" 
                                                       class="form-control form-control-sm text-center score-input mx-auto" 
                                                       style="width: 80px;"
                                                       oninput="calcRowSum(this, <?= $c['Max_Score'] ?>)">
                                            </td>
                                        <?php endforeach; ?>
                                        <td class="bg-light fw-bold text-primary row-total"><?= $row_sum ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer bg-white text-end p-3">
                        <a href="../../index.php" class="btn btn-secondary px-4">إلغاء</a>
                        <button type="submit" class="btn btn-primary px-5"><i class="fas fa-save me-2"></i>حفظ الدرجات</button>
                    </div>
                </div>
            </form>
            
            <script>
                function calcRowSum(input, maxScore) {
                    if (parseFloat(input.value) > maxScore) {
                        input.classList.add('bg-danger', 'text-white');
                    } else {
                        input.classList.remove('bg-danger', 'text-white');
                    }
                    let tr = input.closest('tr');
                    let inputs = tr.querySelectorAll('.score-input');
                    let sum = 0;
                    inputs.forEach(i => {
                        if (i.value !== '') sum += parseFloat(i.value);
                    });
                    tr.querySelector('.row-total').textContent = sum.toFixed(1).replace(/\.0$/, '');
                }

                let formChanged = false;
                document.getElementById('gradesForm').addEventListener('input', () => formChanged = true);
                document.getElementById('gradesForm').addEventListener('submit', () => formChanged = false);
                window.addEventListener('beforeunload', (e) => {
                    if (formChanged) e.returnValue = 'هناك تغييرات غير محفوظة!';
                });
            </script>
        <?php endif; ?>
    <?php endif; ?>
</div>

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