<?php declare(strict_types=1);
/* Student → Assessments → Submit page (CSS-only redesign, logic unchanged)
 * Roles allowed: student, super_admin, branch_admin
 */

error_reporting(E_ALL); ini_set('display_errors','1');

require_once __DIR__ . '/../../includes/auth.php';   // unified session + auth helpers
ec_boot_session();                                   // ensure SAME session name as login
require_role(['student','super_admin','branch_admin']);

require_once __DIR__ . '/../../includes/db.php';
if (is_file(__DIR__ . '/../../includes/helpers.php')) require_once __DIR__ . '/../../includes/helpers.php';

/* ----------------- tiny local helpers ----------------- */
if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }
}
function t_exists(mysqli $db,string $t):bool{
  $t=$db->real_escape_string($t);
  $q=$db->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' LIMIT 1");
  return $q ? (bool)$q->num_rows : false;
}
function c_exists(mysqli $db,string $t,string $c):bool{
  $t=$db->real_escape_string($t); $c=$db->real_escape_string($c);
  $q=$db->query("SHOW COLUMNS FROM `$t` LIKE '$c'");
  return $q ? (bool)$q->num_rows : false;
}
function marks_expr(mysqli $db): string {
  $hasTotal = c_exists($db,'lms_assessments','total_marks');
  $hasMax   = c_exists($db,'lms_assessments','max_score');
  if ($hasTotal && $hasMax) return "COALESCE(a.total_marks,a.max_score,100)";
  if ($hasTotal)           return "COALESCE(a.total_marks,100)";
  if ($hasMax)             return "COALESCE(a.max_score,100)";
  return "100";
}

/* ----------------- inputs ----------------- */
$student_id    = (int)($_SESSION['student_id'] ?? ($_SESSION['auth']['id'] ?? 0));
$assessment_id = filter_input(INPUT_GET,'assessment_id',FILTER_VALIDATE_INT) ?: 0;
$batch_id      = filter_input(INPUT_GET,'batch_id',FILTER_VALIDATE_INT) ?: 0;

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

/* ----------------- fetch assessment row ----------------- */
$HAS_SESS   = t_exists($mysqli,'lms_assessment_sessions') &&
              c_exists($mysqli,'lms_assessment_sessions','open_at') &&
              c_exists($mysqli,'lms_assessment_sessions','close_at');
$MARKS_EXPR = marks_expr($mysqli);

$row = null;
if ($HAS_SESS && $batch_id>0) {
  $sql = "SELECT a.id AS assessment_id, a.title, a.type, a.description,
                 $MARKS_EXPR AS total_marks,
                 s.open_at, s.close_at,
                 a.due_at
            FROM lms_assessments a
            JOIN lms_assessment_sessions s ON s.assessment_id=a.id
           WHERE a.id=? AND s.batch_id=?
             AND (a.active=1)
             AND (s.open_at IS NULL OR s.open_at<=NOW())
             AND (s.close_at IS NULL OR s.close_at>=NOW())
           LIMIT 1";
  $st=$mysqli->prepare($sql);
  $st->bind_param('ii',$assessment_id,$batch_id);
  $st->execute(); $row=$st->get_result()->fetch_assoc(); $st->close();
} else {
  // fallback: mapping tables + available window
  $hasB = t_exists($mysqli,'lms_assessment_batches');
  $hasS = t_exists($mysqli,'lms_assessment_students');
  $join = '';
  $whereMap = '1=1';
  $types = 'i'; $vals = [$assessment_id];

  if ($hasB) { $join     .= " LEFT JOIN lms_assessment_batches  lab ON lab.assessment_id=a.id ";
              $whereMap  = "lab.batch_id=?"; $types.='i'; $vals[]=$batch_id; }
  if ($hasS && $student_id>0) {
    $join     .= " LEFT JOIN lms_assessment_students las ON las.assessment_id=a.id ";
    $whereMap  = "($whereMap OR las.student_id=".$student_id.")";
  }

  $sql = "SELECT DISTINCT a.id AS assessment_id, a.title, a.type, a.description,
                 $MARKS_EXPR AS total_marks,
                 a.available_from AS open_at,
                 a.available_to   AS close_at,
                 a.due_at
            FROM lms_assessments a
            $join
           WHERE a.id=? AND a.active=1 AND ($whereMap)
             AND (a.available_from IS NULL OR a.available_from<=NOW())
             AND (a.available_to   IS NULL OR a.available_to  >=NOW())
           LIMIT 1";

  $st=$mysqli->prepare($sql);
  $st->bind_param($types, ...$vals);
  $st->execute(); $row=$st->get_result()->fetch_assoc(); $st->close();
}

