<?php 

include('includes/config.php');


?>


<?php
include('includes/user_data.php');

?>


<!doctype html>
<html lang="en">


<!-- Mirrored from codervent.com/rocker/demo/vertical/user-profile.html by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 26 Aug 2022 06:47:36 GMT -->
<head>
	<!-- Required meta tags -->
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!--favicon-->
	<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
	<!--plugins-->
	<link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
	<link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
	<link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
	<!-- loader-->
	<link href="assets/css/pace.min.css" rel="stylesheet" />
	<script src="assets/js/pace.min.js"></script>
	<!-- Bootstrap CSS -->
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/bootstrap-extended.css" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&amp;display=swap" rel="stylesheet">
	<link href="assets/css/app.css" rel="stylesheet">
	<link href="assets/css/icons.css" rel="stylesheet">
	<!-- Theme Style CSS -->
	<link rel="stylesheet" href="assets/css/dark-theme.css" />
	<link rel="stylesheet" href="assets/css/semi-dark.css" />
	<link rel="stylesheet" href="assets/css/header-colors.css" />
  <title>End of Term Report Entry</title>
  <style>
    :root{--bg:#f8fafc;--card:#fff;--muted:#6b7280;--accent:#2563eb}
    body{font-family:Inter,system-ui,Segoe UI,Roboto,Arial;background:var(--bg);margin:0;padding:20px}
    .container{max-width:1150px;margin:0 auto}
    .card{background:var(--card);border-radius:12px;padding:18px;box-shadow:0 6px 18px rgba(15,23,42,0.06)}
    .btn{display:inline-block;padding:10px 14px;border-radius:8px;border:0;cursor:pointer}
    .btn-accent{background:var(--accent);color:#fff}
    .btn-ghost{background:transparent;border:1px solid #e6e9ef;color:#111}
    input[type="number"]{width:100%}
    table{width:100%;border-collapse:collapse}
    th,td{padding:8px;border-bottom:1px solid #eef2f7;text-align:left;font-size:14px}
    .small{font-size:13px;color:var(--muted)}
    .flex{display:flex;gap:12px;align-items:center}
    .select, .input, textarea{padding:8px;border-radius:8px;border:1px solid #e6e9ef}
    .badge{padding:4px 8px;border-radius:999px;background:#eef2f7;color:#0f172a;font-size:12px}
    .muted{color:var(--muted)}
    @media (max-width:900px){
      .flex{flex-direction:column;align-items:stretch}
      th,td{font-size:13px}
    }
  </style>
  <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
	<!--wrapper-->
	<div class="wrapper">
		<!--sidebar wrapper -->
		<?php include 'includes/side.php'; ?>
		<!--end sidebar wrapper -->
		<!--start header -->
		<?php include 'includes/head.php'; ?>
		<!--end header -->
		<!--start page wrapper -->
		<div class="page-wrapper">
			<div class="page-content">
				<!--breadcrumb-->
				<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
					<div class="breadcrumb-title pe-3"></div>
					<div class="ps-3">
						<nav aria-label="breadcrumb">
							<ol class="breadcrumb mb-0 p-0">
								<li class="breadcrumb-item"><a href="javascript:;"><i class="bx bx-home-alt"></i></a>
								</li>
								<li class="breadcrumb-item active" aria-current="page"></li>
							</ol>
						</nav>
					</div>
					
				</div>
				<!--end breadcrumb-->
				<div class="container">
					<div class="main-body">
						<div class="row">
						
							<div class="col-lg-12">
								<div class="card">
									<div class="card-body">
									    
									    
									    
									    
									    
									    <!--display result-->
									  
									  <?php
//require_once 'config.php';

// Initialize variables
$students = [];
$selected_session = $_GET['session_id'] ?? '';
$selected_term = $_GET['term_id'] ?? '';
$selected_class = $_GET['class_id'] ?? '';
$selected_exam = $_GET['exam_id'] ?? '';

// Fetch filter options
$sessions = $dbh->query("SELECT id, session_year FROM sessions ORDER BY session_year DESC")->fetchAll();
$terms = $dbh->query("SELECT id, term_name FROM terms ORDER BY id")->fetchAll();
$classes = $dbh->query("SELECT id, name FROM classes ORDER BY name")->fetchAll();

// Fetch exams based on filters
if ($selected_session && $selected_term && $selected_class) {
    $examStmt = $dbh->prepare("
        SELECT id, title 
        FROM exams 
        WHERE session_id = ? AND term_id = ? AND class_id = ? AND status != 'draft'
        ORDER BY title
    ");
    $examStmt->execute([$selected_session, $selected_term, $selected_class]);
    $exams = $examStmt->fetchAll();
} else {
    $exams = [];
}

// Fetch student results when all filters are selected
if ($selected_session && $selected_term && $selected_class && $selected_exam) {
    $stmt = $dbh->prepare("
        SELECT 
            s.Admission_num,
            s.name AS student_name,
            e.title AS exam_title,
            c.name AS class_name,
            sess.session_year,
            t.term_name,
            ea.score,
            ea.status,
            ea.submitted_at
        FROM students s
        JOIN classes c ON s.class_id = c.id
        LEFT JOIN exam_attempts ea ON s.id = ea.student_id AND ea.exam_id = ?
        LEFT JOIN exams e ON ea.exam_id = e.id
        LEFT JOIN sessions sess ON e.session_id = sess.id
        LEFT JOIN terms t ON e.term_id = t.id
        WHERE s.class_id = ? 
        AND s.status = 'active'
        AND e.session_id = ? 
        AND e.term_id = ?
        ORDER BY s.Admission_num
    ");
    
    $stmt->execute([$selected_exam, $selected_class, $selected_session, $selected_term]);
    $students = $stmt->fetchAll();
}
?>


    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800">Student Exam Results</h1>
                    <p class="text-gray-600 mt-2">View and analyze student performance</p>
                </div>
                <div class="bg-blue-100 p-3 rounded-lg">
                    <i class="fas fa-chart-bar text-blue-600 text-2xl"></i>
                </div>
            </div>
        </div>

        <!-- Filters Section -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 class="text-xl font-semibold text-gray-700 mb-4">Filter Results</h2>
            <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Session Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Academic Session</label>
                    <select name="session_id" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" onchange="this.form.submit()">
                        <option value="">Select Session</option>
                        <?php foreach ($sessions as $session): ?>
                            <option value="<?= $session['id'] ?>" <?= $selected_session == $session['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($session['session_year']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Term Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Term</label>
                    <select name="term_id" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" onchange="this.form.submit()">
                        <option value="">Select Term</option>
                        <?php foreach ($terms as $term): ?>
                            <option value="<?= $term['id'] ?>" <?= $selected_term == $term['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($term['term_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Class Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Class</label>
                    <select name="class_id" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" onchange="this.form.submit()">
                        <option value="">Select Class</option>
                        <?php foreach ($classes as $class): ?>
                            <option value="<?= $class['id'] ?>" <?= $selected_class == $class['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($class['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Exam Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Exam</label>
                    <select name="exam_id" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" onchange="this.form.submit()">
                        <option value="">Select Exam</option>
                        <?php foreach ($exams as $exam): ?>
                            <option value="<?= $exam['id'] ?>" <?= $selected_exam == $exam['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($exam['title']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>

        <!-- Results Section -->
        <?php if (!empty($students)): ?>
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <!-- Results Header -->
                <div class="bg-gradient-to-r from-blue-600 to-blue-800 px-6 py-4">
                    <div class="flex justify-between items-center">
                        <h2 class="text-xl font-bold text-white">Exam Results</h2>
                        <div class="text-white">
                            <span class="bg-blue-500 px-3 py-1 rounded-full text-sm">
                                <?= count($students) ?> Students
                            </span>
                        </div>
                    </div>
                    <?php if (!empty($students[0]['exam_title'])): ?>
                        <p class="text-blue-100 mt-1">
                            <?= htmlspecialchars($students[0]['exam_title']) ?> - 
                            <?= htmlspecialchars($students[0]['class_name']) ?> |
                            <?= htmlspecialchars($students[0]['session_year']) ?> |
                            <?= htmlspecialchars($students[0]['term_name']) ?>
                        </p>
                    <?php endif; ?>
                </div>

                <!-- Results Table -->
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Admission No.</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student Name</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Exam Title</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Score</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Submitted At</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($students as $student): ?>
                                <tr class="hover:bg-gray-50 transition-colors duration-150">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="bg-blue-100 p-2 rounded-lg">
                                                <i class="fas fa-id-card text-blue-600"></i>
                                            </div>
                                            <span class="ml-3 font-medium text-gray-900">
                                                <?= htmlspecialchars($student['Admission_num']) ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-gray-900">
                                        <?= htmlspecialchars($student['student_name']) ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-gray-900">
                                        <?= htmlspecialchars($student['exam_title'] ?? 'Not Attempted') ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($student['score'] !== null): ?>
                                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                                                <i class="fas fa-star mr-1"></i>
                                                <?= htmlspecialchars($student['score']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800">
                                                <i class="fas fa-minus mr-1"></i>
                                                N/A
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php
                                        $status = $student['status'] ?? 'not_attempted';
                                        $statusConfig = [
                                            'graded' => ['color' => 'green', 'icon' => 'check-circle', 'text' => 'Graded'],
                                            'submitted' => ['color' => 'blue', 'icon' => 'paper-plane', 'text' => 'Submitted'],
                                            'in_progress' => ['color' => 'yellow', 'icon' => 'clock', 'text' => 'In Progress'],
                                            'not_attempted' => ['color' => 'gray', 'icon' => 'times-circle', 'text' => 'Not Attempted']
                                        ];
                                        $config = $statusConfig[$status] ?? $statusConfig['not_attempted'];
                                        ?>
                                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-<?= $config['color'] ?>-100 text-<?= $config['color'] ?>-800">
                                            <i class="fas fa-<?= $config['icon'] ?> mr-1"></i>
                                            <?= $config['text'] ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        <?= $student['submitted_at'] ? date('M j, Y g:i A', strtotime($student['submitted_at'])) : 'N/A' ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Summary -->
                <div class="bg-gray-50 px-6 py-4 border-t border-gray-200">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                        <?php
                        $attempted = array_filter($students, fn($s) => $s['status'] !== null);
                        $graded = array_filter($students, fn($s) => $s['status'] === 'graded');
                        $averageScore = $graded ? array_sum(array_column($graded, 'score')) / count($graded) : 0;
                        ?>
                        <div class="text-center">
                            <span class="font-semibold text-gray-700">Total Students: </span>
                            <span class="text-blue-600"><?= count($students) ?></span>
                        </div>
                        <div class="text-center">
                            <span class="font-semibold text-gray-700">Attempted: </span>
                            <span class="text-green-600"><?= count($attempted) ?></span>
                        </div>
                        <div class="text-center">
                            <span class="font-semibold text-gray-700">Average Score: </span>
                            <span class="text-purple-600"><?= number_format($averageScore, 2) ?></span>
                        </div>
                    </div>
                </div>
            </div>

        <?php elseif ($selected_session && $selected_term && $selected_class && $selected_exam): ?>
            <!-- No Results Message -->
            <div class="bg-white rounded-lg shadow-md p-8 text-center">
                <div class="max-w-md mx-auto">
                    <div class="bg-yellow-100 p-4 rounded-full w-16 h-16 mx-auto mb-4 flex items-center justify-center">
                        <i class="fas fa-exclamation-triangle text-yellow-600 text-2xl"></i>
                    </div>
                    <h3 class="text-xl font-semibold text-gray-700 mb-2">No Results Found</h3>
                    <p class="text-gray-500">No students have attempted this exam yet or no matching records found.</p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // Auto-submit form when filters change
        document.querySelectorAll('select').forEach(select => {
            select.addEventListener('change', function() {
                if(this.name !== 'exam_id') {
                    // Reset exam selection when other filters change
                    document.querySelector('select[name="exam_id"]').value = '';
                }
                this.form.submit();
            });
        });
    </script>

									  
									    
									    <!--end of display-->
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
									    
<?php
// end_term_report.php
session_start();
require_once 'config.php';

// teacher id must be available in scope (e.g. from session)
if (!isset($teacher_id)) {
    $teacher_id = $_SESSION['teacher_id'] ?? null;
}
if (!$teacher_id) {
    http_response_code(403);
    echo "Teacher not identified. Ensure \$teacher_id is set.";
    exit;
}

// fetch teacher name
$stmt = $dbh->prepare("SELECT name FROM teachers WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $teacher_id]);
$teacher_name = $stmt->fetchColumn() ?: 'Teacher';

$sessions = $dbh->query("SELECT id, session_year FROM sessions ORDER BY session_year DESC")->fetchAll(PDO::FETCH_ASSOC);
$terms    = $dbh->query("SELECT id, term_name FROM terms ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
$classes  = $dbh->query("SELECT id, name FROM classes ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$subjects = $dbh->query("SELECT id, name FROM Subjects ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
?>



<div class="container">
  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
      <div>
        <h2 style="margin:0">End-Term Report Entry</h2>
        <p class="small muted" style="margin:6px 0 0">Enter CA and Exam scores for students. Totals are auto-calculated.</p>
      </div>
      <div style="text-align:right">
        <div class="small muted">Teacher</div>
        <div style="font-weight:600"><?= htmlspecialchars($teacher_name) ?> <span class="badge">ID: <?= htmlspecialchars($teacher_id) ?></span></div>
      </div>
    </div>

    <form id="filterForm" onsubmit="return false;">
      <div class="flex" style="margin-bottom:12px">
        <div style="flex:1">
          <label class="small">Session</label><br>
          <select id="sessionSelect" class="select" required>
            <option value="">-- select session --</option>
            <?php foreach($sessions as $s): ?>
              <option value="<?=htmlspecialchars($s['id'])?>"><?=htmlspecialchars($s['session_year'])?></option>
            <?php endforeach;?>
          </select>
        </div>

        <div style="flex:1">
          <label class="small">Term</label><br>
          <select id="termSelect" class="select" required>
            <option value="">-- select term --</option>
            <?php foreach($terms as $t): ?>
              <option value="<?=htmlspecialchars($t['id'])?>"><?=htmlspecialchars($t['term_name'])?></option>
            <?php endforeach;?>
          </select>
        </div>

        <div style="flex:1">
          <label class="small">Class</label><br>
          <select id="classSelect" class="select" required>
            <option value="">-- select class --</option>
            <?php foreach($classes as $c): ?>
              <option value="<?=htmlspecialchars($c['id'])?>"><?=htmlspecialchars($c['name'])?></option>
            <?php endforeach;?>
          </select>
        </div>

        <div style="flex:1">
          <label class="small">Subject</label><br>
          <select id="subjectSelect" class="select" required>
            <option value="">-- select subject --</option>
            <?php foreach($subjects as $su): ?>
              <option value="<?=htmlspecialchars($su['id'])?>"><?=htmlspecialchars($su['name'])?></option>
            <?php endforeach;?>
          </select>
        </div>

        <div style="display:flex;align-items:end;">
          <button id="loadBtn" class="btn btn-accent" style="margin-left:6px">Load Students</button>
        </div>
      </div>
    </form>

    <div id="message" class="small muted" style="min-height:18px"></div>

    <div id="studentsArea" style="margin-top:12px;display:none">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
        <div><strong>Students</strong> <span id="selectionInfo" class="small muted"></span></div>
        <div>
          <button id="saveBtn" class="btn btn-accent">Save All</button>
          <button id="clearBtn" class="btn btn-ghost" style="margin-left:8px">Clear Inputs</button>
        </div>
      </div>

      <div style="overflow:auto">
        <table id="studentsTable" class="table-auto">
          <thead>
            <tr>
              <th style="width:36px">#</th>
              <th>Admission No</th>
              <th>Student Name</th>
              <th style="width:110px">CA Score</th>
              <th style="width:110px">Exam Score</th>
              <th style="width:90px">Total</th>
              <th style="width:200px">Comment</th>
              <th style="width:120px">Last Updated</th>
            </tr>
          </thead>
          <tbody id="studentsTbody">
            <!-- JS inserts rows -->
          </tbody>
        </table>
      </div>
    </div>

  </div>
</div>

<script>
const teacherId = <?= json_encode($teacher_id) ?>;

function showMessage(txt, isError=false) {
  const m = document.getElementById('message');
  m.textContent = txt;
  m.style.color = isError ? '#dc2626' : '';
}

async function loadStudents() {
  showMessage('');
  const session = document.getElementById('sessionSelect').value;
  const term = document.getElementById('termSelect').value;
  const cls = document.getElementById('classSelect').value;
  const subject = document.getElementById('subjectSelect').value;

  if (!session || !term || !cls || !subject) {
    showMessage('Please select session, term, class and subject.', true);
    return;
  }

  document.getElementById('loadBtn').disabled = true;
  document.getElementById('loadBtn').textContent = 'Loading...';

  try {
    const res = await fetch('ajax/load_students_endterm.php', {
      method:'POST',
      headers:{ 'Content-Type':'application/json' },
      body: JSON.stringify({ session, term, class_id: cls, subject, teacher_id: teacherId })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || 'Failed to load');

    populateTable(data.students, data.existing || {});
    document.getElementById('studentsArea').style.display = '';
    const info = `Session: ${data.session_year || ''} • Term: ${data.term_name || ''} • Class: ${data.class_name || ''} • Subject: ${data.subject_name || ''}`;
    document.getElementById('selectionInfo').textContent = info;

  } catch (err) {
    console.error(err);
    showMessage('Error loading students: ' + err.message, true);
  } finally {
    document.getElementById('loadBtn').disabled = false;
    document.getElementById('loadBtn').textContent = 'Load Students';
  }
}

function populateTable(students, existingMap) {
  const tbody = document.getElementById('studentsTbody');
  tbody.innerHTML = '';
  students.forEach((s, idx) => {
    const ex = existingMap[s.Admission_num] || null;
    const ca = ex ? (ex.ca_test ?? '') : '';
    const exam = ex ? (ex.exam_score ?? '') : '';
    const total = (ca !== '' || exam !== '') ? (Number(ca || 0) + Number(exam || 0)) : '';
    const comment = ex ? (ex.comment ?? '') : '';
    const updated = ex ? (ex.date ?? '') : '';

    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${idx+1}</td>
      <td><input type="hidden" class="admission_no" value="${escapeHtml(s.Admission_num)}">${escapeHtml(s.Admission_num)}</td>
      <td>${escapeHtml(s.name)}</td>
      <td><input min="0" max="100" type="number" class="input ca_test" value="${ca}"></td>
      <td><input min="0" max="100" type="number" class="input exam_score" value="${exam}"></td>
      <td><input type="number" readonly class="input total" value="${total}"></td>
      <td><input type="text" class="input comment" value="${escapeHtml(comment)}"></td>
      <td class="small muted last_updated">${escapeHtml(updated)}</td>
    `;
    tbody.appendChild(row);

    const caInput = row.querySelector('.ca_test');
    const examInput = row.querySelector('.exam_score');
    caInput.addEventListener('input', () => recalcRow(row));
    examInput.addEventListener('input', () => recalcRow(row));
  });
}

function recalcRow(row) {
  const ca = Number(row.querySelector('.ca_test').value || 0);
  const exam = Number(row.querySelector('.exam_score').value || 0);
  row.querySelector('.total').value = ca + exam;
}

function escapeHtml(unsafe){
  if (unsafe === null || unsafe === undefined) return '';
  return String(unsafe)
      .replaceAll('&','&amp;')
      .replaceAll('<','&lt;')
      .replaceAll('>','&gt;')
      .replaceAll('"','&quot;')
      .replaceAll("'","&#039;");
}

async function saveAll() {
  showMessage('');
  const session = document.getElementById('sessionSelect').value;
  const term = document.getElementById('termSelect').value;
  const cls = document.getElementById('classSelect').value;
  const subject = document.getElementById('subjectSelect').value;

  if (!session || !term || !cls || !subject) {
    showMessage('Please select session, term, class and subject before saving.', true);
    return;
  }

  const rows = Array.from(document.querySelectorAll('#studentsTbody tr'));
  const payload = {
    teacher_id: teacherId,
    session, term, class_id: cls, subject,
    records: []
  };

  for (const r of rows) {
    const admission = r.querySelector('.admission_no').value;
    const ca = r.querySelector('.ca_test').value;
    const exam = r.querySelector('.exam_score').value;
    const total = r.querySelector('.total').value;
    const comment = r.querySelector('.comment').value;

    payload.records.push({
      admission_no: admission,
      ca_test: ca === '' ? null : Number(ca),
      exam_score: exam === '' ? null : Number(exam),
      total: total === '' ? null : Number(total),
      comment: comment
    });
  }

  document.getElementById('saveBtn').disabled = true;
  document.getElementById('saveBtn').textContent = 'Saving...';

  try {
    const res = await fetch('ajax/save_endterm.php', {
      method:'POST',
      headers:{ 'Content-Type':'application/json' },
      body: JSON.stringify(payload)
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || 'Save failed');

    showMessage(data.message || 'Saved successfully');
    if (data.updated_map) {
      for (const [adm, ts] of Object.entries(data.updated_map)) {
        const tr = Array.from(document.querySelectorAll('#studentsTbody tr')).find(r => r.querySelector('.admission_no').value === adm);
        if (tr) tr.querySelector('.last_updated').textContent = ts;
      }
    }
  } catch (err) {
    console.error(err);
    showMessage('Save failed: ' + err.message, true);
  } finally {
    document.getElementById('saveBtn').disabled = false;
    document.getElementById('saveBtn').textContent = 'Save All';
  }
}

document.getElementById('loadBtn').addEventListener('click', loadStudents);
document.getElementById('saveBtn').addEventListener('click', saveAll);
document.getElementById('clearBtn').addEventListener('click', () => {
  document.querySelectorAll('#studentsTbody .ca_test, #studentsTbody .exam_score, #studentsTbody .comment').forEach(i => i.value = '');
  document.querySelectorAll('#studentsTbody .total').forEach(i => i.value = '');
});
</script>








								</div>
								
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!--end page wrapper -->
		<!--start overlay-->
		<div class="overlay toggle-icon"></div>
		<!--end overlay-->
		<!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
		<!--End Back To Top Button-->
		<footer class="page-footer">
			<p class="mb-0">Copyright © 2024. All right reserved.</p>
		</footer>
	</div>
	<!--end wrapper-->
	<!--start switcher-->
	<?php include 'includes/customiser.php'; ?>

	<!--end switcher-->
	<!-- Bootstrap JS -->
	<script src="assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<script src="assets/js/jquery.min.js"></script>
	<script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
	<script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
	<script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
	<!--app JS-->
	<script src="assets/js/app.js"></script>
</body>


</html>

