<?php
/* /elms/student/submit_handler.php
   POST: assessment_id, (optionally upload file), etc.
*/
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/student_auth.php'; // or your auth
require_student();

$student_id   = (int)$_SESSION['student_id'];
$assessment_id= (int)($_POST['assessment_id'] ?? 0);

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

// (Do your upload handling here if needed and set $file_path / $submission_notes, etc.)

$mysqli->begin_transaction();
try {
  // Lock the row for this student/assessment
  $q=$mysqli->prepare("
    SELECT id, workflow_status, resubmits_used, resubmit_deadline
      FROM lms_submissions
     WHERE assessment_id=? AND student_id=?
     FOR UPDATE
  ");
  $q->bind_param('ii',$assessment_id,$student_id);
  $q->execute();
  $r = $q->get_result()->fetch_assoc();
  $q->close();

  // Create row if none
  if (!$r) {
    $q=$mysqli->prepare("
      INSERT INTO lms_submissions (assessment_id, student_id, batch_id, submitted_at, workflow_status, resubmits_used)
      VALUES (?, ?, (SELECT batch_id FROM enrollments WHERE student_id=? LIMIT 1), NOW(), 'submitted', 0)
    ");
    $q->bind_param('iii',$assessment_id,$student_id,$student_id);
    $q->execute(); $q->close();
  } else {
    $status   = (string)$r['workflow_status'];
    $used     = (int)$r['resubmits_used'];
    $deadline = $r['resubmit_deadline'] ? strtotime((string)$r['resubmit_deadline']) : null;
    $now = time();

    if ($status === 'needs_correction') {
      if ($used >= 1) { throw new Exception('Resubmission limit reached.'); }
      if ($deadline && $now > $deadline) { throw new Exception('Resubmission window closed.'); }

      $q=$mysqli->prepare("
        UPDATE lms_submissions
           SET resubmits_used = resubmits_used + 1,
               submitted_at   = NOW(),
               workflow_status= 'resubmitted'
         WHERE id=?
      ");
      $q->bind_param('i',$r['id']);
      $q->execute(); $q->close();
    } else {
      // first-time submit or re-submit from draft
      $q=$mysqli->prepare("
        UPDATE lms_submissions
           SET submitted_at = NOW(),
               workflow_status = 'submitted'
         WHERE id=? AND workflow_status IN ('new','draft','submitted')
      ");
      $q->bind_param('i',$r['id']);
      $q->execute(); $q->close();
    }
  }

  // (optionally save uploaded file path, notes, etc. here)

  $mysqli->commit();
  header('Location: /elms/student/assessments/index.php?msg='.rawurlencode('Submitted.'));
} catch (Throwable $e) {
  $mysqli->rollback();
  http_response_code(400);
  echo 'Submit failed: '.$e->getMessage();
}
