<?php
/* /elms/lecturer/grade.php */
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_role(['lecturer','super_admin','branch_admin']);

$lecturer_id   = (int)($_SESSION['lecturer_id'] ?? $_SESSION['user']['id'] ?? 0);
$submission_id = (int)($_GET['submission_id'] ?? 0);

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

if ($submission_id <= 0) { http_response_code(400); exit('Missing submission_id'); }

/* Load submission + security check (ownership via assessment or mapping) */
function t_exists(string $t): bool { global $mysqli;
  $st=$mysqli->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
  $st->bind_param('s',$t); $st->execute();
  $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}

$sql = "
SELECT s.*, a.title AS assess_title, a.lecturer_id AS owner_id,
       st.full_name AS student_name,
       COALESCE(b.batch_name, b.name, CONCAT('Batch ', b.id)) AS batch_label,
       a.course_id
FROM lms_submissions s
JOIN lms_assessments a ON a.id=s.assessment_id
JOIN studentss st ON st.id=s.student_id
JOIN batches b ON b.id=s.batch_id
WHERE s.id=?
  AND (
        a.lecturer_id = ?
     ".(t_exists('lecturer_batches') ? " OR EXISTS (SELECT 1 FROM lecturer_batches lb WHERE lb.lecturer_id=? AND lb.batch_id=s.batch_id) " : "")."
     ".(t_exists('lecturer_courses') ? " OR EXISTS (SELECT 1 FROM lecturer_courses lc WHERE lc.lecturer_id=? AND lc.course_id=a.course_id) " : "")."
      )
LIMIT 1";

$params = [$submission_id, $lecturer_id];
$types  = "ii";
if (t_exists('lecturer_batches')) { $params[]=$lecturer_id; $types.="i"; }
if (t_exists('lecturer_courses')) { $params[]=$lecturer_id; $types.="i"; }

$st = $mysqli->prepare($sql);
$st->bind_param($types, ...$params);
$st->execute();
$sub = $st->get_result()->fetch_assoc();
$st->close();

if (!$sub) { http_response_code(404); exit('Submission not found / not yours.'); }

/* Handle POST (grade OR request correction) */
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action   = $_POST['action'] ?? '';
  $score    = isset($_POST['score']) ? (float)$_POST['score'] : null;
  $feedback = trim((string)($_POST['feedback'] ?? ''));

  $mysqli->begin_transaction();
  try {
    if ($action === 'grade') {
      // save provisional grade
      $q=$mysqli->prepare("
        UPDATE lms_submissions
           SET provisional_score=?, feedback=?, graded_at=NOW(),
               workflow_status='graded_provisional'
         WHERE id=? AND workflow_status IN ('submitted','resubmitted','needs_correction')
      ");
      $q->bind_param('dsi',$score,$feedback,$submission_id);
      $q->execute(); $q->close();

      // audit
      $q=$mysqli->prepare("INSERT INTO lms_grade_audit (submission_id,action,actor_role,actor_id,created_at)
                           VALUES (?,?,?, ?,NOW())");
      $act='grade_set'; $role='lecturer';
      $q->bind_param('issi',$submission_id,$act,$role,$lecturer_id);
      $q->execute(); $q->close();

      $mysqli->commit();
      $msg = 'Saved provisional grade.';
    }
    elseif ($action === 'request_correction') {
      $days = max(1, (int)($_POST['resubmit_days'] ?? 7)); // default 7 days
      $q=$mysqli->prepare("
        UPDATE lms_submissions
           SET workflow_status='needs_correction',
               resubmit_deadline=DATE_ADD(NOW(), INTERVAL ? DAY)
         WHERE id=? AND workflow_status IN ('submitted','resubmitted','graded_provisional')
      ");
      $q->bind_param('ii',$days,$submission_id);
      $q->execute(); $q->close();

      // audit
      $q=$mysqli->prepare("INSERT INTO lms_grade_audit (submission_id,action,actor_role,actor_id,created_at)
                           VALUES (?,?,?, ?,NOW())");
      $act='request_correction'; $role='lecturer';
      $q->bind_param('issi',$submission_id,$act,$role,$lecturer_id);
      $q->execute(); $q->close();

      $mysqli->commit();
      $msg = 'Correction requested (resubmission window opened).';
    } else {
      throw new Exception('Unknown action');
    }
  } catch (Throwable $e) {
    $mysqli->rollback();
    $msg = 'Error: '.$e->getMessage();
  }
  // reload fresh state
  header('Location: grade.php?submission_id='.$submission_id.'&msg='.rawurlencode($msg));
  exit;
}
?>
<!doctype html><meta charset="utf-8"><title>Grade</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container py-4">
  <a href="grade_queue.php" class="btn btn-sm btn-outline-secondary mb-3">← Back</a>
  <h4 class="mb-1"><?= esc($sub['assess_title']) ?></h4>
  <div class="text-muted mb-3">Student: <strong><?= esc($sub['student_name']) ?></strong> · Batch: <?= esc($sub['batch_label']) ?></div>
  <?php if (!empty($_GET['msg'])): ?>
    <div class="alert alert-info py-2"><?= esc($_GET['msg']) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <div class="col-lg-7">
      <div class="card mb-3">
        <div class="card-header">Grading</div>
        <div class="card-body">
          <form method="post" class="row g-3">
            <input type="hidden" name="action" value="grade">
            <div class="col-4">
              <label class="form-label">Provisional score</label>
              <input type="number" step="0.01" class="form-control" name="score" value="<?= esc($sub['provisional_score'] ?? '') ?>" required>
            </div>
            <div class="col-12">
              <label class="form-label">Feedback to student</label>
              <textarea name="feedback" rows="4" class="form-control"><?= esc($sub['feedback'] ?? '') ?></textarea>
            </div>
            <div class="col-12">
              <button class="btn btn-primary">Save provisional grade</button>
            </div>
          </form>
        </div>
      </div>

      <div class="card">
        <div class="card-header">Request correction (one resubmission only)</div>
        <div class="card-body">
          <form method="post" class="row g-2">
            <input type="hidden" name="action" value="request_correction">
            <div class="col-6">
              <label class="form-label">Resubmission window (days)</label>
              <input type="number" class="form-control" name="resubmit_days" value="7" min="1" max="30">
            </div>
            <div class="col-12">
              <button class="btn btn-outline-warning">Request correction</button>
              <div class="small text-muted mt-2">
                Student may resubmit <strong>once</strong> before the deadline.
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>

    <div class="col-lg-5">
      <div class="card">
        <div class="card-header">Submission status</div>
        <div class="card-body small">
          <div><strong>Status:</strong> <?= esc($sub['workflow_status'] ?? '') ?></div>
          <div><strong>Submitted at:</strong> <?= esc($sub['submitted_at'] ?? '') ?></div>
          <div><strong>Resubmits used:</strong> <?= (int)$sub['resubmits_used'] ?></div>
          <div><strong>Resubmit deadline:</strong> <?= esc($sub['resubmit_deadline'] ?? '—') ?></div>
        </div>
      </div>
    </div>
  </div>
</div>
