<?php
// /elms/student/assessments/submit.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../../includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
  http_response_code(500);
  exit('DB connection failed');
}

$mysqli->set_charset('utf8mb4');

if (empty($_SESSION['student_id'])) {
  header('Location: /elms/student/login.php?next=' . rawurlencode($_SERVER['REQUEST_URI'] ?? '/elms/student/assessments/index.php'));
  exit;
}

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

function table_exists(mysqli $db, string $table): bool {
  $table = $db->real_escape_string($table);
  $q = $db->query("SHOW TABLES LIKE '{$table}'");
  return $q && $q->num_rows > 0;
}

function col_exists(mysqli $db, string $table, string $col): bool {
  $table = $db->real_escape_string($table);
  $col = $db->real_escape_string($col);
  $q = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  return $q && $q->num_rows > 0;
}

function flash($key, $value = null) {
  if ($value === null) {
    $msg = $_SESSION['flash'][$key] ?? null;
    unset($_SESSION['flash'][$key]);
    return $msg;
  }

  $_SESSION['flash'][$key] = $value;
}

function clean_file_name(string $name): string {
  $name = preg_replace('/[^A-Za-z0-9._-]+/', '_', $name);
  return trim($name, '._');
}

function public_file_url(string $relative): string {
  return '/elms/' . ltrim($relative, '/');
}

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

if ($assessment_id <= 0) {
  header('Location: /elms/student/assessments/index.php');
  exit;
}

/* Student */
$studentCols = "id, full_name, academic_email, center_reg_no, reference_no, lms_status";
if (table_exists($mysqli, 'studentss') && col_exists($mysqli, 'studentss', 'course_id')) {
  $studentCols .= ", course_id";
}

$st = $mysqli->prepare("SELECT $studentCols FROM studentss WHERE id=? LIMIT 1");
$st->bind_param('i', $student_id);
$st->execute();
$student = $st->get_result()->fetch_assoc();
$st->close();

if (!$student) {
  session_destroy();
  header('Location: /elms/student/login.php');
  exit;
}

$_SESSION['student_name']   = $student['full_name'] ?? ($_SESSION['student_name'] ?? 'Student');
$_SESSION['academic_email'] = $student['academic_email'] ?? ($_SESSION['academic_email'] ?? '');
$_SESSION['center_reg_no']  = $student['center_reg_no'] ?? ($_SESSION['center_reg_no'] ?? '');

$lms_status = strtolower(trim((string)($student['lms_status'] ?? 'active')));

if (in_array($lms_status, ['inactive', 'suspended'], true)) {
  session_destroy();
  header('Location: /elms/student/login.php');
  exit;
}

/* Detect assessment table */
$assessmentTable = null;

foreach (['lms_assessments', 'assessments', 'assignments', 'course_assessments'] as $tbl) {
  if (table_exists($mysqli, $tbl)) {
    $assessmentTable = $tbl;
    break;
  }
}

if (!$assessmentTable) {
  http_response_code(404);
  exit('Assessments table not found');
}

$aIdCol     = col_exists($mysqli, $assessmentTable, 'id') ? 'id' : 'assessment_id';
$aTitleCol  = col_exists($mysqli, $assessmentTable, 'title') ? 'title' : (col_exists($mysqli, $assessmentTable, 'name') ? 'name' : $aIdCol);
$aMaxCol    = col_exists($mysqli, $assessmentTable, 'max_mark') ? 'max_mark' : (col_exists($mysqli, $assessmentTable, 'max_marks') ? 'max_marks' : (col_exists($mysqli, $assessmentTable, 'marks') ? 'marks' : null));
$aDueCol    = col_exists($mysqli, $assessmentTable, 'due_at') ? 'due_at' : (col_exists($mysqli, $assessmentTable, 'due_date') ? 'due_date' : (col_exists($mysqli, $assessmentTable, 'deadline') ? 'deadline' : null));
$aBriefCol  = col_exists($mysqli, $assessmentTable, 'brief') ? 'brief' : (col_exists($mysqli, $assessmentTable, 'instructions') ? 'instructions' : (col_exists($mysqli, $assessmentTable, 'description') ? 'description' : null));
$aModuleCol = col_exists($mysqli, $assessmentTable, 'module_id') ? 'module_id' : null;
$aCourseCol = col_exists($mysqli, $assessmentTable, 'course_id') ? 'course_id' : null;
$aActiveCol = col_exists($mysqli, $assessmentTable, 'active') ? 'active' : (col_exists($mysqli, $assessmentTable, 'is_active') ? 'is_active' : null);

