<?php
// /admin/daily_work_view.php
require_once __DIR__ . '/_auth.php';
header('Content-Type: text/html; charset=utf-8');

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

// CSRF for posting back to /admin/daily_work.php
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf'];

$id = (int)($_GET['id'] ?? 0);
if(!$id){ echo '<div>Invalid ID</div>'; exit; }

$q = mysqli_query($conn, "
  SELECT s.*, st.full_name
  FROM daily_work_submissions s
  JOIN students st ON st.id=s.student_id
  WHERE s.id=$id
  LIMIT 1
");
$s = mysqli_fetch_assoc($q);
if(!$s){ echo "<div>Submission not found.</div>"; exit; }

$fq = mysqli_query($conn,"
  SELECT file_path,file_type,original_name
  FROM daily_work_files WHERE submission_id=$id ORDER BY id ASC
");

$recheck = ($s['status']==='RECHECK_REQUESTED');
?>
<style>
  body{font-family:system-ui,-apple-system,Segoe UI,Roboto}
  .muted{color:#64748b;font-size:13px}
  .files{display:flex;gap:8px;flex-wrap:wrap;margin-top:8px}
  .file-box{border:1px solid #e5e7eb;border-radius:8px;overflow:hidden;background:#fff}
  .file-box img{width:160px;height:110px;object-fit:cover;display:block}
  .file-box video{width:160px;height:110px;display:block}
  .file-box .meta{font-size:11px;padding:4px 6px;border-top:1px solid #e5e7eb;text-align:center}
  .alert-recheck{background:#fff7ed;border:1px solid #fed7aa;color:#92400e;padding:10px;border-radius:10px;margin:10px 0}
  label{font-size:13px;color:#475569;margin-top:6px;display:block}
  input,select,textarea{width:100%;border:1px solid #e5e7eb;border-radius:10px;padding:8px 10px;height:38px}
  textarea{min-height:100px}
  button{padding:10px 12px;border-radius:10px;border:1px solid #2563eb;background:#2563eb;color:#fff;cursor:pointer;margin-top:6px}
</style>

<h3 style="margin:0 0 6px;color:#2563eb"><?=h($s['title'])?></h3>
<div class="muted">
  Student: <b><?=h($s['full_name'])?></b> • <?=h($s['work_date'])?> •
  Status: <b><?=h($s['status'])?></b>
</div>

<?php if($recheck): ?>
  <div class="alert-recheck">
    🔁 <b>Recheck Requested</b><br>
    <?= h($s['recheck_note'] ?: 'No reason provided.') ?>
  </div>
<?php endif; ?>

<?php if(!empty($s['description'])): ?>
  <p style="white-space:pre-wrap; margin-top:10px"><?=h($s['description'])?></p>
<?php endif; ?>

<?php if(mysqli_num_rows($fq)>0): ?>
  <h4 style="margin:10px 0 4px">Files</h4>
  <div class="files">
    <?php while($f=mysqli_fetch_assoc($fq)):
      $url='../'.$f['file_path'];
      $ext=strtolower(pathinfo($f['file_path'],PATHINFO_EXTENSION));
      if(in_array($ext,['jpg','jpeg','png','gif','webp'])): ?>
        <div class="file-box"><a href="<?=$url?>" target="_blank"><img src="<?=$url?>"></a><div class="meta">Image</div></div>
      <?php elseif(in_array($ext,['mp4','webm','ogg'])): ?>
        <div class="file-box"><video src="<?=$url?>" controls></video><div class="meta">Video</div></div>
      <?php else: ?>
        <div class="file-box" style="width:160px;height:110px;display:flex;align-items:center;justify-content:center;flex-direction:column">
          <div>📁 File</div><a href="<?=$url?>" target="_blank">Open</a>
        </div>
      <?php endif; endwhile; ?>
  </div>
<?php endif; ?>

<hr style="margin:12px 0">

<form method="post" action="daily_work.php" style="display:grid;gap:8px">
  <input type="hidden" name="action" value="save_review">
  <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
  <input type="hidden" name="sid" value="<?= (int)$s['id'] ?>">

  <label>Points (0–<?= (int)$s['points_max'] ?>)</label>
  <input type="number" name="points" value="<?= h($s['points_obtained']) ?>" min="0" max="<?= (int)$s['points_max'] ?>" step="1" required>

  <label>Status</label>
  <select name="status" required>
    <?php foreach(['REVIEWED','APPROVED','REJECTED'] as $st): ?>
      <option <?= $s['status']===$st ? 'selected':'' ?>><?= $st ?></option>
    <?php endforeach; ?>
  </select>

  <label>Admin Comment</label>
  <textarea name="comment" placeholder="Feedback for student..."><?= h($s['admin_comment']) ?></textarea>

  <button type="submit">💾 Save Review</button>
</form>

<script>
  // Lock points to 0 when REJECTED (UI hint; server also enforces)
  (function(){
    const statusSel = document.querySelector('select[name="status"]');
    const pointsInp = document.querySelector('input[name="points"]');
    function sync(){
      if (!statusSel || !pointsInp) return;
      if (statusSel.value === 'REJECTED') {
        pointsInp.value = 0;
        pointsInp.setAttribute('readonly','readonly');
        pointsInp.style.opacity = .6;
        pointsInp.title = 'Rejected submissions always save 0 points';
      } else {
        pointsInp.removeAttribute('readonly');
        pointsInp.style.opacity = 1;
        pointsInp.title = '';
        if (pointsInp.value === '') pointsInp.value = 0;
      }
    }
    statusSel && statusSel.addEventListener('change', sync);
    sync();
  })();
</script>
