<?php
// /elms/lecturer/assessments/corrections.php
declare(strict_types=1);
if (session_status()===PHP_SESSION_NONE) session_start();
@date_default_timezone_set('Asia/Colombo');

ini_set('display_errors','0');
ini_set('log_errors','1');
ini_set('error_log', __DIR__.'/corrections_error.log');

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

$docroot = rtrim($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__,3), '/');

$attempts=[];
function try_include_db(array $paths, array &$attempts){
  foreach($paths as $p){
    $attempts[]=$p.(is_file($p)?" [exists]":" [missing]");
    if(is_file($p)){ require_once $p; return $p; }
  }
  return null;
}
$loaded_db = try_include_db([
  $docroot.'/elms/includes/db.php',
  dirname(__DIR__,2).'/includes/db.php',
  dirname(__DIR__,1).'/db.php',
], $attempts);

if (!isset($_SESSION['user'])) { http_response_code(403); exit('Forbidden'); }
$who = $_SESSION['user']['full_name'] ?? ($_SESSION['user']['username'] ?? 'Lecturer');

if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
  if (defined('DB_HOST')) { $mysqli = @new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); }
}
if (!$mysqli || $mysqli->connect_errno){ echo "DB not ready"; exit; }
$mysqli->set_charset('utf8mb4');
$mysqli->query("SET time_zone = '+05:30'");

function t_exists(mysqli $db,string $t){ $p=$db->real_escape_string($t); $r=$db->query("SHOW TABLES LIKE '$p'"); $ok=$r&&$r->num_rows>0; if($r)$r->free(); return $ok; }

$sid = (int)($_GET['sid'] ?? 0);
if ($sid<=0){ http_response_code(400); exit('Bad request'); }

$studentsT = t_exists($mysqli,'studentss') ? 'studentss' : (t_exists($mysqli,'students') ? 'students' : null);
$joinStudent = $studentsT ? "LEFT JOIN `$studentsT` st ON st.id=s.student_id" : "";
$studentExpr = $studentsT ? "COALESCE(st.full_name, CONCAT('#',s.student_id))" : "CONCAT('#',s.student_id)";

$submittedExpr = t_exists($mysqli,'lms_submissions') && $mysqli->query("SHOW COLUMNS FROM `lms_submissions` LIKE 'submitted_at'")->num_rows
  ? 's.submitted_at' : ( $mysqli->query("SHOW COLUMNS FROM `lms_submissions` LIKE 'created_at'")->num_rows
  ? 's.created_at' : ( $mysqli->query("SHOW COLUMNS FROM `lms_submissions` LIKE 'updated_at'")->num_rows ? 's.updated_at' : 'NULL'));

$sql = "SELECT s.*, a.title AS assessment_title, $studentExpr AS student_name, $submittedExpr AS submitted_at
        FROM lms_submissions s
        JOIN lms_assessments a ON a.id=s.assessment_id
        $joinStudent
        WHERE s.id=?";
$st = $mysqli->prepare($sql); $st->bind_param('i',$sid); $st->execute();
$rs = $st->get_result(); $sub = $rs? $rs->fetch_assoc():null; if($rs)$rs->free(); $st->close();
if (!$sub){ http_response_code(404); exit('Submission not found'); }

$file_cols = ['file_path','file','doc_path','upload_path','filepath'];
$file_path = '';
foreach ($file_cols as $c){ if (!empty($sub[$c])) { $file_path=$sub[$c]; break; } }

