<?php
// /admin/daily_work.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'); }
}

/* ---------- CSRF ---------- */
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf'];

/* ---------- Filters ---------- */
$status = $_GET['status'] ?? '';
$q = trim($_GET['q'] ?? '');
$where = " WHERE 1=1 ";
if ($status && in_array($status,['SUBMITTED','REVIEWED','APPROVED','REJECTED','RECHECK_REQUESTED'], true)) {
  $where .= " AND s.status='".mysqli_real_escape_string($conn,$status)."' ";
}
if ($q !== '') {
  $qesc = mysqli_real_escape_string($conn, $q);
  $where .= " AND (st.full_name LIKE '%$qesc%' OR s.title LIKE '%$qesc%') ";
}

/* ---------- Handle Review Save ---------- */
$msg = $err = '';
if ($_SERVER['REQUEST_METHOD']==='POST'
    && ($_POST['action'] ?? '')==='save_review'
    && hash_equals($CSRF, $_POST['csrf'] ?? '')
) {
  $sid       = (int)($_POST['sid'] ?? 0);
  $status_in = $_POST['status'] ?? 'REVIEWED';
  $comment   = trim($_POST['comment'] ?? '');

  // fetch points_max to clamp
  $pm = null;
  if ($sid > 0) {
    $st = mysqli_prepare($conn, "SELECT points_max FROM daily_work_submissions WHERE id=? LIMIT 1");
    mysqli_stmt_bind_param($st, "i", $sid);
    mysqli_stmt_execute($st);
    $rs = mysqli_stmt_get_result($st);
    $pm = mysqli_fetch_assoc($rs);
    mysqli_stmt_close($st);
  }

  if (!$pm) {
    $err = "Submission not found.";
  } else {
    $points_max = (int)$pm['points_max'];
    $points     = (int)($_POST['points'] ?? 0);

    // Enforce status
    if (!in_array($status_in, ['REVIEWED','APPROVED','REJECTED'], true)) {
      $status_in = 'REVIEWED';
    }

    // REJECTED => always zero points
    if ($status_in === 'REJECTED') {
      $points = 0;
    } else {
      if ($points < 0) $points = 0;
      if ($points > $points_max) $points = $points_max;
    }

    $up = mysqli_prepare($conn, "
      UPDATE daily_work_submissions
      SET points_obtained=?, status=?, admin_comment=?, updated_at=NOW()
      WHERE id=?
    ");
    mysqli_stmt_bind_param($up, "issi", $points, $status_in, $comment, $sid);
    if (!mysqli_stmt_execute($up)) {
      $err = "Error: " . mysqli_stmt_error($up);
    } else {
      $msg = "Updated submission #{$sid}";
    }
    mysqli_stmt_close($up);
  }
}

/* ---------- Load submissions ---------- */
$sql = "
  SELECT s.id, s.title, s.work_date, s.status, s.points_obtained, s.points_max, s.recheck_note,
         st.full_name
  FROM daily_work_submissions s
  JOIN students st ON st.id=s.student_id
  $where
  ORDER BY s.created_at DESC
  LIMIT 300
";
$list = mysqli_query($conn, $sql);

admin_header('Daily Work Review');
?>
<style>
  .filters{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end;margin-bottom:10px}
  .filters input,.filters select{border:1px solid #e5e7eb;border-radius:10px;padding:8px 10px;height:38px}
  .card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:14px;box-shadow:0 1px 2px rgba(15,23,42,.04),0 8px 24px rgba(15,23,42,.06)}
  table{width:100%;border-collapse:separate;border-spacing:0}
  th,td{padding:10px 12px;border-bottom:1px solid #e5e7eb}
  thead th{background:#f1f5f9;font-size:13px;position:sticky;top:0;z-index:1}
  tbody tr:hover{background:#f9fafb}
  .badge{padding:3px 8px;border-radius:999px;font-size:11px;font-weight:700;border:1px solid #e5e7eb}
  .ok{background:#dcfce7;color:#166534;border-color:#86efac}
  .warn{background:#fff7ed;color:#9a3412;border-color:#fed7aa}
  .blue{background:#dbeafe;color:#1e3a8a;border-color:#bfdbfe}
  .danger{background:#fee2e2;color:#991b1b;border-color:#fecaca}
  .row-flag{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:#1e3a8a}
  /* Modal */
  .modal{position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;align-items:center;justify-content:center;z-index:60}
  .modal.show{display:flex}
  .dialog{background:#fff;border-radius:12px;padding:16px;width:96%;max-width:960px;max-height:90vh;overflow:auto;position:relative;box-shadow:0 10px 40px rgba(0,0,0,.25)}
  .close{position:absolute;right:12px;top:10px;cursor:pointer;color:#64748b}
  .btn{border:1px solid #e5e7eb;border-radius:10px;padding:8px 12px;background:#fff;cursor:pointer}
  .btn.primary{background:#2563eb;border-color:#2563eb;color:#fff}
</style>

<h2 style="margin:0 0 8px">Daily Work — Admin Review</h2>

<form class="filters" method="get">
  <input name="q" placeholder="Search by name/title" value="<?=h($q)?>" style="max-width:240px">
  <select name="status" style="max-width:200px">
    <option value="">Status: All</option>
    <?php foreach(['SUBMITTED','REVIEWED','APPROVED','REJECTED','RECHECK_REQUESTED'] as $s): ?>
      <option value="<?=$s?>" <?=$s===$status?'selected':''?>><?=$s?></option>
    <?php endforeach; ?>
  </select>
  <button class="btn">Filter</button>
  <a class="btn" href="daily_work.php">Reset</a>
</form>

<?php if($msg): ?><div class="card" style="background:#f0fdf4;border-color:#86efac;color:#065f46"><?=h($msg)?></div><?php endif; ?>
<?php if($err): ?><div class="card" style="background:#fff1f2;border-color:#fecaca;color:#991b1b"><?=h($err)?></div><?php endif; ?>

<div class="card">
  <div style="overflow:auto;border-radius:10px;border:1px solid #e5e7eb">
    <table>
      <thead>
        <tr>
          <th style="text-align:center;width:70px">ID</th>
          <th>Student</th>
          <th>Title</th>
          <th style="width:120px">Date</th>
          <th style="width:140px">Status</th>
          <th style="width:120px">Points</th>
          <th style="text-align:center;width:120px">Action</th>
        </tr>
      </thead>
      <tbody>
      <?php if(!$list || mysqli_num_rows($list)==0): ?>
        <tr><td colspan="7" style="text-align:center;color:#64748b">No submissions found</td></tr>
      <?php else: while($r=mysqli_fetch_assoc($list)): 
        $cls = ($r['status']==='REVIEWED' || $r['status']==='APPROVED') ? 'ok' :
               ($r['status']==='RECHECK_REQUESTED' ? 'blue' :
                ($r['status']==='REJECTED' ? 'danger' : 'warn'));
        $pts = is_null($r['points_obtained']) ? '-' : ((int)$r['points_obtained']).'/'.(int)$r['points_max'];
      ?>
        <tr>
          <td style="text-align:center"><?= (int)$r['id'] ?></td>
          <td><?= h($r['full_name']) ?></td>
          <td>
            <?= h($r['title']) ?>
            <?php if(!empty($r['recheck_note'])): ?>
              <span class="row-flag">• 🔁 Recheck requested</span>
            <?php endif; ?>
          </td>
          <td><?= h($r['work_date']) ?></td>
          <td><span class="badge <?=$cls?>"><?= h($r['status']) ?></span></td>
          <td><?= $pts ?></td>
          <td style="text-align:center">
            <button type="button" class="btn primary reviewBtn" data-sid="<?= (int)$r['id'] ?>">Review</button>
          </td>
        </tr>
      <?php endwhile; endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal -->
<div class="modal" id="reviewModal">
  <div class="dialog">
    <span class="close" id="mClose">✕</span>
    <div id="mContent">Loading…</div>
  </div>
</div>

<script>
  const modal   = document.getElementById('reviewModal');
  const content = document.getElementById('mContent');
  const closeBtn= document.getElementById('mClose');

  document.querySelectorAll('.reviewBtn').forEach(btn=>{
    btn.addEventListener('click', async ()=>{
      const sid = btn.dataset.sid;
      modal.classList.add('show');
      content.innerHTML = 'Loading…';

      // Build path to admin/daily_work_view.php in same folder
      const base = window.location.pathname.replace(/[^\/]+$/, ''); // e.g. /zetechup/admin/
      const url  = base + 'daily_work_view.php?id=' + encodeURIComponent(sid);

      try{
        const res = await fetch(url, { credentials:'same-origin' });
        if(!res.ok){
          content.innerHTML = `<div style="color:#991b1b">Failed to load (HTTP ${res.status}).</div>`;
          return;
        }
        const html = await res.text();
        content.innerHTML = html;
      }catch(e){
        content.innerHTML = `<div style="color:#991b1b">Network error.</div>`;
      }
    });
  });

  closeBtn.onclick = ()=> modal.classList.remove('show');
  window.addEventListener('click',(e)=>{ if(e.target===modal) modal.classList.remove('show'); });
</script>

<?php admin_footer(); ?>
