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

include '../../includes/header.php';

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

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

// التحقق من نوع المستخدم
$is_student = !empty($_SESSION['student_id']);
$student_id = $is_student ? $_SESSION['student_id'] : ($_GET['student_id'] ?? 0);

if (!$is_student && !hasPermission('view_scores')) {
    header('Location: ../../index.php');
    exit();
}

try {
    // جلب بيانات الطالب
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$student) throw new Exception("الطالب غير موجود.");
} catch (Exception $e) {
    $_SESSION['error_message'] = $e->getMessage();
    header('Location: index.php');
    exit();
}

$pageTitle = htmlspecialchars($student['full_name']);

// المتغيرات الأساسية (لاحظ استخدام Departement_ID كما هي في الداتا بيز)
$sel_dept = $student['Departement_ID'];
$sel_grade = $student['grade_level'];
$sel_semester = $_GET['semester'] ?? '1';
$sel_year = $_GET['year'] ?? '2025-2026';

function gradeToNumber($grade_level) {
    $map = ['المرحلة الأولى'=>'1','المرحلة الثانية'=>'2','المرحلة الثالثة'=>'3','المرحلة الرابعة'=>'4','المرحلة الخامسة'=>'5'];
    return $map[$grade_level] ?? '1';
}

$lecture_details = [];
$total_weighted_sum = 0;
$total_ects = 0;
$has_failed_lecture = false; // متغير للتحقق من الرسوب في أي مادة

try {
    $grade_num = gradeToNumber($sel_grade);
    
    // جلب المواد الخاصة بقسم ومرحلة الطالب
    $stmt = $pdo->prepare("SELECT Lecture_ID, Lecture_Name, ECTS FROM lectures WHERE Department_ID = ? AND Grade = ?");
    $stmt->execute([$sel_dept, $grade_num]);
    $lectures = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // جلب جميع مكونات الدرجات
    $stmt = $pdo->prepare("SELECT * FROM score_components ORDER BY display_order ASC");
    $stmt->execute();
    $all_components = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // جلب درجات الطالب في هذا الفصل والعام
    $stmt = $pdo->prepare("SELECT Component_ID, Score FROM student_scores WHERE Student_ID = ? AND Academic_Year = ? AND Semester = ?");
    $stmt->execute([$student_id, $sel_year, $sel_semester]);
    $student_scores = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $sc) {
        $student_scores[$sc['Component_ID']] = $sc['Score'];
    }

    // حساب الدرجات والنسب
    foreach ($lectures as $l) {
        $lid = $l['Lecture_ID'];
        $earned_sum = 0;
        $max_sum = 0;
        $comps = [];

        foreach ($all_components as $c) {
            if ($c['Lecture_ID'] == $lid) {
                $score = $student_scores[$c['Component_ID']] ?? 0;
                $earned_sum += $score;
                $max_sum += $c['Max_Score'];
                $comps[] = ['name' => $c['Component_Name'], 'score' => $score, 'max' => $c['Max_Score']];
            }
        }

        $pct = $max_sum > 0 ? ($earned_sum / $max_sum) * 100 : 0;
        
        // التحقق مما إذا كان الطالب راسباً في هذه المادة
        if ($max_sum > 0 && $pct < 50) {
            $has_failed_lecture = true;
        }

        $total_weighted_sum += ($pct * $l['ECTS']);
        $total_ects += $l['ECTS'];

        $lecture_details[] = [
            'id' => $lid,
            'name' => $l['Lecture_Name'],
            'ects' => $l['ECTS'],
            'earned' => $earned_sum,
            'max' => $max_sum,
            'pct' => round($pct, 1),
            'comps' => $comps
        ];
    }
} catch (Exception $e) {
    $error_msg = $e->getMessage();
}

// حساب المعدل النهائي وتحديد حالة النجاح
$final_avg = $total_ects > 0 ? round($total_weighted_sum / $total_ects, 2) : 0;
$is_passed = ($final_avg >= 50 && !$has_failed_lecture && $total_ects > 0);
?>

