<?php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

if (!function_exists('h')) {
  function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
}

$today = date('Y-m-d');

/* -----------------------------------------------------------------
   AJAX API
------------------------------------------------------------------ */
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
  header('Content-Type: application/json; charset=utf-8');
  $act = $_POST['action'] ?? $_GET['action'] ?? '';

  // 1) Load students of batch
  if ($act === 'list_students') {
    $bid = (int)($_GET['batch_id'] ?? 0);
    $rows = mysqli_query($conn, "
      SELECT s.id, s.full_name
      FROM students s
      JOIN registrations r ON r.student_id = s.id
      WHERE r.batch_id = $bid
      ORDER BY s.full_name
    ");
    $out = [];
    while ($r = mysqli_fetch_assoc($rows)) $out[] = $r;
    echo json_encode(['ok'=>true,'items'=>$out]);
    exit;
  }

  // 2) Mark attendance (and auto summary update)
  if ($act === 'mark') {
    $sid = (int)$_POST['student_id'];
    $bid = (int)$_POST['batch_id'];
    $date = $_POST['class_date'] ?? date('Y-m-d');
    $status = $_POST['status'] ?? 'PRESENT';
    $aid = (int)($_SESSION['admin_id'] ?? 0);

    mysqli_query($conn, "
      INSERT INTO attendance (student_id,batch_id,class_date,status,marked_by)
      VALUES ($sid,$bid,'$date','$status',$aid)
      ON DUPLICATE KEY UPDATE status=VALUES(status), marked_at=NOW()
    ");

    // --- Auto update monthly summary (safe fallback if triggers missing)
    mysqli_query($conn, "
      REPLACE INTO attendance_summary (student_id,month_year,presents,absents,leaves,total_days)
      SELECT student_id, DATE_FORMAT(class_date,'%Y-%m'),
             SUM(status='PRESENT'), SUM(status='ABSENT'),
             SUM(status='LEAVE'), COUNT(*)
      FROM attendance
      WHERE student_id=$sid
      GROUP BY DATE_FORMAT(class_date,'%Y-%m')
    ");

    echo json_encode(['ok'=>true]);
    exit;
  }

  // 3) Monthly summary for one student
  if ($act === 'monthly') {
    $sid = (int)$_GET['student_id'];
    $month = $_GET['month'] ?? date('Y-m');
    $res = mysqli_fetch_assoc(mysqli_query($conn, "
      SELECT SUM(status='PRESENT') AS presents,
             SUM(status='ABSENT')  AS absents,
             SUM(status='LEAVE')   AS leaves,
             COUNT(*) AS total
      FROM attendance
      WHERE student_id=$sid AND DATE_FORMAT(class_date,'%Y-%m')='$month'
    "));
    echo json_encode(['ok'=>true,'data'=>$res]);
    exit;
  }

  echo json_encode(['ok'=>false,'error'=>'Unknown action']);
  exit;
}

/* -----------------------------------------------------------------
   UI
------------------------------------------------------------------ */
$batches = mysqli_query($conn, "SELECT id,name FROM batches WHERE status IN('Scheduled','Ongoing') ORDER BY name");
admin_header('Attendance');
?>
<style>
  body{background:#f8fafc}
  h2,h3{color:#1e3a8a;margin:0 0 8px}
  .grid{display:grid;grid-template-columns:repeat(12,1fr);gap:12px}
  .card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:16px;box-shadow:0 2px 6px rgba(0,0,0,.05)}
  select,input{border:1px solid #e5e7eb;border-radius:8px;padding:8px;width:100%}
  button{border-radius:8px;padding:6px 12px;border:1px solid #e5e7eb;cursor:pointer}
  button.primary{background:#2563eb;color:#fff;border-color:#2563eb}
  table{width:100%;border-collapse:collapse;margin-top:8px}
  th,td{padding:8px 10px;border-bottom:1px solid #e5e7eb}
  thead{background:#f1f5f9}
  .status-btn{padding:4px 10px;border-radius:6px;border:1px solid #e5e7eb;font-size:12px;margin-right:4px}
  .PRESENT{background:#dcfce7;color:#166534}
  .ABSENT{background:#fee2e2;color:#991b1b}
  .LEAVE{background:#fff7ed;color:#92400e}
  .progress{height:10px;background:#e5e7eb;border-radius:999px;overflow:hidden;margin-top:4px}
  .bar{height:10px;background:#2563eb;width:0%;transition:.3s}
  .summary{display:none;background:#f1f5f9;border-radius:10px;padding:8px;margin-top:6px;font-size:13px}
  .summary.open{display:block;animation:fadeIn .3s}
  @keyframes fadeIn{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}}
</style>

<h2>Attendance Dashboard</h2>

<div class="grid">
  <div class="card" style="grid-column:span 4">
    <h3>Batch</h3>
    <select id="batchSel">
      <option value="">— Select —</option>
      <?php while($b=mysqli_fetch_assoc($batches)): ?>
        <option value="<?=$b['id']?>"><?=h($b['name'])?></option>
      <?php endwhile; ?>
    </select>
  </div>
  <div class="card" style="grid-column:span 4">
    <h3>Date</h3>
    <input type="date" id="classDate" value="<?=$today?>">
  </div>
  <div class="card" style="grid-column:span 4;text-align:center">
    <h3>Progress</h3>
    <div class="progress"><div id="bar" class="bar"></div></div>
    <div id="barText" style="font-size:13px;color:#475569;margin-top:4px">0 / 0 marked</div>
  </div>
</div>

<div id="studCard" class="card" style="margin-top:14px;display:none">
  <h3 id="batchTitle">Students</h3>
  <table id="attTable"><thead><tr><th>#</th><th>Name</th><th>Status</th><th>Summary</th></tr></thead><tbody></tbody></table>
</div>

<script>
const bSel=document.getElementById('batchSel'),
      box=document.getElementById('studCard'),
      body=document.querySelector('#attTable tbody'),
      bar=document.getElementById('bar'),
      btxt=document.getElementById('barText'),
      date=document.getElementById('classDate');

let total=0,marked=0;
function updateBar(){
  const pct=total?Math.round(marked/total*100):0;
  bar.style.width=pct+'%';
  btxt.textContent=`${marked}/${total} marked (${pct}%)`;
}

/* ------- Load Students ------- */
bSel.onchange=async()=>{
  const bid=bSel.value;if(!bid){box.style.display='none';return;}
  const r=await fetch('attendance.php?action=list_students&batch_id='+bid,{headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d=await r.json(); if(!d.ok){alert('Load error');return;}
  body.innerHTML=''; total=d.items.length; marked=0; updateBar();
  d.items.forEach((s,i)=>{
    body.insertAdjacentHTML('beforeend',`
      <tr>
        <td>${i+1}</td><td>${s.full_name}</td>
        <td>
          <button class="status-btn PRESENT" data-id="${s.id}" data-s="PRESENT">P</button>
          <button class="status-btn ABSENT"  data-id="${s.id}" data-s="ABSENT">A</button>
          <button class="status-btn LEAVE"   data-id="${s.id}" data-s="LEAVE">L</button>
        </td>
        <td>
          <button class="btn summaryBtn" data-id="${s.id}">📊</button>
          <div id="sum-${s.id}" class="summary"></div>
        </td>
      </tr>`);
  });
  box.style.display='block';
};

/* ------- Mark Attendance ------- */
body.addEventListener('click',async e=>{
  if(!e.target.classList.contains('status-btn'))return;
  const sid=e.target.dataset.id,s=e.target.dataset.s,bid=bSel.value,d=date.value;
  const fd=new FormData();fd.append('action','mark');fd.append('student_id',sid);
  fd.append('status',s);fd.append('batch_id',bid);fd.append('class_date',d);
  const r=await fetch('attendance.php',{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
  const j=await r.json();if(!j.ok){alert('Save failed');return;}
  e.target.parentElement.querySelectorAll('.status-btn').forEach(x=>x.style.opacity='.4');
  e.target.style.opacity='1';marked++;updateBar();
});

/* ------- Monthly summary ------- */
body.addEventListener('click',async e=>{
  if(!e.target.classList.contains('summaryBtn'))return;
  const sid=e.target.dataset.id,div=document.getElementById('sum-'+sid);
  if(div.classList.contains('open')){div.classList.remove('open');div.innerHTML='';return;}
  const m=date.value.slice(0,7);
  const r=await fetch('attendance.php?action=monthly&student_id='+sid+'&month='+m,{headers:{'X-Requested-With':'XMLHttpRequest'}});
  const d=await r.json(); if(!d.ok){div.textContent='Error';return;}
  const x=d.data||{};
  div.innerHTML=`<b>${m}</b><br>
    ✅ Presents: ${x.presents||0}<br>
    ❌ Absents: ${x.absents||0}<br>
    💤 Leaves: ${x.leaves||0}<br>
    📅 Total: ${x.total||0}<br>
    📈 Attendance: ${(x.total?((x.presents/x.total)*100).toFixed(1):0)}%`;
  div.classList.add('open');
});
</script>

<?php admin_footer(); ?>