/* Fetch assessment */
$select = [];
$select[] = "`$aIdCol` AS id";
$select[] = "`$aTitleCol` AS title";
$select[] = $aMaxCol ? "`$aMaxCol` AS max_marks" : "100 AS max_marks";
$select[] = $aDueCol ? "`$aDueCol` AS due_at" : "NULL AS due_at";
$select[] = $aBriefCol ? "`$aBriefCol` AS brief" : "'' AS brief";
$select[] = $aModuleCol ? "`$aModuleCol` AS module_id" : "0 AS module_id";
$select[] = $aCourseCol ? "`$aCourseCol` AS course_id" : "0 AS course_id";

$where = "`$aIdCol` = ?";
if ($aActiveCol) {
  $where .= " AND (`$aActiveCol` IS NULL OR `$aActiveCol` IN (1,'1','active','Active','ACTIVE','yes','YES'))";
}

$sql = "SELECT " . implode(', ', $select) . " FROM `$assessmentTable` WHERE $where LIMIT 1";
$st = $mysqli->prepare($sql);
$st->bind_param('i', $assessment_id);
$st->execute();
$assessment = $st->get_result()->fetch_assoc();
$st->close();

if (!$assessment) {
  http_response_code(404);
  exit('Assessment not found');
}

/* Ensure submissions table */
$mysqli->query("
CREATE TABLE IF NOT EXISTS `lms_assessment_submissions` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `assessment_id` INT UNSIGNED NOT NULL,
  `student_id` INT UNSIGNED NOT NULL,
  `file_path` VARCHAR(500) NULL,
  `original_name` VARCHAR(255) NULL,
  `student_note` TEXT NULL,
  `status` VARCHAR(50) NOT NULL DEFAULT 'submitted',
  `marks` DECIMAL(10,2) NULL,
  `feedback` TEXT NULL,
  `submitted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_assessment_student` (`assessment_id`, `student_id`),
  KEY `idx_student` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* Existing submission */
$submission = null;
$st = $mysqli->prepare("
  SELECT *
  FROM lms_assessment_submissions
  WHERE assessment_id = ?
    AND student_id = ?
  ORDER BY id DESC
  LIMIT 1
");
$st->bind_param('ii', $assessment_id, $student_id);
$st->execute();
$submission = $st->get_result()->fetch_assoc();
$st->close();

/* Submit upload */
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $note = trim((string)($_POST['student_note'] ?? ''));

  $hasNewFile = !empty($_FILES['submission_file']['name']) && is_uploaded_file($_FILES['submission_file']['tmp_name']);

  if (!$hasNewFile && !$submission) {
    flash('err', 'Please upload your submission file.');
    header("Location: submit.php?assessment_id={$assessment_id}");
    exit;
  }

  $filePath = $submission['file_path'] ?? null;
  $originalName = $submission['original_name'] ?? null;

  if ($hasNewFile) {
    $allowed = ['pdf','doc','docx','ppt','pptx','xls','xlsx','zip','rar','png','jpg','jpeg','txt','csv'];
    $maxMb = 50;

    $originalName = $_FILES['submission_file']['name'];
    $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
      flash('err', 'Invalid file type. Allowed: PDF, Word, PPT, Excel, ZIP, images.');
      header("Location: submit.php?assessment_id={$assessment_id}");
      exit;
    }

    if ((int)$_FILES['submission_file']['size'] > ($maxMb * 1024 * 1024)) {
      flash('err', "File too large. Maximum {$maxMb}MB allowed.");
      header("Location: submit.php?assessment_id={$assessment_id}");
      exit;
    }

    $uploadDir = dirname(__DIR__, 2) . '/uploads/submissions';
    if (!is_dir($uploadDir)) {
      @mkdir($uploadDir, 0775, true);
    }

    $safeName = date('Ymd_His') . '_A' . $assessment_id . '_S' . $student_id . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $dest = rtrim($uploadDir, '/\\') . DIRECTORY_SEPARATOR . clean_file_name($safeName);

    if (!move_uploaded_file($_FILES['submission_file']['tmp_name'], $dest)) {
      flash('err', 'Upload failed. Please try again.');
      header("Location: submit.php?assessment_id={$assessment_id}");
      exit;
    }

    $filePath = 'uploads/submissions/' . basename($dest);
  }

  if ($submission) {
    $sid = (int)$submission['id'];

    $st = $mysqli->prepare("
      UPDATE lms_assessment_submissions
      SET file_path = ?,
          original_name = ?,
          student_note = ?,
          status = 'submitted',
          submitted_at = NOW()
      WHERE id = ?
        AND student_id = ?
    ");
    $st->bind_param('sssii', $filePath, $originalName, $note, $sid, $student_id);
    $st->execute();
    $st->close();

    flash('ok', 'Submission updated successfully.');
  } else {
    $st = $mysqli->prepare("
      INSERT INTO lms_assessment_submissions
        (assessment_id, student_id, file_path, original_name, student_note, status, submitted_at)
      VALUES
        (?, ?, ?, ?, ?, 'submitted', NOW())
    ");
    $st->bind_param('iisss', $assessment_id, $student_id, $filePath, $originalName, $note);
    $st->execute();
    $st->close();

    flash('ok', 'Submission uploaded successfully.');
  }

  header("Location: submit.php?assessment_id={$assessment_id}");
  exit;
}

/* Refresh submission after POST */
$submission = null;
$st = $mysqli->prepare("
  SELECT *
  FROM lms_assessment_submissions
  WHERE assessment_id = ?
    AND student_id = ?
  ORDER BY id DESC
  LIMIT 1
");
$st->bind_param('ii', $assessment_id, $student_id);
$st->execute();
$submission = $st->get_result()->fetch_assoc();
$st->close();

$dueText = $assessment['due_at'] ? date('Y-m-d H:i', strtotime((string)$assessment['due_at'])) : 'No due date';
$isOverdue = false;

if (!empty($assessment['due_at'])) {
  $isOverdue = strtotime((string)$assessment['due_at']) < time();
}

$PAGE_TITLE = 'Submit Assessment';
$ACTIVE_MENU = 'assessments';
require_once __DIR__ . '/../studentlayout_top.php';
?>

<div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3 mb-4">
  <div>
    <h2 class="section-title mb-1"><?= h($assessment['title'] ?? 'Assessment') ?></h2>
    <div class="text-muted small">
      Max Marks: <?= h($assessment['max_marks'] ?? '100') ?>
      · Due: <?= h($dueText) ?>
    </div>
  </div>

  <div class="d-flex gap-2">
    <a href="/elms/student/assessments/brief.php?assessment_id=<?= (int)$assessment_id ?>"
       class="btn btn-outline-secondary btn-sm rounded-pill">
      <i class="bi bi-file-earmark-text me-1"></i> Brief
    </a>

    <a href="/elms/student/assessments/index.php"
       class="btn btn-outline-secondary btn-sm rounded-pill">
      <i class="bi bi-arrow-left me-1"></i> Back
    </a>
  </div>
</div>

<?php if ($msg = flash('ok')): ?>
  <div class="alert alert-success"><?= h($msg) ?></div>
<?php endif; ?>

<?php if ($msg = flash('err')): ?>
  <div class="alert alert-danger"><?= h($msg) ?></div>
<?php endif; ?>

<?php if ($isOverdue && !$submission): ?>
  <div class="alert alert-warning">
    <i class="bi bi-exclamation-triangle me-1"></i>
    This assessment due date has passed. Submission may be marked as late.
  </div>
<?php endif; ?>

<div class="row g-4">

  <div class="col-xl-7">
    <div class="card soft-card">
      <div class="card-body p-4">
        <h3 class="section-title mb-3">
          <?= $submission ? 'Update Submission' : 'Upload Submission' ?>
        </h3>

        <form method="post" enctype="multipart/form-data">
          <input type="hidden" name="assessment_id" value="<?= (int)$assessment_id ?>">

          <div class="mb-3">
            <label class="form-label fw-bold">Submission File</label>
            <input type="file" name="submission_file" class="form-control">
            <div class="form-text">
              Allowed: PDF, Word, PPT, Excel, ZIP, images. Maximum 50MB.
              <?php if ($submission): ?>
                Leave empty if you only want to update your note.
              <?php endif; ?>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label fw-bold">Student Note / Comment</label>
            <textarea name="student_note" rows="4" class="form-control"
                      placeholder="Write any note for your lecturer..."><?= h($submission['student_note'] ?? '') ?></textarea>
          </div>

          <button class="btn btn-primary rounded-pill">
            <i class="bi bi-upload me-1"></i>
            <?= $submission ? 'Update Submission' : 'Submit Assessment' ?>
          </button>
        </form>
      </div>
    </div>
  </div>

  <div class="col-xl-5">

    <div class="card soft-card mb-4">
      <div class="card-body p-4">
        <h3 class="section-title mb-3">Assessment Brief</h3>

        <?php if (!empty($assessment['brief'])): ?>
          <div class="brief-box">
            <?= nl2br(h(strip_tags((string)$assessment['brief']))) ?>
          </div>
        <?php else: ?>
          <div class="text-muted">
            No text brief available. Use the Brief button to check attached files.
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="card soft-card">
      <div class="card-body p-4">
        <h3 class="section-title mb-3">Submission Status</h3>

        <?php if (!$submission): ?>
          <div class="status-box not-submitted">
            <i class="bi bi-clock-history fs-2 d-block mb-2"></i>
            <div class="fw-bold">Not Submitted</div>
            <div class="small">Upload your file before the due date.</div>
          </div>
        <?php else: ?>
          <div class="status-box submitted">
            <i class="bi bi-check-circle fs-2 d-block mb-2"></i>
            <div class="fw-bold">Submitted</div>
            <div class="small">
              <?= h(date('Y-m-d H:i', strtotime((string)$submission['submitted_at']))) ?>
            </div>
          </div>

          <div class="mt-3">
            <div class="small text-muted">File</div>
            <?php if (!empty($submission['file_path'])): ?>
              <a href="<?= h(public_file_url((string)$submission['file_path'])) ?>" target="_blank" class="fw-bold">
                <?= h($submission['original_name'] ?: basename((string)$submission['file_path'])) ?>
              </a>
            <?php else: ?>
              <div class="text-muted">No file attached.</div>
            <?php endif; ?>
          </div>

          <div class="mt-3">
            <div class="small text-muted">Marks</div>
            <div class="fw-bold">
              <?= $submission['marks'] !== null ? h($submission['marks']) : 'Pending' ?>
            </div>
          </div>

          <?php if (!empty($submission['feedback'])): ?>
            <div class="mt-3">
              <div class="small text-muted">Feedback</div>
              <div class="feedback-box">
                <?= nl2br(h((string)$submission['feedback'])) ?>
              </div>
            </div>
          <?php endif; ?>

        <?php endif; ?>
      </div>
    </div>

  </div>

</div>

<style>
  .brief-box{
    background:#f8fafc;
    border:1px solid rgba(15,23,42,.08);
    border-radius:18px;
    padding:16px;
    line-height:1.7;
    color:#334155;
  }

  .status-box{
    border-radius:18px;
    padding:22px;
    text-align:center;
  }

  .status-box.not-submitted{
    background:#fff7ed;
    color:#9a3412;
    border:1px solid #fed7aa;
  }

  .status-box.submitted{
    background:#ecfdf5;
    color:#047857;
    border:1px solid #a7f3d0;
  }

  .feedback-box{
    background:#f8fafc;
    border:1px solid rgba(15,23,42,.08);
    border-radius:14px;
    padding:12px;
    line-height:1.6;
  }
</style>

<?php require_once __DIR__ . '/../studentlayout_bottom.php'; ?>