$corrections = [];
if (t_exists($mysqli,'lms_corrections')) {
  $sql = "SELECT c.*, u.full_name AS requested_by_name, u.username
          FROM lms_corrections c
          LEFT JOIN users u ON u.id=c.requested_by
          WHERE c.submission_id=?
          ORDER BY c.created_at DESC";
  $st = $mysqli->prepare($sql); $st->bind_param('i',$sid); $st->execute();
  if (method_exists($st,'get_result')) { $rs=$st->get_result(); while($r=$rs->fetch_assoc()) $corrections[]=$r; if($rs)$rs->free(); }
  $st->close();
}

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Corrections — <?= esc($sub['assessment_title'] ?? '') ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    :root{ --ink:#0f172a; --muted:#64748b; --bg:#f6f7fb; --card:#fff; --line:#e5e7eb; --brand:#5b21b6; }
    body{margin:0;background:var(--bg);color:var(--ink);font-family:system-ui,Segoe UI,Arial,sans-serif}
    .page{display:grid;grid-template-columns:220px 1fr;min-height:100vh}
    @media(max-width:1024px){.page{grid-template-columns:1fr}}
    .sidebar{background:#0b1220;color:#cbd5e1;padding:18px}
    .side-head{font-weight:700;font-size:13px;margin-bottom:14px;text-transform:uppercase;letter-spacing:.08em}
    .who{margin-bottom:10px}
    .nav a{display:block;color:#cbd5e1;text-decoration:none;padding:9px 8px;border-radius:8px}
    .nav a:hover{background:#14203b}
    .content{display:flex;flex-direction:column}
    .topbar{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:14px 18px;border-bottom:1px solid var(--line);background:#fff}
    .title{font-size:20px;font-weight:900}
    .wrap{max-width:1100px;margin:0 auto;padding:22px 20px}
    .card{background:var(--card);border:1px solid var(--line);border-radius:16px;box-shadow:0 10px 24px rgba(0,0,0,.04);padding:16px}
    .btn{display:inline-flex;align-items:center;gap:6px;padding:10px 12px;border-radius:10px;border:1px solid var(--line);background:#fff;cursor:pointer;font-weight:700}
    .muted{color:var(--muted)}
    .timeline{margin:0;padding:0;list-style:none}
    .tl-item{display:grid;grid-template-columns:18px 1fr;gap:10px;margin-bottom:14px}
    .dot{width:10px;height:10px;border-radius:50%;background:#5b21b6;margin-top:8px}
    .badge{padding:.25rem .6rem;border-radius:999px;background:#eef2ff;color:#3730a3;font-weight:800;font-size:12px}
    .filebox{border:1px dashed var(--line);border-radius:12px;padding:10px;background:#fafafa}
  </style>
</head>
<body>
<div class="page">
  <aside class="sidebar">
    <div class="side-head">Lecturer</div>
    <div class="who">
      <div style="font-weight:700"><?= esc($who) ?></div>
      <div style="text-transform:uppercase;font-size:11px;letter-spacing:.08em">LECTURER</div>
    </div>
    <nav class="nav">
      <a href="./grade.php?sid=<?= (int)$sid ?>">← Back to Grade</a>
      <a href="./index.php">🧾 Assessments</a>
      <a href="../../logout.php">🔓 Logout</a>
    </nav>
  </aside>

  <main class="content">
    <div class="topbar">
      <div>
        <div class="title">Corrections</div>
        <div class="muted" style="font-size:12px">
          Student: <?= esc($sub['student_name'] ?? ('#'.$sub['student_id'])) ?> ·
          Assessment: <?= esc($sub['assessment_title'] ?? ('#'.$sub['assessment_id'])) ?> ·
          Submitted: <?= esc($sub['submitted_at'] ?? '') ?>
        </div>
      </div>
      <div class="muted"><?= date('Y-m-d H:i') ?> (Sri Lanka)</div>
    </div>

    <div class="wrap">
      <div class="card">
        <h3>Latest file</h3>
        <?php if ($file_path): ?>
          <div class="filebox">
            <div><b>File:</b> <a href="/<?= esc($file_path) ?>" target="_blank" rel="noopener"><?= esc(basename($file_path)) ?></a></div>
            <div class="muted" style="font-size:12px">Preview in a new tab if needed.</div>
            <div style="margin-top:8px">
              <a class="btn" href="/elms/files/download.php?p=<?= urlencode($file_path) ?>">⬇ Download file</a>
              <a class="btn" href="/elms/lecturer/assessments/report_card.php?sid=<?= (int)$sid ?>">🧾 Download report (PDF)</a>
            </div>
          </div>
        <?php else: ?>
          <div class="muted">No file recorded for this submission.</div>
        <?php endif; ?>
      </div>

      <div class="card" style="margin-top:14px">
        <h3>Correction timeline</h3>
        <?php if (!$corrections): ?>
          <div class="muted">No corrections have been logged for this submission.</div>
          <div style="margin-top:10px">
            <span class="badge">Tip</span> When you press <b>Request correction</b> in the grade page, your feedback is stored as the reason here.
          </div>
        <?php else: ?>
          <ul class="timeline">
            <?php foreach ($corrections as $c): ?>
              <li class="tl-item">
                <div class="dot"></div>
                <div>
                  <div><b>Requested</b> by <?= esc($c['requested_by_name'] ?: $c['username'] ?: $c['requested_role'] ?: 'Lecturer') ?> •
                    <span class="badge"><?= esc($c['status']) ?></span>
                  </div>
                  <div class="muted" style="font-size:12px"><?= esc($c['created_at']) ?></div>
                  <?php if (!empty($c['reason'])): ?>
                    <div style="margin-top:6px;white-space:pre-wrap"><?= esc($c['reason']) ?></div>
                  <?php endif; ?>
                </div>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div>

      <p class="muted" style="text-align:center;margin-top:16px">© <?= date('Y') ?> EdenCampus</p>
    </div>
  </main>
</div>
</body>
</html>
