<?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>Mid Term Test Entry</title>
  <!-- Use Tailwind-like utility classes (assumes your project has equivalent CSS) -->
  <style>
    /* Minimal fallback styling if Tailwind not available */
    :root{--bg:#f8fafc;--card:#fff;--muted:#6b7280;--accent:#0ea5a4}
    body{font-family:Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,"Helvetica Neue",Arial;background:var(--bg);margin:0;padding:20px}
    .container{max-width:1100px;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>
</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">
						
							
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//echo $teacher_id;
// mid_term_test.php
// Assumptions:
// - config.php sets up $dbh (PDO)
// - $teacher_id is already available and authenticated (from session or include)

// Example: teacher id available
// $teacher_id = $_SESSION['teacher_id'];
// But the user said teacher is identified as $teacher_id; ensure that variable is in scope.
if (!isset($teacher_id)) {
    // attempt to get from session as fallback
    $teacher_id = $_SESSION['teacher_id'] ?? null;
}
if (!$teacher_id) {
    http_response_code(403);
    echo "Teacher not identified. Ensure \$teacher_id is set.";
    exit;
}

// Load dropdown options
$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=""style="margin:0px;width:100%;padding:0px;">
  <div class="card" style="margin:0px;width:100%;">
    <div style="justify-content:space-between;align-items:center;margin-bottom:12px">
      <div>
        <h2 style="margin:0">Mid-Term / Weekly Test Entry</h2>
        <p class="small muted" style="margin:6px 0 0">Select session, term, class and subject to load students. Add scores and save.</p>
      </div>
      <div class="small muted">Teacher ID: <span class="badge"><?=htmlspecialchars($teacher_id)?></span></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:90px">WK Test</th>
              <th style="width:90px">Mid Test</th>
              <th style="width:90px">Total</th>
              <th style="width:200px">Comment</th>
              <th style="width:110px">Last Updated</th>
            </tr>
          </thead>
          <tbody id="studentsTbody">
            <!-- rows inserted by JS -->
          </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;
  }

  const payload = { session, term, class_id: cls, subject, teacher_id: teacherId };

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

  try {
    const res = await fetch('ajax/load_students.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 || '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 row = document.createElement('tr');

    const ex = existingMap[s.Admission_num] || null;
    const wk = ex ? (ex.wk_test ?? '') : '';
    const mid = ex ? (ex.mid_test ?? '') : '';
    const total = (wk !== '' || mid !== '') ? (Number(wk || 0) + Number(mid || 0)) : '';
    const comment = ex ? (ex.comment ?? '') : '';
    const updated = ex ? (ex.date ?? '') : '';

    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 wk_test" value="${wk}"></td>
      <td><input min="0" max="100" type="number" class="input mid_test" value="${mid}"></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);

    // attach events to recalc
    const wkInput = row.querySelector('.wk_test');
    const midInput = row.querySelector('.mid_test');
    wkInput.addEventListener('input', () => recalcRow(row));
    midInput.addEventListener('input', () => recalcRow(row));
  });
}

function recalcRow(row) {
  const wk = Number(row.querySelector('.wk_test').value || 0);
  const mid = Number(row.querySelector('.mid_test').value || 0);
  row.querySelector('.total').value = wk + mid;
}

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 wk = r.querySelector('.wk_test').value;
    const mid = r.querySelector('.mid_test').value;
    const total = r.querySelector('.total').value;
    const comment = r.querySelector('.comment').value;

    // optionally skip all-empty rows (no scores and no comment)
    if (wk === '' && mid === '' && comment.trim() === '') {
      // but we might want to still delete existing entries if they previously existed - that behaviour is not automatic here.
      payload.records.push({
        admission_no: admission,
        wk_test: wk === '' ? null : Number(wk),
        mid_test: mid === '' ? null : Number(mid),
        total: total === '' ? null : Number(total),
        comment: comment
      });
    } else {
      payload.records.push({
        admission_no: admission,
        wk_test: wk === '' ? null : Number(wk),
        mid_test: mid === '' ? null : Number(mid),
        total: total === '' ? null : Number(total),
        comment: comment
      });
    }
  }

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

  try {
    const res = await fetch('ajax/save_midterm.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');
    // update last-updated column with returned timestamps if provided
    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 .wk_test, #studentsTbody .mid_test, #studentsTbody .comment').forEach(i => i.value = '');
  document.querySelectorAll('#studentsTbody .total').forEach(i => i.value = '');
});

</script>





						
					</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>