<div class="content-area">
    <div class="page-header d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="page-title"><?= $pageTitle ?></h2>
            <p class="page-subtitle text-muted"><?= htmlspecialchars($student['Departement'] ?? '') ?> | <?= htmlspecialchars($sel_grade) ?> | الفصل <?= htmlspecialchars($sel_semester) ?></p>
        </div>
        <?php if (!$is_student): ?>
            <a href="index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-right me-2"></i>العودة للقائمة</a>
        <?php endif; ?>
    </div>

    <?php if ($is_student): ?>
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-body p-3">
            <form method="GET" action="" class="d-flex gap-3 align-items-end">
                <div>
                    <label class="form-label small">الفصل الدراسي</label>
                    <select class="form-select form-select-sm" name="semester">
                        <option value="1" <?= $sel_semester == '1' ? 'selected' : '' ?>>الفصل الأول</option>
                        <option value="2" <?= $sel_semester == '2' ? 'selected' : '' ?>>الفصل الثاني</option>
                    </select>
                </div>
                <div>
                    <label class="form-label small">العام الدراسي</label>
                    <input type="text" class="form-control form-control-sm" name="year" value="<?= htmlspecialchars($sel_year) ?>">
                </div>
                <button type="submit" class="btn btn-primary btn-sm px-4">عرض</button>
            </form>
        </div>
    </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">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3">المادة</th>
                        <th>ECTS</th>
                        <th>الدرجة المحصلة</th>
                        <th>من</th>
                        <th>النسبة</th>
                        <th>الحالة</th>
                        <th class="text-center">تفاصيل</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($lecture_details)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-4 text-muted">لا توجد مواد مسجلة لهذا الفصل.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($lecture_details as $ld): ?>
                            <tr>
                                <td class="ps-3 fw-bold"><?= htmlspecialchars($ld['name']) ?></td>
                                <td><span class="badge bg-secondary"><?= $ld['ects'] ?></span></td>
                                <td class="fw-bold text-primary"><?= $ld['earned'] ?></td>
                                <td><?= $ld['max'] ?></td>
                                <td><?= $ld['pct'] ?>%</td>
                                <td>
                                    <?php if ($ld['max'] == 0): ?>
                                        <span class="badge bg-secondary">غير مدخل</span>
                                    <?php elseif ($ld['pct'] >= 50): ?>
                                        <span class="badge bg-success">ناجح</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">راسب</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#modal-<?= $ld['id'] ?>">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card shadow-sm border-0 <?= $is_passed ? 'bg-success' : ($total_ects == 0 ? 'bg-secondary' : 'bg-danger') ?> text-white mt-4">
        <div class="card-body d-flex justify-content-between align-items-center p-4">
            <div>
                <h4 class="mb-1">المعدل المرجح للفصل الدراسي</h4>
                <h1 class="display-5 fw-bold mb-0">
                    <?php if ($total_ects == 0): ?>
                        ---
                    <?php elseif (!$is_passed): ?>
                        راسب
                    <?php else: ?>
                        <?= $final_avg ?>%
                    <?php endif; ?>
                </h1>
            </div>
            <div class="text-end">
                <h4 class="mb-1">الحالة العامة</h4>
                <h2 class="mb-0">
                    <?php if ($total_ects == 0): ?> 
                        غير متوفر 
                    <?php elseif ($is_passed): ?> 
                        ناجح <i class="fas fa-check-circle"></i> 
                    <?php else: ?> 
                        راسب <i class="fas fa-times-circle"></i> 
                    <?php endif; ?>
                </h2>
            </div>
        </div>
    </div>
</div>

<?php foreach ($lecture_details as $ld): ?>
    <div class="modal fade" id="modal-<?= $ld['id'] ?>" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-light">
                    <h5 class="modal-title">تفاصيل درجات <?= htmlspecialchars($ld['name']) ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0">
                    <table class="table mb-0 text-center">
                        <thead class="table-dark">
                            <tr><th>المكوّن</th><th>الدرجة</th><th>من</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($ld['comps'] as $c): ?>
                                <tr>
                                    <td><?= htmlspecialchars($c['name']) ?></td>
                                    <td class="fw-bold text-primary"><?= $c['score'] ?></td>
                                    <td><?= $c['max'] ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <tr class="table-secondary fw-bold">
                                <td>المجموع</td>
                                <td class="text-primary"><?= $ld['earned'] ?></td>
                                <td><?= $ld['max'] ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>

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