<?php
// /user/daily_work.php
require_once __DIR__ . '/_user_auth.php';
require_once __DIR__ . '/_user_layout.php';

// Never cache this page
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

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

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

/* -----------------------------------------------
   Helpers
----------------------------------------------- */
function ext_to_category($ext){
  $ext = strtolower($ext);
  $map = [
    'image'   => ['jpg','jpeg','png','gif','webp','bmp'],
    'video'   => ['mp4','webm','ogg','mov','mkv'],
    'audio'   => ['mp3','wav','aac','m4a','flac','oga'],
    'doc'     => ['pdf','doc','docx','ppt','pptx','xls','xlsx','txt','csv'],
    'archive' => ['zip','rar','7z','tar','gz'],
  ];
  foreach($map as $k=>$arr) if (in_array($ext, $arr)) return $k;
  return 'other';
}
function ensure_dir($path){ if (!is_dir($path)) @mkdir($path, 0775, true); }
function file_url_from_rel($rel){ return '../' . ltrim($rel, '/'); }

/* -----------------------------------------------
   Latest course & batch (optional info)
----------------------------------------------- */
$course_id = null; $batch_id = null;
$qr = mysqli_query($conn, "
  SELECT r.course_id, r.batch_id
  FROM registrations r
  WHERE r.student_id={$student_id}
  ORDER BY r.approved_at DESC
  LIMIT 1
");
if ($rr = mysqli_fetch_assoc($qr)) {
  $course_id = (int)$rr['course_id'];
  $batch_id  = (int)$rr['batch_id'];
}

/* -----------------------------------------------
   AJAX Endpoints (JSON)
----------------------------------------------- */
$isAjax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])==='xmlhttprequest');
if ($isAjax) {
  header('Content-Type: application/json; charset=utf-8');

  $act  = $_POST['action'] ?? $_GET['action'] ?? '';
  $csrf = $_POST['csrf']   ?? $_GET['csrf']   ?? '';
  $need = in_array($act, ['submit','delete','edit_save','recheck'], true);
  if ($need && !hash_equals($CSRF, $csrf)) {
    echo json_encode(['ok'=>false,'error'=>'CSRF failed']); exit;
  }

  // SUBMIT
  if ($act === 'submit') {
    $title = trim($_POST['title'] ?? '');
    $desc  = trim($_POST['description'] ?? '');
    $date  = $_POST['work_date'] ?? date('Y-m-d');
    $time  = trim($_POST['time_label'] ?? '');
    if ($title === '') { echo json_encode(['ok'=>false,'error'=>'Title required']); exit; }

    // Fingerprint to avoid re-post on reload (180s window)
    $names = [];
    if (!empty($_FILES['files']) && is_array($_FILES['files']['name'])) {
      foreach($_FILES['files']['name'] as $nm){ $names[] = (string)$nm; }
    }
    $fp = hash('sha256', $student_id.'|'.$title.'|'.$date.'|'.$time.'|'.strlen($desc).'|'.json_encode($names));
    $now = time();
    if (!isset($_SESSION['last_submit_fp'])) $_SESSION['last_submit_fp'] = [];
    if (isset($_SESSION['last_submit_fp'][$fp]) && ($now - $_SESSION['last_submit_fp'][$fp] < 180)) {
      echo json_encode(['ok'=>true,'duplicate'=>true]); exit;
    }

    // DB duplicate guard (same title + date)
    $escTitle = mysqli_real_escape_string($conn, $title);
    $dup = mysqli_fetch_assoc(mysqli_query($conn, "
      SELECT id FROM daily_work_submissions
      WHERE student_id={$student_id}
        AND title='{$escTitle}'
        AND work_date='{$date}'
      LIMIT 1
    "));
    if ($dup) { echo json_encode(['ok'=>false,'error'=>'Already submitted this title for the same date. Edit that one.']); exit; }

    // Insert
    $st = mysqli_prepare($conn, "INSERT INTO daily_work_submissions
      (student_id, course_id, batch_id, work_date, time_label, title, description, points_max, status)
      VALUES (?,?,?,?,?,?,?,10,'SUBMITTED')");
    mysqli_stmt_bind_param($st, "iiissss", $student_id, $course_id, $batch_id, $date, $time, $title, $desc);
    if (!mysqli_stmt_execute($st)) {
      $err = mysqli_stmt_error($st);
      mysqli_stmt_close($st);
      echo json_encode(['ok'=>false,'error'=>"Save error: $err"]); exit;
    }
    $sid = mysqli_insert_id($conn);
    mysqli_stmt_close($st);

    // Files
    if (!empty($_FILES['files']) && is_array($_FILES['files']['name'])) {
      $count = count($_FILES['files']['name']);
      $max   = 20 * 1024 * 1024; // 20MB
      for ($i=0; $i<$count; $i++) {
        if ($_FILES['files']['error'][$i] !== UPLOAD_ERR_OK) continue;
        if ($_FILES['files']['size'][$i]  > $max) continue;

        $orig = $_FILES['files']['name'][$i];
        $tmp  = $_FILES['files']['tmp_name'][$i];
        $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
        if (in_array($ext,['php','phtml','phar'])) continue;

        $cat     = ext_to_category($ext);
        $baseRel = "uploads/work/{$cat}/".date('Y')."/".date('m')."/{$student_id}";
        $baseFs  = dirname(__DIR__) . "/{$baseRel}";
        ensure_dir($baseFs);

        $safe = preg_replace('/[^a-zA-Z0-9_.-]/','_', $orig);
        $name = time().'_'.mt_rand(1000,9999).'_'.$safe;
        $dest = $baseFs . '/' . $name;
        if (move_uploaded_file($tmp, $dest)) {
          $rel = $baseRel . '/' . $name;
          $sf = mysqli_prepare($conn, "INSERT INTO daily_work_files (submission_id,file_path,file_type,original_name) VALUES (?,?,?,?)");
          mysqli_stmt_bind_param($sf, "isss", $sid, $rel, $cat, $orig);
          mysqli_stmt_execute($sf);
          mysqli_stmt_close($sf);
        }
      }
    }

    $_SESSION['last_submit_fp'][$fp] = $now;
    echo json_encode(['ok'=>true,'id'=>$sid]); exit;
  }

  // DELETE (SUBMITTED / RECHECK_REQUESTED only)
  if ($act === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    $r  = mysqli_fetch_assoc(mysqli_query($conn, "
      SELECT status FROM daily_work_submissions WHERE id={$id} AND student_id={$student_id} LIMIT 1
    "));
    if (!$r) { echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }
    if (!in_array($r['status'], ['SUBMITTED','RECHECK_REQUESTED'], true)) {
      echo json_encode(['ok'=>false,'error'=>'Only SUBMITTED or RECHECK_REQUESTED can be deleted']); exit;
    }
    mysqli_query($conn, "DELETE FROM daily_work_submissions WHERE id={$id} AND student_id={$student_id} LIMIT 1");
    echo json_encode(['ok'=>true]); exit;
  }

  // EDIT LOAD
  if ($act === 'edit_load') {
    $id = (int)($_GET['id'] ?? 0);
    $r  = mysqli_fetch_assoc(mysqli_query($conn, "
      SELECT id, title, description, work_date, time_label, status
      FROM daily_work_submissions
      WHERE id={$id} AND student_id={$student_id} LIMIT 1
    "));
    if (!$r) { echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }
    if (!in_array($r['status'], ['SUBMITTED','RECHECK_REQUESTED'], true)) {
      echo json_encode(['ok'=>false,'error'=>'Editing not allowed for current status']); exit;
    }
    echo json_encode(['ok'=>true,'data'=>$r]); exit;
  }

  // EDIT SAVE
  if ($act === 'edit_save') {
    $id    = (int)($_POST['id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $desc  = trim($_POST['description'] ?? '');
    $date  = $_POST['work_date'] ?? date('Y-m-d');
    $time  = trim($_POST['time_label'] ?? '');

    $r = mysqli_fetch_assoc(mysqli_query($conn, "
      SELECT status FROM daily_work_submissions WHERE id={$id} AND student_id={$student_id} LIMIT 1
    "));
    if (!$r) { echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }
    if (!in_array($r['status'], ['SUBMITTED','RECHECK_REQUESTED'], true)) {
      echo json_encode(['ok'=>false,'error'=>'Editing not allowed']); exit;
    }

    $st = mysqli_prepare($conn, "UPDATE daily_work_submissions
      SET title=?, description=?, work_date=?, time_label=?, updated_at=NOW()
      WHERE id=? LIMIT 1");
    mysqli_stmt_bind_param($st, "ssssi", $title, $desc, $date, $time, $id);
    mysqli_stmt_execute($st);
    mysqli_stmt_close($st);
    echo json_encode(['ok'=>true]); exit;
  }

  // RECHECK (only once, and only after decision)
  if ($act === 'recheck') {
    $id   = (int)($_POST['id'] ?? 0);
    $note = trim($_POST['note'] ?? '');

    $r = mysqli_fetch_assoc(mysqli_query($conn, "
      SELECT status, recheck_note
      FROM daily_work_submissions
      WHERE id={$id} AND student_id={$student_id} LIMIT 1
    "));
    if (!$r) { echo json_encode(['ok'=>false,'error'=>'Not found']); exit; }
    if (!in_array($r['status'], ['REVIEWED','APPROVED','REJECTED'], true)) {
      echo json_encode(['ok'=>false,'error'=>'Recheck allowed only after review/decision']); exit;
    }
    // one-time recheck guard
    if (!empty($r['recheck_note'])) {
      echo json_encode(['ok'=>false,'error'=>'You already requested a recheck for this submission.']); exit;
    }

    $st = mysqli_prepare($conn, "UPDATE daily_work_submissions
      SET status='RECHECK_REQUESTED', recheck_note=?, updated_at=NOW()
      WHERE id=? LIMIT 1");
    mysqli_stmt_bind_param($st, "si", $note, $id);
    mysqli_stmt_execute($st);
    mysqli_stmt_close($st);
    echo json_encode(['ok'=>true]); exit;
  }

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

/* -----------------------------------------------
   Summary tiles
----------------------------------------------- */
$totAll = mysqli_fetch_assoc(mysqli_query($conn, "
  SELECT COALESCE(SUM(points_max),0) AS all_max, COUNT(*) AS total_subs
  FROM daily_work_submissions WHERE student_id={$student_id}
"));
$totScored = mysqli_fetch_assoc(mysqli_query($conn, "
  SELECT COALESCE(SUM(points_max),0) AS scored_max,
         COALESCE(SUM(points_obtained),0) AS obtained
  FROM daily_work_submissions
  WHERE student_id={$student_id} AND points_obtained IS NOT NULL
"));
$totPending = mysqli_fetch_assoc(mysqli_query($conn, "
  SELECT COUNT(*) AS pending
  FROM daily_work_submissions
  WHERE student_id={$student_id}
    AND (points_obtained IS NULL OR status IN ('SUBMITTED','RECHECK_REQUESTED'))
"));

$allMax   = (int)($totAll['all_max'] ?? 0);
$obtained = (int)($totScored['obtained'] ?? 0);
$scMax    = (int)($totScored['scored_max'] ?? 0);
$pending  = (int)($totPending['pending'] ?? 0);
$prog     = ($scMax > 0) ? min(100, round($obtained * 100 / $scMax)) : 0;

/* -----------------------------------------------
   Group submissions by date
----------------------------------------------- */
$rows = mysqli_query($conn, "
  SELECT id, work_date, time_label, title, description,
         points_max, points_obtained, status, admin_comment, recheck_note, created_at
  FROM daily_work_submissions
  WHERE student_id={$student_id}
  ORDER BY work_date DESC, created_at DESC
");
$groups = []; $ids = [];
while ($r = mysqli_fetch_assoc($rows)) {
  $d = $r['work_date'] ?: date('Y-m-d', strtotime($r['created_at']));
  $groups[$d][] = $r; $ids[] = (int)$r['id'];
}

$fileMap = [];
if (!empty($ids)) {
  $idList = implode(',', $ids);
  $fq = mysqli_query($conn, "
    SELECT submission_id, file_path
    FROM daily_work_files
    WHERE submission_id IN ($idList) ORDER BY id ASC
  ");
  while ($f = mysqli_fetch_assoc($fq)) {
    $sid = (int)$f['submission_id'];
    $fileMap[$sid][] = $f['file_path'];
  }
}

/* -----------------------------------------------
   Small UI helpers
----------------------------------------------- */
function status_badge($st) {
  $cls = ($st==='APPROVED' || $st==='REVIEWED') ? 'ok'
        : ($st==='RECHECK_REQUESTED' ? 'blue'
          : ($st==='REJECTED' ? 'danger' : 'warn'));
  return '<span class="badge '.$cls.'">'.h($st).'</span>';
}

user_header('Daily Work');
?>
<style>
  /* Modal Background */
.workedit-modal {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,.45);
  display: none;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

/* Dialog Box */
.workedit-dialog {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  width: 95%;
  max-width: 520px;
  box-shadow: 0 10px 40px rgba(0,0,0,.3);
  animation: workeditFade .25s ease;
}

@keyframes workeditFade {
  from { opacity: 0; transform: scale(.95); }
  to { opacity: 1; transform: scale(1); }
}

/* Heading */
.workedit-title {
  margin: 0 0 12px;
  color: #2563eb;
  font-size: 20px;
  font-weight: 600;
}

/* Form Layout */
.workedit-form {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 12px;
}

/* Fields */
.workedit-field {
  grid-column: span 6;
  display: flex;
  flex-direction: column;
}

.workedit-field.small {
  grid-column: span 3;
}

.workedit-field.full {
  grid-column: span 12;
}

/* Labels */
.workedit-label {
  font-size: 13px;
  margin-bottom: 4px;
  color: #6b7280;
}

/* Inputs */
.workedit-input,
.workedit-textarea {
  width: 100%;
  padding: 9px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.workedit-textarea {
  min-height: 90px;
  resize: vertical;
}

/* Buttons Area */
.workedit-actions {
  grid-column: span 12;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* Buttons */
.workedit-btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  background: #e5e7eb;
  transition: .2s;
}

.workedit-btn:hover {
  background: #d1d5db;
}

.workedit-btn.primary {
  background: #2563eb;
  color: #fff;
}

.workedit-btn.primary:hover {
  background: #1e4ed8;
}

  .summary{display:grid;grid-template-columns:repeat(12,1fr);gap:12px}
  .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)}
  .stat{grid-column:span 4}
  .title{font-weight:800;color:#0f172a}
  .muted{color:#64748b;font-size:12px}
  .progress{height:8px;background:#e5e7eb;border-radius:999px;overflow:hidden}
  .bar{height:8px;background:#2563eb}
  .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}
  .grid{display:grid;grid-template-columns:repeat(12,1fr);gap:12px}
  .btn{padding:6px 12px;border:1px solid #e5e7eb;border-radius:8px;cursor:pointer;background:#fff}
  .btn.primary{background:#2563eb;border-color:#2563eb;color:#fff}
  .btn.ghost{background:#f8fafc}
  .day{margin-top:16px}
  .day-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px}
  .item{display:flex;align-items:center;justify-content:space-between;border:1px solid #e5e7eb;border-radius:10px;padding:10px;background:#fff}
  .left{display:flex;align-items:center;gap:10px}
  .chip{padding:2px 8px;border-radius:999px;border:1px solid #e5e7eb;background:#f8fafc;font-size:11px}
  .actions{display:flex;gap:8px;flex-wrap:wrap}
  .details{display:none;margin-top:8px;border-left:3px solid #2563eb;padding-left:10px}
  .gallery{display:flex;gap:8px;flex-wrap:wrap;margin-top:8px}
  .thumb{border:1px solid #e5e7eb;border-radius:8px;overflow:hidden}
  .thumb img{width:180px;height:120px;object-fit:cover;display:block}
  .thumb video{width:220px;height:140px;display:block}

  /* Scoped Submit Form styling (won’t conflict with layout) */
  #workFormCard { --c-bg:#fff; --c-br:#e5e7eb; --c-t:#0f172a; --c-muted:#64748b; --c-prim:#2563eb; --c-prim-100:#dbeafe; --c-prim-200:#bfdbfe;
    border:1px solid var(--c-br); border-radius:14px; background:var(--c-bg); padding:18px;
    box-shadow:0 1px 2px rgba(15,23,42,.04), 0 8px 24px rgba(15,23,42,.06);
  }
  #workFormCard .form-title{margin:0 0 10px;color:var(--c-prim);font-weight:800;font-size:18px}
  #workFormCard .form-help{color:var(--c-muted);font-size:12px;margin-top:6px}
  #workFormCard .form-row{display:grid;grid-template-columns:repeat(12,1fr);gap:12px}
  #workFormCard .col-12{grid-column:span 12}
  #workFormCard .col-6{grid-column:span 6}
  #workFormCard .col-3{grid-column:span 3}
  #workFormCard .form-label{display:block;font-size:12px;color:var(--c-muted);margin-bottom:4px;font-weight:600}
  #workFormCard .form-control{width:100%;height:40px;background:#fff;border:1px solid var(--c-br);border-radius:10px;padding:8px 12px;color:var(--c-t);outline:none;transition:border-color .15s, box-shadow .15s;}
  #workFormCard .form-control:focus{border-color:var(--c-prim);box-shadow:0 0 0 3px var(--c-prim-100);}
  #workFormCard textarea.form-control{min-height:110px;resize:vertical}
  #workFormCard .btn{border:1px solid var(--c-br);border-radius:10px;background:#fff;padding:8px 12px;cursor:pointer;font-weight:600}
  #workFormCard .btn.primary{background:var(--c-prim);border-color:var(--c-prim);color:#fff}
  #workFormCard .btn.ghost{background:#f8fafc}
  @media (max-width:900px){ #workFormCard .col-6,#workFormCard .col-3{grid-column:span 12} .stat{grid-column:span 12} }
</style>

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

<!-- Summary -->
<div class="summary">
  <div class="card stat">
    <div class="title">Reviewed Points</div>
    <div style="font-size:24px;font-weight:800;margin:4px 0"><?= $obtained ?> / <?= $scMax ?></div>
    <div class="progress"><div class="bar" style="width:<?= $prog ?>%"></div></div>
    <div class="muted" style="margin-top:4px"><?= $prog ?>% of reviewed work</div>
  </div>
  <div class="card stat">
    <div class="title">Total Potential</div>
    <div style="font-size:24px;font-weight:800;margin:4px 0"><?= $allMax ?></div>
    <div class="muted">Sum of points_max for all submissions</div>
  </div>
  <div class="card stat">
    <div class="title">Pending</div>
    <div style="font-size:24px;font-weight:800;margin:4px 0"><?= $pending ?></div>
    <div class="muted">Submitted / Recheck yet to be scored</div>
  </div>
</div>

<!-- Submit form (scoped styles) -->
<div id="workFormCard" class="card" style="margin-top:16px">
  <h3 class="form-title">Submit Work</h3>
  <form id="workForm" enctype="multipart/form-data" class="form-row">
    <input type="hidden" name="action" value="submit">
    <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">

    <div class="col-6">
      <label class="form-label">Title</label>
      <input class="form-control" name="title" placeholder="e.g., HTML Forms Practice" required>
    </div>
    <div class="col-3">
      <label class="form-label">Date</label>
      <input class="form-control" type="date" name="work_date" value="<?= h(date('Y-m-d')) ?>" required>
    </div>
    <div class="col-3">
      <label class="form-label">Time label</label>
      <input class="form-control" name="time_label" placeholder="Morning / Slot">
    </div>
    <div class="col-12">
      <label class="form-label">Description</label>
      <textarea class="form-control" name="description" placeholder="What did you do today?"></textarea>
      <div class="form-help">Attach files below. Up to 20MB/file. Images, videos, audio, docs & archives supported.</div>
    </div>
    <div class="col-12">
      <label class="form-label">Attach files (multiple)</label>
      <input class="form-control" type="file" name="files[]" multiple>
    </div>
    <div class="col-12" style="display:flex;gap:8px;justify-content:flex-end">
      <button class="btn primary" id="submitBtn">Submit</button>
      <button type="reset" class="btn ghost">Reset</button>
    </div>
  </form>
  <div id="submitMsg" class="form-help"></div>
</div>

<!-- Grouped submissions -->
<h3 style="margin-top:18px">Your Work by Day</h3>

<?php if (empty($groups)): ?>
  <div class="card" style="margin-top:8px;color:#64748b">No submissions yet.</div>
<?php endif; ?>

<?php foreach ($groups as $day => $items): ?>
  <div class="day">
    <div class="day-head">
      <div class="title"><?= h(date('d M Y', strtotime($day))) ?></div>
      <div class="muted"><?= count($items) ?> item(s)</div>
    </div>

    <div class="grid" style="grid-template-columns:repeat(12,1fr)">
      <div style="grid-column:span 12; display:grid; gap:8px">
        <?php foreach ($items as $it):
          $sid  = (int)$it['id'];
          $pts  = is_null($it['points_obtained']) ? '—' : ((int)$it['points_obtained']).' / '.(int)$it['points_max'];
          $canEdit    = in_array($it['status'], ['SUBMITTED','RECHECK_REQUESTED'], true);
          $canDelete  = $canEdit;
          $canRecheck = in_array($it['status'], ['REVIEWED','APPROVED','REJECTED'], true) && empty($it['recheck_note']); // one-time
        ?>
          <div class="item">
            <div class="left">
              <?= status_badge($it['status']) ?>
              <div>
                <div style="font-weight:700"><?= h($it['title']) ?></div>
                <div class="muted"><?= h($it['time_label']) ?></div>
              </div>
            </div>
            <div class="actions">
              <span class="chip">Points: <?= $pts ?></span>
              <button class="btn viewBtn" data-id="<?= $sid ?>">View</button>
              <?php if ($canEdit): ?><button class="btn editBtn" data-id="<?= $sid ?>">Edit</button><?php endif; ?>
              <?php if ($canDelete): ?><button class="btn delBtn" data-id="<?= $sid ?>">Delete</button><?php endif; ?>
              <?php if ($canRecheck): ?><button class="btn recheckBtn" data-id="<?= $sid ?>">Recheck</button><?php endif; ?>
            </div>
          </div>

          <!-- Details -->
          <div id="details-<?= $sid ?>" class="details">
            <?php if (!empty($it['description'])): ?>
              <div style="white-space:pre-wrap"><?= h($it['description']) ?></div>
            <?php endif; ?>

            <?php if (!empty($fileMap[$sid])): ?>
              <div class="gallery">
                <?php foreach ($fileMap[$sid] as $fp):
                  $url = file_url_from_rel($fp);
                  $ext = strtolower(pathinfo($fp, PATHINFO_EXTENSION));
                ?>
                  <?php if (in_array($ext, ['jpg','jpeg','png','gif','webp'])): ?>
                    <div class="thumb"><a href="<?= $url ?>" target="_blank"><img src="<?= $url ?>"></a></div>
                  <?php elseif (in_array($ext, ['mp4','webm','ogg','mov','mkv'])): ?>
                    <div class="thumb"><video src="<?= $url ?>" controls></video></div>
                  <?php elseif ($ext === 'pdf'): ?>
                    <div class="thumb" style="width:180px;height:120px;display:flex;align-items:center;justify-content:center;flex-direction:column">
                      <div>📄 PDF</div><a class="btn" href="<?= $url ?>" target="_blank">Open</a>
                    </div>
                  <?php else: ?>
                    <div class="thumb" style="width:180px;height:120px;display:flex;align-items:center;justify-content:center;flex-direction:column">
                      <div>📁 File</div><a class="btn" href="<?= $url ?>" target="_blank">Download</a>
                    </div>
                  <?php endif; ?>
                <?php endforeach; ?>
              </div>
            <?php else: ?>
              <div class="muted">No files attached.</div>
            <?php endif; ?>

            <?php if (!empty($it['admin_comment'])): ?>
              <div class="card" style="margin-top:8px;background:#f1f5f9"> <b>Admin:</b> <?= h($it['admin_comment']) ?> </div>
            <?php endif; ?>

            <?php if (!empty($it['recheck_note'])): ?>
              <div class="card" style="margin-top:8px;background:#fff7ed"> <b>Your recheck:</b> <?= h($it['recheck_note']) ?> </div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
<?php endforeach; ?>

<!-- Edit Modal -->
<!-- <div id="modal" style="position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;align-items:center;justify-content:center;z-index:60">
  <div class="dialog" style="background:#fff;border-radius:12px;padding:16px;width:96%;max-width:520px;box-shadow:0 10px 40px rgba(0,0,0,.3)">
    <h3 style="margin:0 0 8px;color:#2563eb">Edit Work</h3>
    <form id="editForm" class="grid" style="grid-template-columns:repeat(12,1fr);gap:12px">
      <input type="hidden" name="action" value="edit_save">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="id" id="eid">
      <div style="grid-column:span 6">
        <label class="muted">Title</label>
        <input  class="form-control" name="title" id="etitle" required>
      </div>
      <div style="grid-column:span 3">
        <label class="muted">Date</label>
        <input class="form-control" type="date" name="work_date" id="edate" required>
      </div>
      <div style="grid-column:span 3">
        <label class="muted">Time label</label>
        <input class="form-control" name="time_label" id="etime">
      </div>
      <div style="grid-column:span 12">
        <label class="muted">Description</label>
        <textarea class="form-control" name="description" id="edesc"></textarea>
      </div>
      <div style="grid-column:span 12; display:flex; gap:8px; justify-content:flex-end">
        <button class="btn primary">Save</button>
        <button type="button" class="btn" id="closeModal">Cancel</button>
      </div>
    </form>
  </div>
</div> -->
<div id="modal" class="workedit-modal">
  <div class="workedit-dialog">
    <h3 class="workedit-title">Edit Work</h3>

    <form id="editForm" class="workedit-form">
      <input type="hidden" name="action" value="edit_save">
      <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
      <input type="hidden" name="id" id="eid">

      <div class="workedit-field">
        <label class="workedit-label">Title</label>
        <input class="workedit-input" name="title" id="etitle" required>
      </div>

      <div class="workedit-field small">
        <label class="workedit-label">Date</label>
        <input type="date" class="workedit-input" name="work_date" id="edate" required>
      </div>

      <div class="workedit-field small">
        <label class="workedit-label">Time label</label>
        <input class="workedit-input" name="time_label" id="etime">
      </div>

      <div class="workedit-field full">
        <label class="workedit-label">Description</label>
        <textarea class="workedit-textarea" name="description" id="edesc"></textarea>
      </div>

      <div class="workedit-actions">
        <button class="workedit-btn primary">Save</button>
        <button type="button" class="workedit-btn" id="closeModal">Cancel</button>
      </div>
    </form>
  </div>
</div>

<script>
const submitForm = document.getElementById('workForm');
const submitBtn  = document.getElementById('submitBtn');
const submitMsg  = document.getElementById('submitMsg');

submitForm.addEventListener('submit', async (e)=>{
  e.preventDefault();
  submitBtn.disabled = true;
  submitMsg.textContent = 'Submitting...';
  const fd = new FormData(submitForm);
  try{
    const res = await fetch('daily_work.php', { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const data = await res.json();
    if(!data.ok){
      submitMsg.textContent = data.error || 'Failed';
      submitBtn.disabled = false;
      return;
    }
    submitMsg.textContent = data.duplicate ? 'Already submitted recently (ignored duplicate) ✔' : 'Submitted ✔';
    submitForm.reset();
    // Reload via GET (no form re-post)
    location.reload();
  }catch(err){
    submitMsg.textContent = 'Network error';
    submitBtn.disabled = false;
  }
});

// View toggle
document.querySelectorAll('.viewBtn').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    const id = btn.dataset.id;
    const div = document.getElementById('details-'+id);
    div.style.display = (div.style.display==='block' ? 'none' : 'block');
    if(div.style.display==='block'){ div.scrollIntoView({behavior:'smooth', block:'center'}); }
  });
});

// Delete
document.querySelectorAll('.delBtn').forEach(btn=>{
  btn.addEventListener('click', async ()=>{
    if(!confirm('Delete this work?')) return;
    const fd = new FormData();
    fd.append('action','delete');
    fd.append('csrf','<?= h($CSRF) ?>');
    fd.append('id', btn.dataset.id);
    const res = await fetch('daily_work.php',{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    const data = await res.json();
    if(!data.ok){ alert(data.error||'Delete failed'); return; }
    location.reload();
  });
});

// Recheck (one-time)
document.querySelectorAll('.recheckBtn').forEach(btn=>{
  btn.addEventListener('click', async ()=>{
    const note = prompt('Recheck reason (optional):','');
    if(note===null) return;
    const fd = new FormData();
    fd.append('action','recheck');
    fd.append('csrf','<?= h($CSRF) ?>');
    fd.append('id', btn.dataset.id);
    fd.append('note', note);
    const res = await fetch('daily_work.php',{method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    const data = await res.json();
    if(!data.ok){ alert(data.error||'Recheck failed'); return; }
    location.reload();
  });
});

// Edit modal
const modal = document.getElementById('modal');
document.getElementById('closeModal').onclick = ()=> modal.style.display='none';

document.querySelectorAll('.editBtn').forEach(btn=>{
  btn.addEventListener('click', async ()=>{
    const id = btn.dataset.id;
    const url = 'daily_work.php?action=edit_load&id='+encodeURIComponent(id);
    try{
      const res = await fetch(url, { headers:{'X-Requested-With':'XMLHttpRequest'} });
      const data = await res.json();
      if(!data.ok){ alert(data.error||'Load failed'); return; }
      document.getElementById('eid').value    = data.data.id ?? '';
      document.getElementById('etitle').value = data.data.title ?? '';
      document.getElementById('edate').value  = data.data.work_date ?? '<?= h(date('Y-m-d')) ?>';
      document.getElementById('etime').value  = data.data.time_label ?? '';
      document.getElementById('edesc').value  = data.data.description ?? '';
      modal.style.display = 'flex';
    }catch(e){
      alert('Network error while loading.');
    }
  });
});

document.getElementById('editForm').addEventListener('submit', async (e)=>{
  e.preventDefault();
  const fd = new FormData(e.target);
  const res = await fetch('daily_work.php', { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
  const data = await res.json();
  if(!data.ok){ alert(data.error||'Update failed'); return; }
  modal.style.display='none';
  location.reload();
});
</script>

<?php user_footer(); ?>