if (!$row) { http_response_code(404); die('Assessment not found or not available now.'); }

/* ----------------- handle submission ----------------- */
$flash = '';
if ($_SERVER['REQUEST_METHOD']==='POST' && t_exists($mysqli,'lms_submissions')) {
  $content = trim((string)($_POST['content'] ?? ''));
  $fileRel = null;

  if (!empty($_FILES['file']['name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
    $dir = dirname(__DIR__,2).'/uploads/assessments';
    if (!is_dir($dir)) @mkdir($dir, 0775, true);
    $safeName = time().'_'.preg_replace('/[^A-Za-z0-9._-]/','_', $_FILES['file']['name']);
    $dest = rtrim($dir,'/\\').'/'.$safeName;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
      $fileRel = 'uploads/assessments/'.$safeName;
    }
  }

  $cols = [];
  if (c_exists($mysqli,'lms_submissions','assessment_id')) $cols['assessment_id']=$assessment_id;
  if (c_exists($mysqli,'lms_submissions','student_id'))    $cols['student_id']=$student_id;
  if ($batch_id && c_exists($mysqli,'lms_submissions','batch_id')) $cols['batch_id']=$batch_id;
  if (c_exists($mysqli,'lms_submissions','content'))       $cols['content']=$content;
  if ($fileRel && c_exists($mysqli,'lms_submissions','file_path')) $cols['file_path']=$fileRel;
  if (c_exists($mysqli,'lms_submissions','submitted_at'))  $cols['submitted_at']=date('Y-m-d H:i:s');

  $haveId  = c_exists($mysqli,'lms_submissions','id');
  $canFind = c_exists($mysqli,'lms_submissions','assessment_id') && c_exists($mysqli,'lms_submissions','student_id');

  $existingId = 0;
  if ($canFind) {
    $chk=$mysqli->prepare("SELECT ".($haveId?'id':'1')." AS id FROM lms_submissions WHERE assessment_id=? AND student_id=? LIMIT 1");
    $chk->bind_param('ii',$assessment_id,$student_id);
    $chk->execute(); $r=$chk->get_result()->fetch_assoc(); $chk->close();
    $existingId = (int)($r['id'] ?? 0);
  }

  if ($existingId && $haveId) {
    $sets=[]; $types=''; $vals=[];
    foreach($cols as $k=>$v){ $sets[]="`$k`=?"; $types .= is_int($v)?'i':'s'; $vals[]=$v; }
    $types .= 'i'; $vals[] = $existingId;
    $sqlU = "UPDATE lms_submissions SET ".implode(',',$sets)." WHERE id=?";
    $st=$mysqli->prepare($sqlU); $st->bind_param($types, ...$vals); $st->execute(); $st->close();
    $flash='Submission updated.';
  } else {
    if ($cols){
      $fields = '`'.implode('`,`', array_keys($cols)).'`';
      $ph     = rtrim(str_repeat('?,', count($cols)),',');
      $types  = ''; foreach($cols as $v) $types .= (is_int($v)?'i':'s');
      $st=$mysqli->prepare("INSERT INTO lms_submissions ($fields) VALUES ($ph)");
      $st->bind_param($types, ...array_values($cols));
      $st->execute(); $st->close();
      $flash='Submitted successfully.';
    } else {
      $flash='Nothing to save (no compatible columns found in lms_submissions).';
    }
  }
}

/* ----------------- any previous submission ----------------- */
$prev = null;
if (t_exists($mysqli,'lms_submissions') && c_exists($mysqli,'lms_submissions','assessment_id') && c_exists($mysqli,'lms_submissions','student_id')) {
  $sel = "SELECT * FROM lms_submissions WHERE assessment_id=? AND student_id=? ORDER BY ".(c_exists($mysqli,'lms_submissions','submitted_at')?'submitted_at DESC':'id DESC')." LIMIT 1";
  $st=$mysqli->prepare($sel); $st->bind_param('ii',$assessment_id,$student_id); $st->execute();
  $prev=$st->get_result()->fetch_assoc(); $st->close();
}

/* ----------------- layout ----------------- */
$top = __DIR__ . '/../layout_top.php';
$bot = __DIR__ . '/../layout_bottom.php';
if (is_file($top)) require $top; else {
  echo "<!doctype html><meta charset='utf-8'><link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css'><div class='container py-3'>";
}
?>

<!-- ===== CSS-only redesign (wide screen, cleaner UI) ===== -->
<style>
  :root{
    --font: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Noto Sans", Arial, "Helvetica Neue", sans-serif;
    --ink:#0f172a; --muted:#64748b;
    --border:#e6eaf3; --surface:#fff; --surface-2:#f6f9ff;
    --accent:#2563eb; --accent-2:#0ea5e9; --danger:#ef4444;
    --shadow: 0 14px 36px rgba(2,6,23,.08);
    --radius:16px;
  }

  /* Wider content while keeping your left sidebar */
  .container, .container-fluid, .page, .page-body, .app-content{
    max-width: 1320px !important;
  }
  @media (min-width: 1600px){
    .container, .container-fluid, .page, .page-body, .app-content{
      max-width: 1460px !important;
    }
  }
  /* Ultra-wide option (uncomment if needed)
  @media (min-width: 1900px){
    .container, .container-fluid, .page, .page-body, .app-content{ max-width: 1640px !important; }
  } */

  body{ font-family:var(--font); color:var(--ink); background:#f4f7ff; }
  .text-muted,.small,.form-text{ color:var(--muted) !important; }

  /* Title */
  h1.h5{
    font-size: clamp(1.35rem, .9rem + 1vw, 1.6rem) !important;
    font-weight: 800; letter-spacing:.2px; margin-bottom: .9rem !important;
  }
  h1.h5 small{ font-weight:700; color:var(--muted); }

  /* Cards */
  .card{
    border:1px solid var(--border) !important;
    border-radius: var(--radius) !important;
    box-shadow: var(--shadow);
    overflow: hidden;
    background: var(--surface);
  }
  .card-header{
    background: linear-gradient(180deg,#ffffff, var(--surface-2)) !important;
    border-bottom:1px solid var(--border) !important;
    font-weight: 800;
  }
  .card-body{ padding: 1.25rem 1.25rem 1.15rem; }
  .row > [class*="col-"] > .card{ margin-bottom: 1.2rem; }

  /* Summary badges line */
  .card .small{ display:flex; flex-wrap:wrap; gap:.35rem; }
  .card .small .badge{ margin-right:.35rem; margin-bottom:.35rem; }

  /* Badges contrast */
  .badge{ border:1px solid transparent; font-weight:700; }
  .badge.bg-secondary{
    background:#eef2ff !important; color:#1e3a8a !important; border-color:#dbe4ff !important;
  }
  .badge.bg-info{
    background:#e7f3ff !important; color:#0b3a66 !important; border-color:#cfe7ff !important;
  }
  .badge.bg-danger{
    background:#fee2e2 !important; color:#7f1d1d !important; border-color:#fecaca !important;
  }

  /* Forms */
  .form-label{ font-weight:800; color:#0b1220; }
  .form-control{
    border:1px solid var(--border);
    border-radius:14px;
    background:#fff;
    padding:.72rem .9rem;
  }
  .form-control:focus{
    border-color:#bcd3ff;
    box-shadow: 0 0 0 .25rem rgba(37,99,235,.15);
  }
  textarea.form-control{ min-height: 220px; resize: vertical; }
  input[type="file"].form-control{ padding:.45rem .9rem; }

  /* Buttons */
  .btn{
    border-radius: 12px;
    font-weight: 800;
    letter-spacing:.2px;
  }
  .btn-primary{
    border:0;
    background: linear-gradient(90deg, var(--accent), var(--accent-2));
    box-shadow: 0 10px 22px rgba(37,99,235,.22);
  }
  .btn-primary:hover{ filter:brightness(1.05); }
  .btn-outline-secondary{
    border-color: var(--border) !important;
    background:#fff !important; color: var(--ink) !important;
  }
  .btn + .btn{ margin-left:.5rem; }

  @media (max-width: 768px){
    .card-body{ padding: 1rem; }
    textarea.form-control{ min-height: 180px; }
  }
</style>

<h1 class="h5 mb-3">
  Submit: <?= esc($row['title']) ?>
  <small class="text-muted">(<?= esc($row['type']) ?>)</small>
</h1>

<?php if (!empty($flash)): ?>
  <div class="alert alert-info py-2"><?= esc($flash) ?></div>
<?php endif; ?>

<div class="row">
  <div class="col-lg-7">
    <div class="card mb-3">
      <div class="card-body">
        <?php if (!empty($row['description'])): ?>
          <div class="mb-2"><?= nl2br(esc((string)$row['description'])) ?></div>
          <hr>
        <?php endif; ?>
        <div class="small">
          <span class="badge bg-secondary me-1">Total <?= esc((string)$row['total_marks']) ?></span>
          <?php if (!empty($row['open_at'])): ?>
            <span class="badge bg-info text-dark me-1">Open <?= esc($row['open_at']) ?></span>
          <?php endif; ?>
          <?php if (!empty($row['close_at'])): ?>
            <span class="badge bg-info text-dark me-1">Close <?= esc($row['close_at']) ?></span>
          <?php endif; ?>
          <?php if (!empty($row['due_at'])): ?>
            <span class="badge bg-danger">Due <?= esc($row['due_at']) ?></span>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-header">Your submission</div>
      <div class="card-body">
        <?php if ($prev): ?>
          <div class="alert alert-secondary">
            <div class="small text-muted mb-1">Last submitted <?= esc($prev['submitted_at'] ?? '') ?></div>
            <?php if (!empty($prev['content'])): ?>
              <div class="mb-2"><?= nl2br(esc((string)$prev['content'])) ?></div>
            <?php endif; ?>
            <?php if (!empty($prev['file_path'])): ?>
              <div><a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= esc((string)$prev['file_path']) ?>">Download file</a></div>
            <?php endif; ?>
          </div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data">
          <div class="mb-3">
            <label class="form-label">Answer / Notes (optional)</label>
            <textarea name="content" class="form-control" placeholder="Write your answer or attach a file…"></textarea>
          </div>
          <div class="mb-3">
            <label class="form-label">Attach file (optional)</label>
            <input type="file" name="file" class="form-control">
          </div>
          <button class="btn btn-primary">Submit</button>
          <a class="btn btn-outline-secondary" href="index.php?course_id=<?= isset($_GET['course_id'])?(int)$_GET['course_id']:0 ?>&batch_id=<?= (int)$batch_id ?>">Back</a>
        </form>
      </div>
    </div>
  </div>

  <div class="col-lg-5">
    <div class="card">
      <div class="card-header">Assessment Info</div>
      <div class="card-body">
        <dl class="row mb-0">
          <dt class="col-4">Type</dt><dd class="col-8"><?= esc($row['type']) ?></dd>
          <dt class="col-4">Total marks</dt><dd class="col-8"><?= esc((string)$row['total_marks']) ?></dd>
          <?php if (!empty($row['open_at'])): ?>
            <dt class="col-4">Open</dt><dd class="col-8"><?= esc($row['open_at']) ?></dd>
          <?php endif; ?>
          <?php if (!empty($row['close_at'])): ?>
            <dt class="col-4">Close</dt><dd class="col-8"><?= esc($row['close_at']) ?></dd>
          <?php endif; ?>
          <?php if (!empty($row['due_at'])): ?>
            <dt class="col-4">Due</dt><dd class="col-8"><?= esc($row['due_at']) ?></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>
  </div>
</div>

<?php if (is_file($bot)) require $bot; else echo '</div>'; ?>
