<?php
session_start();
include 'db.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

mysqli_set_charset($conn, "utf8mb4");

function esc($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

// ✅ دالة تنسيق العرض: 63.00 → 63 ، 24.67 تبقى 24.67
function fmt_num($v) {
    if ($v === '' || $v === null) return '';
    $v = (float)$v;
    if (fmod($v, 1) == 0.0) {
        return (string)(int)$v;
    }
    return rtrim(rtrim(number_format($v, 2, '.', ''), '0'), '.');
}

// ✅ دالة تقريب نصف فأعلى
function round_half_up_int($v) {
    $v = (float)$v;
    $i = floor($v);
    return ($v - $i >= 0.5) ? $i + 1 : $i;
}

// ✅ دالة توحيد اسم المرحلة
function norm_stage($s){
    $s = trim($s);
    $s = str_replace(array('الأ','ال',' '), array('ا','', ''), $s);
    return $s;
}

// ✅ دالة لأخذ أعلى 3 درجات (نخليها ديسمل هنا، ونقرّب بعدين)
function top3_avg_admin($arr) {
    $clean = array();
    foreach ($arr as $v) {
        $clean[] = floatval($v);
    }
    rsort($clean);
    $top3 = array_slice($clean, 0, 3);
    $sum = array_sum($top3);
    $count = count($top3) > 0 ? count($top3) : 1;
    return round($sum / $count, 2);
}

/* =========================
   1) جلب المراحل
   ========================= */
$stages_rs = mysqli_query($conn, "SELECT DISTINCT stage FROM students ORDER BY FIELD(stage,
'أول متوسط','ثاني متوسط','ثالث متوسط','رابع علمي','خامس علمي','سادس علمي'), stage");
$stages = [];
while($r = mysqli_fetch_assoc($stages_rs)) $stages[] = $r['stage'];

$stage   = isset($_GET['stage']) ? trim($_GET['stage']) : '';
$subject = isset($_GET['subject']) ? trim($_GET['subject']) : '';

/* =========================
   2) تصدير كل الدرجات
   ========================= */
if (isset($_GET['export_all'])) {
    header("Content-Type: application/vnd.ms-excel; charset=utf-8");
    header("Content-Disposition: attachment; filename=all_grades_export.xls");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo "<table border='1'>";
    echo "<tr>
        <th>اسم الطالب</th><th>الشعبة</th><th>المرحلة</th><th>المادة</th>
        <th>ش1</th><th>ش2</th><th>ش3</th><th>اليومي ف1</th><th>فصل1</th>
        <th>نصف السنة</th><th>ش1 (ف2)</th><th>ش2 (ف2)</th><th>ش3 (ف2)</th>
        <th>اليومي ف2</th><th>فصل2</th><th>معدل سنوي</th><th>النتيجة النهائية</th><th>تاريخ الحفظ</th>
    </tr>";

    $q = mysqli_query($conn, "
        SELECT s.name, s.stage, s.class, g.*
        FROM grades g
        JOIN students s ON s.id = g.student_id
        ORDER BY s.stage, s.class ASC, s.name ASC
    ");
    while($r = mysqli_fetch_assoc($q)) {
        echo "<tr>
            <td>".esc($r['name'])."</td>
            <td>".esc($r['class'])."</td>
            <td>".esc($r['stage'])."</td>
            <td>".esc($r['subject'])."</td>
            <td>".esc($r['month1'])."</td>
            <td>".esc($r['month2'])."</td>
            <td>".esc($r['month3'])."</td>
            <td>".esc($r['daily1'])."</td>
            <td>".esc($r['semester1'])."</td>
            <td>".esc($r['midterm'])."</td>
            <td>".esc($r['month4'])."</td>
            <td>".esc($r['month5'])."</td>
            <td>".esc($r['month6'])."</td>
            <td>".esc($r['daily2'])."</td>
            <td>".esc($r['semester2'])."</td>
            <td>".esc($r['annual_average'])."</td>
            <td>".esc($r['final_result'])."</td>
            <td>".esc($r['saved_at'])."</td>
        </tr>";
    }

    echo "</table>";
    exit;
}

/* =========================
   3) تصدير مادة محددة (بدون تقسيم مدرس)
   ========================= */
if (isset($_GET['export']) && $stage !== '' && $subject !== '') {
    $file_name = "درجات-" . str_replace(' ', '-', $stage) . "-" . str_replace(' ', '-', $subject) . ".xls";

    header("Content-Type: application/vnd.ms-excel; charset=utf-8");
    header("Content-Disposition: attachment; filename=$file_name");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo "<table border='1'>";
    echo "<tr>
        <th>اسم الطالب</th><th>الشعبة</th><th>المرحلة</th><th>المادة</th>
        <th>ش1</th><th>ش2</th><th>ش3</th><th>اليومي ف1</th><th>فصل1</th>
        <th>نصف السنة</th><th>ش1 (ف2)</th><th>ش2 (ف2)</th><th>ش3 (ف2)</th>
        <th>اليومي ف2</th><th>فصل2</th><th>معدل سنوي</th><th>النتيجة النهائية</th><th>تاريخ الحفظ</th>
    </tr>";

    $stage_esc   = mysqli_real_escape_string($conn, $stage);
    $subject_esc = mysqli_real_escape_string($conn, $subject);

    $q = mysqli_query($conn, "
        SELECT s.name, s.stage, s.class, g.*
        FROM grades g
        JOIN students s ON s.id = g.student_id
        WHERE REPLACE(s.stage,'الأ','ا') LIKE REPLACE('%$stage_esc%','الأ','ا')
          AND TRIM(LOWER(REPLACE(g.subject,'ال',''))) = TRIM(LOWER(REPLACE('$subject_esc','ال','')))
        ORDER BY s.class ASC, s.name ASC
    ");
    while($r = mysqli_fetch_assoc($q)) {
        echo "<tr>
            <td>".esc($r['name'])."</td>
            <td>".esc($r['class'])."</td>
            <td>".esc($r['stage'])."</td>
            <td>".esc($r['subject'])."</td>
            <td>".esc($r['month1'])."</td>
            <td>".esc($r['month2'])."</td>
            <td>".esc($r['month3'])."</td>
            <td>".esc($r['daily1'])."</td>
            <td>".esc($r['semester1'])."</td>
            <td>".esc($r['midterm'])."</td>
            <td>".esc($r['month4'])."</td>
            <td>".esc($r['month5'])."</td>
            <td>".esc($r['month6'])."</td>
            <td>".esc($r['daily2'])."</td>
            <td>".esc($r['semester2'])."</td>
            <td>".esc($r['annual_average'])."</td>
            <td>".esc($r['final_result'])."</td>
            <td>".esc($r['saved_at'])."</td>
        </tr>";
    }

    echo "</table>";
    exit;
}

/* =========================
   4) حفظ الدرجات (بدون teacher_id)
   ========================= */
$save_notice = "";
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['do_save'])) {
    $stage   = mysqli_real_escape_string($conn, $_POST['stage']);
    $subject = mysqli_real_escape_string($conn, $_POST['subject']);
    $grades  = $_POST['grades'];

    foreach ($grades as $sid => $g) {
        $sid = (int)$sid;

        $month1 = isset($g['month1']) ? (float)$g['month1'] : 0;
        $month2 = isset($g['month2']) ? (float)$g['month2'] : 0;
        $month3 = isset($g['month3']) ? (float)$g['month3'] : 0;
        $daily1 = isset($g['daily1']) ? (float)$g['daily1'] : 0;
        $midterm = isset($g['midterm']) ? (float)$g['midterm'] : 0;
        $month4 = isset($g['month4']) ? (float)$g['month4'] : 0;
        $month5 = isset($g['month5']) ? (float)$g['month5'] : 0;
        $month6 = isset($g['month6']) ? (float)$g['month6'] : 0;
        $daily2 = isset($g['daily2']) ? (float)$g['daily2'] : 0;
        $final_result = isset($g['final_result']) ? (float)$g['final_result'] : 0;

        // ✅ الفصل الأول
        if ($daily1 > 0) {
            $semester1 = top3_avg_admin(array($month1, $month2, $month3, $daily1));
        } else {
            $semester1 = round(($month1 + $month2 + $month3) / 3, 2);
        }
        // تقريب الفصل الأول
        $semester1 = round_half_up_int($semester1);

        // ✅ الفصل الثاني
        if ($daily2 > 0) {
            $semester2 = top3_avg_admin(array($month4, $month5, $month6, $daily2));
        } else {
            $semester2 = round(($month4 + $month5 + $month6) / 3, 2);
        }
        // تقريب الفصل الثاني
        $semester2 = round_half_up_int($semester2);

        // ✅ المعدل السنوي (نخليها بديسمل مثل ما كانت)
        $annual_average = round(($semester1 + $semester2 + $midterm) / 3, 2);

        // نبحث عن درجة لهذه المادة لهذا الطالب (نتجاهل teacher_id)
        $check = mysqli_query($conn, "
            SELECT id FROM grades 
            WHERE student_id=$sid 
              AND TRIM(LOWER(REPLACE(subject,'ال',''))) = TRIM(LOWER(REPLACE('$subject','ال','')))
            LIMIT 1
        ");
        if (mysqli_num_rows($check) > 0) {
            $r = mysqli_fetch_assoc($check);
            mysqli_query($conn, "
                UPDATE grades SET 
                    month1=$month1,
                    month2=$month2,
                    month3=$month3,
                    daily1=$daily1,
                    semester1=$semester1,
                    midterm=$midterm,
                    month4=$month4,
                    month5=$month5,
                    month6=$month6,
                    daily2=$daily2,
                    semester2=$semester2,
                    annual_average=$annual_average,
                    final_result=$final_result,
                    saved_at=NOW()
                WHERE id=".$r['id']."
            ");
        } else {
            mysqli_query($conn, "
                INSERT INTO grades (
                    student_id,subject,
                    month1,month2,month3,daily1,semester1,midterm,
                    month4,month5,month6,daily2,semester2,
                    annual_average,final_result,saved_at
                )
                VALUES (
                    $sid,'$subject',
                    $month1,$month2,$month3,$daily1,$semester1,$midterm,
                    $month4,$month5,$month6,$daily2,$semester2,
                    $annual_average,$final_result,NOW()
                )
            ");
        }
    }
    $save_notice = "✅ تم حفظ الدرجات، والآن الصفحة تعرض درجات كل المدرسين لهذه المادة.";
}

/* =========================
   5) جلب المواد للمرحلة (بدون تقسيم مدرس)
   ========================= */
$subjects = [];
if ($stage !== '') {
    $stage_esc = mysqli_real_escape_string($conn, $stage);
    $rs = mysqli_query($conn, "
        SELECT DISTINCT name AS subject
        FROM subjects
        WHERE
            REPLACE(REPLACE(REPLACE(stage,'الأ','ا'),'ال',''), ' ', '') =
            REPLACE(REPLACE(REPLACE('$stage_esc','الأ','ا'),'ال',''), ' ', '')
        ORDER BY name ASC
    ");
    while($r = mysqli_fetch_assoc($rs)) {
        $subjects[] = $r['subject'];
    }
}

/* =========================
   6) جلب الطلاب + دمج درجات كل المدرسين
   ========================= */
$rows = [];
if ($stage !== '' && $subject !== '') {
    $stage_esc   = mysqli_real_escape_string($conn, $stage);
    $subject_esc = mysqli_real_escape_string($conn, $subject);

    // 1) الطلاب
    $srs = mysqli_query($conn, "
        SELECT id,name,class
        FROM students
        WHERE REPLACE(stage,'الأ','ا') LIKE REPLACE('%$stage_esc%','الأ','ا')
        ORDER BY class ASC, name ASC
    ");
    while($s = mysqli_fetch_assoc($srs)) {
        $rows[$s['id']] = [
            'id'            => $s['id'],
            'name'          => $s['name'],
            'class'         => $s['class'],
            'month1'        => '',
            'month2'        => '',
            'month3'        => '',
            'daily1'        => '',
            'semester1'     => '',
            'midterm'       => '',
            'month4'        => '',
            'month5'        => '',
            'month6'        => '',
            'daily2'        => '',
            'semester2'     => '',
            'annual_average'=> '',
            'final_result'  => '',
            'saved_at'      => ''
        ];
    }

    // 2) الدرجات (كل المدرسين لهذه المادة)
    if (!empty($rows)) {
        $ids = implode(',', array_keys($rows));
        $grs = mysqli_query($conn, "
            SELECT g.*
            FROM grades g
            WHERE g.student_id IN ($ids)
              AND TRIM(LOWER(REPLACE(g.subject,'ال',''))) = TRIM(LOWER(REPLACE('$subject_esc','ال','')))
        ");
        while($g = mysqli_fetch_assoc($grs)) {
            $sid = $g['student_id'];
            if (isset($rows[$sid])) {
                $old_time = $rows[$sid]['saved_at'] ? strtotime($rows[$sid]['saved_at']) : 0;
                $new_time = $g['saved_at'] ? strtotime($g['saved_at']) : 0;
                if ($new_time >= $old_time) {
                    foreach ($g as $k=>$v) {
                        if (array_key_exists($k,$rows[$sid])) {
                            $rows[$sid][$k] = $v;
                        }
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>درجات الطلبة — أدمن</title>
<style>
body{font-family:'Cairo',Arial;background:#f6f7fb;margin:0}
.top{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;background:#fff;border-bottom:1px solid #eee}
.container{max-width:1200px;margin:20px auto;padding:0 16px}
.step{background:#fff;border:1px solid #eee;border-radius:16px;box-shadow:0 10px 25px rgba(0,0,0,.05);padding:14px;margin-bottom:16px}
.badge{display:inline-block;background:#f0f4ff;border:1px solid #dbe4ff;padding:6px 10px;border-radius:8px;margin:4px;text-decoration:none;color:#000}
.btn{display:inline-block;background:#2d6cdf;color:#fff;text-decoration:none;padding:8px 12px;border-radius:10px;margin:4px}
.btn.alt{background:#6c757d}
.btn.save{background:#27ae60}
.btn.excel{background:#1c8b2e}
.btn.all{background:#8b5cf6}
table{width:1700px;border-collapse:collapse;background:#fff;border-radius:12px;overflow:hidden}
th,td{border-bottom:1px solid #eee;padding:6px;text-align:center;font-size:13px;white-space:nowrap}
thead th{background:#f9fafe}
.notice{background:#eaf7ee;border:1px solid #c6efd1;color:#2a7d2e;padding:10px;border-radius:10px;margin-bottom:12px}
.small{font-size:12px;color:#777}
input[type="number"]{width:80px;padding:3px;border:1px solid #ccc;border-radius:4px;text-align:center}
.strike-lowest{background:#ffe6f2 !important;color:#c00 !important;text-decoration:line-through;font-weight:bold}
.class-A { background: #e3f2fd !important; color: #0d47a1; }
.class-B { background: #fff3e0 !important; color: #e65100; }
.class-C { background: #e8f5e9 !important; color: #1b5e20; }
.class-D { background: #f3e5f5 !important; color: #4a148c; }
.class-OTHER { background: #eceff1 !important; color: #263238; }
</style>
</head>
<body>
<div class="top">
  <div><strong>درجات الطلبة (عرض/تحرير) — الأدمن</strong></div>
  <div>
    <a class="btn alt" href="admin_dashboard.php">العودة للوحة</a>
    <a class="btn" href="admin_logout.php">خروج</a>
  </div>
</div>

<div class="container">
<a class="btn all" href="?export_all=1">📘 تصدير كل الدرجات</a>
<?php if($stage && $subject): ?>
<a class="btn excel" href="?stage=<?php echo urlencode($stage); ?>&subject=<?php echo urlencode($subject); ?>&export=1">⬇️ تصدير درجات المادة المحددة</a>
<?php endif; ?>

<?php if($save_notice!==""):?>
  <div class="notice"><?php echo esc($save_notice);?></div>
<?php endif;?>

<div class="step">
  <div><strong>المرحلة:</strong></div>
  <?php foreach($stages as $st): ?>
    <a class="badge" href="?stage=<?php echo urlencode($st);?>"><?php echo esc($st);?></a>
  <?php endforeach;?>
  <?php if($stage!==''):?>
    <div class="small">المختار: <strong><?php echo esc($stage);?></strong></div>
  <?php endif;?>
</div>

<?php if($stage!==''):?>
<div class="step">
  <div><strong>المادة:</strong></div>
  <?php if(count($subjects)===0): ?>
    <div class="small">لا توجد مواد.</div>
  <?php else: ?>
    <?php foreach($subjects as $sub): ?>
      <a class="badge" href="?stage=<?php echo urlencode($stage);?>&subject=<?php echo urlencode($sub);?>"><?php echo esc($sub);?></a>
    <?php endforeach;?>
  <?php endif;?>
  <?php if($subject != ''): ?>
    <div class="small" style="margin-top:6px;">
      المختار: <strong><?php echo esc($subject);?></strong>
    </div>
  <?php endif; ?>
</div>
<?php endif;?>

<?php if($stage!=='' && $subject!=='' && count($rows)>0): ?>
<form method="post" class="step">
  <input type="hidden" name="do_save" value="1">
  <input type="hidden" name="stage" value="<?php echo esc($stage);?>">
  <input type="hidden" name="subject" value="<?php echo esc($subject);?>">
  <div class="small" style="margin-bottom:8px;">
    ✅ ملاحظة: يتم شطب أقل درجة في كل فصل (إذا وُجد يومي)، ويتم حساب المعدل السنوي = (ف1 + ف2 + نصف السنة) ÷ 3 تلقائيًا، وتم تقريب ف1 وف2 لأقرب درجة.
  </div>
  <div style="overflow-x:auto;">
  <table>
    <thead>
      <tr>
        <th>اسم الطالب</th><th>الشعبة</th>
        <th>ش1</th><th>ش2</th><th>ش3</th><th>اليومي ف1</th><th>ف1</th>
        <th>نصف السنة</th>
        <th>ش1 (ف2)</th><th>ش2 (ف2)</th><th>ش3 (ف2)</th><th>اليومي ف2</th><th>ف2</th>
        <th>المعدل السنوي</th><th>النتيجة</th><th>📅 تاريخ الحفظ</th>
      </tr>
    </thead>
    <tbody>
    <?php foreach($rows as $sid => $r): ?>
      <?php
        $m1  = (float)$r['month1'];
        $m2  = (float)$r['month2'];
        $m3  = (float)$r['month3'];
        $d1  = (float)$r['daily1'];
        $mid = (float)$r['midterm'];
        $m4  = (float)$r['month4'];
        $m5  = (float)$r['month5'];
        $m6  = (float)$r['month6'];
        $d2  = (float)$r['daily2'];

        // 🔹 فصل أول (حساب + تقريب)
        if ($d1 > 0) {
            $firstVals = array('month1'=>$m1,'month2'=>$m2,'month3'=>$m3,'daily1'=>$d1);
            $min_key1 = null; $min_val1 = null;
            foreach ($firstVals as $k=>$v) {
                if ($min_val1 === null || $v < $min_val1) {
                    $min_val1 = $v;
                    $min_key1 = $k;
                }
            }
            $sem1_display = top3_avg_admin(array($m1,$m2,$m3,$d1));
        } else {
            $min_key1 = null;
            $sem1_display = round(($m1+$m2+$m3)/3,2);
        }
        $sem1_display = round_half_up_int($sem1_display);

        // 🔹 فصل ثاني (حساب + تقريب)
        if ($d2 > 0) {
            $secondVals = array('month4'=>$m4,'month5'=>$m5,'month6'=>$m6,'daily2'=>$d2);
            $min_key2 = null; $min_val2 = null;
            foreach ($secondVals as $k=>$v) {
                if ($min_val2 === null || $v < $min_val2) {
                    $min_val2 = $v;
                    $min_key2 = $k;
                }
            }
            $sem2_display = top3_avg_admin(array($m4,$m5,$m6,$d2));
        } else {
            $min_key2 = null;
            $sem2_display = round(($m4+$m5+$m6)/3,2);
        }
        $sem2_display = round_half_up_int($sem2_display);

        $annual_disp = round(($sem1_display + $sem2_display + $mid)/3, 2);

        // تلوين الشعبة
        $cls = trim($r['class']);
        $cls_up = strtoupper($cls);
        if ($cls_up == 'A' || $cls_up == 'أ' || $cls_up == 'آ') {
            $class_color = 'class-A';
        } elseif ($cls_up == 'B' || $cls_up == 'ب') {
            $class_color = 'class-B';
        } elseif ($cls_up == 'C' || $cls_up == 'ج') {
            $class_color = 'class-C';
        } elseif ($cls_up == 'D' || $cls_up == 'د') {
            $class_color = 'class-D';
        } else {
            $class_color = 'class-OTHER';
        }
      ?>
      <tr>
        <td><?php echo esc($r['name']);?></td>
        <td class="<?php echo $class_color;?>"><?php echo esc($r['class']);?></td>

        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][month1]" value="<?php echo esc(fmt_num($r['month1']));?>" <?php echo ($min_key1=='month1'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][month2]" value="<?php echo esc(fmt_num($r['month2']));?>" <?php echo ($min_key1=='month2'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][month3]" value="<?php echo esc(fmt_num($r['month3']));?>" <?php echo ($min_key1=='month3'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][daily1]" value="<?php echo esc(fmt_num($r['daily1']));?>" <?php echo ($min_key1=='daily1'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" value="<?php echo esc($sem1_display);?>" readonly></td>

        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][midterm]" value="<?php echo esc(fmt_num($r['midterm']));?>"></td>

        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][month4]" value="<?php echo esc(fmt_num($r['month4']));?>" <?php echo ($min_key2=='month4'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][month5]" value="<?php echo esc(fmt_num($r['month5']));?>" <?php echo ($min_key2=='month5'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][month6]" value="<?php echo esc(fmt_num($r['month6']));?>" <?php echo ($min_key2=='month6'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][daily2]" value="<?php echo esc(fmt_num($r['daily2']));?>" <?php echo ($min_key2=='daily2'?'class="strike-lowest"':''); ?>></td>
        <td><input type="number" step="0.01" value="<?php echo esc($sem2_display);?>" readonly></td>

        <td><input type="number" step="0.01" value="<?php echo esc(fmt_num($annual_disp));?>" readonly></td>
        <td><input type="number" step="0.01" name="grades[<?php echo $sid;?>][final_result]" value="<?php echo esc(fmt_num($r['final_result']));?>"></td>
        <td><?php echo $r['saved_at'] ? date("Y-m-d H:i", strtotime($r['saved_at'])) : "-"; ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  </div>
  <button class="btn save" type="submit">💾 حفظ الدرجات</button>
</form>
<?php endif;?>
</div>
</body>
</html>
