<?php
header("Content-Type: text/html; charset=UTF-8");
session_start();
if (!isset($_SESSION['evaluator_name'])) {
    header("Location: register.php");
    exit();
}
$evaluatorName = $_SESSION['evaluator_name'];
include('last_db_config.php');
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>تقييم الطلاب</title>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="unified-style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
</head>
<body>
  <header class="program-header">
    <div class="header-content">
      <img src="wezara.png" alt="شعار الوزارة" class="logo-right">
      <div class="title-container">
        <h1 class="program-title">البرنامج القومي لتنمية مهارات اللغة العربية بالمرحلة الابتدائية</h1>
      </div>
      <img src="week.png" alt="شعار البرنامج" class="logo-left">
    </div>
  </header>

  <div class="topbar">
    <div class="welcome">مرحبًا د. <?= htmlspecialchars($evaluatorName) ?> 👋</div>
    <div class="topbar-links">
      <a href="#" onclick="location.reload()">🔄 تسجيل مدرسة جديدة</a>
      <a href="index.php">🚪 تسجيل خروج</a>
    </div>
  </div>

  <div class="form-row1">
    <div class="form-group1">
      <label for="GovID">المحافظة</label>
      <select id="GovID" class="form-control" required>
        <option disabled selected value="">اختر المحافظة</option>
        <?php
          $rs = mysqli_query($conn, "SELECT GovID, GovName FROM government ORDER BY GovName");
          while ($r = mysqli_fetch_assoc($rs)) echo "<option value='{$r['GovID']}'>{$r['GovName']}</option>";
        ?>
      </select>
    </div>
    <div class="form-group1">
      <label for="EdaraID">الإدارة التعليمية</label>
      <select id="EdaraID" class="form-control" required><option disabled selected>اختر الإدارة</option></select>
    </div>
    <div class="form-group1">
      <label for="schoolID">المدرسة</label>
      <select id="schoolID" class="form-control" required><option disabled selected>اختر المدرسة</option></select>
    </div>
    <div class="form-group1">
      <label for="classID">الصف</label>
      <select id="classID" class="form-control" required>
        <option disabled selected>اختر الصف</option>
        <option value="3">الثالث</option><option value="4">الرابع</option>
        <option value="5">الخامس</option><option value="6">السادس</option>
      </select>
    </div>
  </div>

  <div class="counters">
    <span id="countEvaluated">✅ تم تقييم: 0</span>
    <span id="countNotEvaluated">🕒 لم يُقيم: 0</span>
    <span id="countAbsent">🚫 الغياب : 0</span>
  </div>

  <div id="studentsTableContainer"></div>
  <div id="saveMessage" style="text-align:center; margin:10px;"></div>

