<?php
// /elms/student/assessments/submissions.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/submissions.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 public_file_url(?string $path): string {
  if (!$path) return '';

  $path = str_replace('\\', '/', trim($path));

  if ($path === '') return '';

  if (preg_match('#^https?://#i', $path)) {
    return $path;
  }

  if (str_starts_with($path, '/elms/')) {
    return $path;
  }

  if (str_starts_with($path, '/uploads/')) {
    return '/elms' . $path;
  }

  if (str_starts_with($path, 'uploads/')) {
    return '/elms/' . $path;
  }

  if (str_starts_with($path, '/')) {
    return $path;
  }

  return '/elms/uploads/submissions/' . ltrim($path, '/');
}

$student_id = (int)$_SESSION['student_id'];

/* 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;
}

/* Ensure submissions table exists */
$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;
");

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

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

$rows = [];

if ($assessmentTable) {
  $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));

  $select = "
    s.id AS submission_id,
    s.assessment_id,
    s.file_path,
    s.original_name,
    s.student_note,
    s.status,
    s.marks,
    s.feedback,
    s.submitted_at,
    a.`$aTitleCol` AS assessment_title
  ";

  $select .= $aMaxCol ? ", a.`$aMaxCol` AS max_marks" : ", 100 AS max_marks";
  $select .= $aDueCol ? ", a.`$aDueCol` AS due_at" : ", NULL AS due_at";

  $sql = "
    SELECT $select
    FROM lms_assessment_submissions s
    LEFT JOIN `$assessmentTable` a ON a.`$aIdCol` = s.assessment_id
    WHERE s.student_id = ?
    ORDER BY s.submitted_at DESC, s.id DESC
  ";

  $st = $mysqli->prepare($sql);
  $st->bind_param('i', $student_id);
  $st->execute();
  $rs = $st->get_result();

  while ($r = $rs->fetch_assoc()) {
    $rows[] = $r;
  }

  $st->close();
} else {
  $st = $mysqli->prepare("
    SELECT 
      s.id AS submission_id,
      s.assessment_id,
      s.file_path,
      s.original_name,
      s.student_note,
      s.status,
      s.marks,
      s.feedback,
      s.submitted_at,
      CONCAT('Assessment #', s.assessment_id) AS assessment_title,
      100 AS max_marks,
      NULL AS due_at
    FROM lms_assessment_submissions s
    WHERE s.student_id = ?
    ORDER BY s.submitted_at DESC, s.id DESC
  ");
  $st->bind_param('i', $student_id);
  $st->execute();
  $rs = $st->get_result();

  while ($r = $rs->fetch_assoc()) {
    $rows[] = $r;
  }

  $st->close();
}

$total = count($rows);
$marked = 0;
$pending = 0;

foreach ($rows as $r) {
  if ($r['marks'] !== null && $r['marks'] !== '') {
    $marked++;
  } else {
    $pending++;
  }
}

$PAGE_TITLE = 'My Submissions';
$ACTIVE_MENU = 'submissions';
require_once __DIR__ . '/../studentlayout_top.php';
?>

<div class="row g-4 mb-4">

  <div class="col-md-4">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-upload"></i>
        </div>
        <div>
          <div class="stat-label">Total Submissions</div>
          <div class="stat-value"><?= (int)$total ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-4">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-check-circle"></i>
        </div>
        <div>
          <div class="stat-label">Marked</div>
          <div class="stat-value"><?= (int)$marked ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-4">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-hourglass-split"></i>
        </div>
        <div>
          <div class="stat-label">Pending Marks</div>
          <div class="stat-value"><?= (int)$pending ?></div>
        </div>
      </div>
    </div>
  </div>

</div>

<div class="card soft-card">
  <div class="card-body p-4">

    <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">Submission History</h2>
        <div class="text-muted small">Your uploaded assessment files and results</div>
      </div>

      <a href="/elms/student/assessments/index.php" class="btn btn-primary btn-sm rounded-pill">
        <i class="bi bi-clipboard-check me-1"></i> Go to Assessments
      </a>
    </div>

    <?php if (!$rows): ?>

      <div class="text-center py-5">
        <i class="bi bi-inbox fs-1 text-muted d-block mb-3"></i>
        <h3 class="h5 fw-bold">No submissions yet</h3>
        <p class="text-muted mb-0">Submit your assessments to see them here.</p>
      </div>

    <?php else: ?>

      <div class="table-responsive">
        <table class="table align-middle submission-table">
          <thead>
            <tr>
              <th>Assessment</th>
              <th>File</th>
              <th>Submitted</th>
              <th>Status</th>
              <th>Marks</th>
              <th>Feedback</th>
              <th class="text-end">Action</th>
            </tr>
          </thead>

          <tbody>
            <?php foreach ($rows as $r): ?>
              <?php
                $fileUrl = public_file_url($r['file_path'] ?? '');
                $marks = $r['marks'];
                $isMarked = ($marks !== null && $marks !== '');
                $status = $isMarked ? 'Marked' : ($r['status'] ?: 'Submitted');
                $badgeClass = $isMarked ? 'badge-soft-green' : 'badge-soft-yellow';
              ?>

              <tr>
                <td>
                  <div class="fw-bold"><?= h($r['assessment_title'] ?? ('Assessment #' . $r['assessment_id'])) ?></div>
                  <div class="small text-muted">
                    Max <?= h($r['max_marks'] ?? '100') ?>
                    <?php if (!empty($r['due_at'])): ?>
                      · Due <?= h(date('Y-m-d H:i', strtotime((string)$r['due_at']))) ?>
                    <?php endif; ?>
                  </div>
                </td>

                <td>
                  <?php if ($fileUrl): ?>
                    <a href="<?= h($fileUrl) ?>" target="_blank" class="fw-semibold text-decoration-none">
                      <i class="bi bi-file-earmark-arrow-down me-1"></i>
                      <?= h($r['original_name'] ?: basename((string)$r['file_path'])) ?>
                    </a>
                  <?php else: ?>
                    <span class="text-muted">No file</span>
                  <?php endif; ?>
                </td>

                <td>
                  <?= !empty($r['submitted_at']) ? h(date('Y-m-d H:i', strtotime((string)$r['submitted_at']))) : '-' ?>
                </td>

                <td>
                  <span class="badge <?= h($badgeClass) ?> rounded-pill">
                    <?= h($status) ?>
                  </span>
                </td>

                <td>
                  <?php if ($isMarked): ?>
                    <span class="fw-bold"><?= h($marks) ?></span>
                    <span class="text-muted small">/ <?= h($r['max_marks'] ?? '100') ?></span>
                  <?php else: ?>
                    <span class="text-muted">Pending</span>
                  <?php endif; ?>
                </td>

                <td style="min-width:220px;">
                  <?php if (!empty($r['feedback'])): ?>
                    <div class="feedback-preview">
                      <?= h(mb_strimwidth(strip_tags((string)$r['feedback']), 0, 120, '...')) ?>
                    </div>
                  <?php else: ?>
                    <span class="text-muted">No feedback yet</span>
                  <?php endif; ?>
                </td>

                <td class="text-end">
                  <a href="/elms/student/assessments/submit.php?assessment_id=<?= (int)$r['assessment_id'] ?>"
                     class="btn btn-outline-primary btn-sm rounded-pill">
                    View
                  </a>
                </td>
              </tr>

            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

    <?php endif; ?>

  </div>
</div>

<style>
  .submission-table thead th{
    color:#64748b;
    font-size:12px;
    text-transform:uppercase;
    letter-spacing:.04em;
    border-bottom:1px solid rgba(15,23,42,.08);
  }

  .submission-table tbody td{
    padding-top:16px;
    padding-bottom:16px;
  }

  .feedback-preview{
    background:#f8fafc;
    border:1px solid rgba(15,23,42,.06);
    border-radius:12px;
    padding:10px;
    font-size:13px;
    color:#334155;
  }
</style>

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