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

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

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

if (!hasPermission('delete_scores')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لحذف الدرجات.';
    ob_end_clean();
    header('Location: ../../index.php');
    exit();
}

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

$type = $_GET['type'] ?? '';

try {
    if ($type === 'single' && !empty($_GET['score_id'])) {
        $stmt = $pdo->prepare("DELETE FROM student_scores WHERE Score_ID = ?");
        $stmt->execute([$_GET['score_id']]);
        $_SESSION['success_message'] = 'تم حذف الدرجة بنجاح.';

    } elseif ($type === 'student_semester' && !empty($_GET['student_id']) && !empty($_GET['lecture_id']) && !empty($_GET['semester']) && !empty($_GET['year'])) {
        $stmt = $pdo->prepare("DELETE FROM student_scores WHERE Student_ID = ? AND Lecture_ID = ? AND Semester = ? AND Academic_Year = ?");
        $stmt->execute([$_GET['student_id'], $_GET['lecture_id'], $_GET['semester'], $_GET['year']]);
        $_SESSION['success_message'] = 'تم حذف درجات الطالب المحددة بنجاح.';
        
    } else {
        $_SESSION['error_message'] = 'معطيات الحذف غير مكتملة.';
    }
} catch (Exception $e) {
    $_SESSION['error_message'] = 'خطأ في قاعدة البيانات: ' . $e->getMessage();
}

ob_end_clean();
if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
    header('Location: ' . $_SERVER['HTTP_REFERER']);
} else {
    header('Location: index.php');
}
exit();
?>