<script>
$(function(){
  $('#GovID').change(function(){
    $.post('action copy.php',{GovID:$(this).val()}, data => {
      $('#EdaraID').html(data);
      $('#schoolID').html('<option disabled selected>اختر المدرسة</option>');
    });
  });
  $('#EdaraID').change(function(){
    $.post('action copy.php',{EdaraID:$(this).val()}, data => $('#schoolID').html(data));
  });
  $('#schoolID, #classID').change(buildTable);

  function buildTable(){
    const school = $('#schoolID').val(), cls = $('#classID').val();
    if(!school || !cls) { $('#studentsTableContainer').html('<p style="color:red">يرجى اختيار المدرسة والصف</p>'); return; }
    $('#studentsTableContainer').html('<p>جاري التحميل...</p>');
    $.post('fail_students_retrieve.php', { SchoolID: school, Class: cls }, res => {
      $('#countEvaluated').text('✅ تم تقييم: ' + res.evaluated);
      $('#countNotEvaluated').text('🕒 لم يُقيم: ' + res.notEvaluated);
      $('#countAbsent').text('🚫 الغياب : ' + (res.absentCount || 0));
      if(res.options.length === 0){ $('#studentsTableContainer').html('<p>لا يوجد طلاب بحاجة للتقييم</p>'); return; }
      let html = '<div class="table-responsive"> <table> <thead><tr><th>اسم الطالب</th>';
      for(let i=1;i<=13;i++) html += `<th>السؤال${i}</th>`;
      html += '<th>إجراء</th> </thead><tbody>';
      res.options.forEach(stu => {
        html += `<tr data-id="${stu.StudentID}">`;
        // Student info cell: name (line1), حاضر/غائب and nationality (line2), دمج + disability (line3)
        html += `<td style="min-width: 200px;">
          <div><strong>${stu.Name}</strong></div>
          <div style="margin-top: 6px;">
            <label style="margin-left: 12px;"><input type="radio" name="status_${stu.StudentID}" value="present" checked> حاضر</label>
            <label><input type="radio" name="status_${stu.StudentID}" value="absent"> غائب</label>
            <label style="margin-left: 12px; margin-right: 12px;">|</label>
            <label style="margin-left: 12px;"><input type="radio" name="nationality_${stu.StudentID}" value="egyptian" checked> مصرى</label>
            <label><input type="radio" name="nationality_${stu.StudentID}" value="non_egyptian"> غير مصرى</label>
          </div>
          <div style="margin-top: 6px; display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
            <label><input type="checkbox" class="merge-checkbox"> دمج</label>
            <select class="disability-type" disabled style="padding: 4px 8px;">
              <option value="">اختر نوع الإعاقة</option>
              <option value="سمعية">سمعية</option>
              <option value="بصرية">بصرية</option>
              <option value="ذهنية">ذهنية</option>
              <option value="حركية">حركية</option>
            </select>
          </div>
        </td>`;
        // 13 question grade inputs
        for(let i=1;i<=13;i++){
          let max = i===7?3: i===8||i===10?2: i===11?3: i===13?10:5;
          html += `<td><input type="number" name="grade${i}[]" min="0" max="${max}" class="grade-input" style="width:55px;"></td>`;
        }
        html += `<td><button class="save-btn">حفظ</button></td>`;
        html += `<\/tr>`;
      });
      html += '</tbody></table></div>';
      $('#studentsTableContainer').html(html);
    },'json');
  }

  // Hide grade inputs when "غائب" is selected
  $(document).on('change', 'input[type=radio]', function(){
    let $row = $(this).closest('tr');
    if($(this).val() === 'absent') $row.find('.grade-input').closest('td').hide();
    else $row.find('.grade-input').closest('td').show();
  });

  // Enable/disable disability dropdown based on "دمج" checkbox
  $(document).on('change', '.merge-checkbox', function(){
    let $dis = $(this).closest('tr').find('.disability-type');
    $(this).is(':checked') ? $dis.prop('disabled', false) : $dis.prop('disabled', true).val('');
  });

  // Save student data
  $(document).on('click','.save-btn', function(){
    let $row = $(this).closest('tr'), id = $row.data('id');
    let data = { 
      student_id: id, 
      name: <?= json_encode($evaluatorName) ?>, 
      merge: $row.find('.merge-checkbox').is(':checked') ? 1 : 0, 
      disability: $row.find('.disability-type').val() || '',
      nationality: $row.find('input[name="nationality_'+id+'"]:checked').val() || 'egyptian'
    };
    if($row.find('input[type=radio]:checked').val() === 'absent') {
      data.absent = true;
    } else {
      let allFilled = true;
      $row.find('input[type=number]').each(function(i){ 
        let v = $(this).val(); 
        if(v === '' || isNaN(v)) allFilled = false; 
        data['q'+(i+1)] = v || 0; 
      });
      if(!allFilled){ alert('يرجى إدخال جميع الدرجات قبل الحفظ.'); return; }
    }
    let $btn = $(this).prop('disabled', true);
    $.post('insert_fail_student.php', data, response => {
      if(response.includes('success')){ 
        $row.remove(); 
        $('#saveMessage').css('color','green').text('✅ تم حفظ بيانات الطالب'); 
        buildTable();  // Refresh table to update counters
      } else { 
        $('#saveMessage').css('color','red').text('❌ خطأ: '+response); 
        $btn.prop('disabled', false); 
      }
    });
  });

  // Limit number inputs to max value
  $(document).on('input','#studentsTableContainer input[type="number"]', function(){
    let max = parseInt($(this).attr('max')), val = parseInt($(this).val());
    if(val > max) $(this).val(max); 
    else if(val < 0 || isNaN(val)) $(this).val('');
  });
});
</script>
</body>
</html>