<?php
/* ===================================================================
   /elms/student/assessments/submit.php
   - Students: ONE-TIME upload (no resubmissions)
   - Admin/Coordinator override via ?allowresubmit=1
   - File upload REQUIRED
   - Correct download URL (/elms/uploads/...)
   - Simple one-column UI
   =================================================================== */

/* ---- Force HTTPS before any output ---- */
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
  $host = $_SERVER['HTTP_HOST'] ?? 'admin.edencampus.lk';
  $uri  = $_SERVER['REQUEST_URI'] ?? '/';
  header('Location: https://' . $host . $uri, true, 301);
  exit;
}

/* ---- Errors: enable when debugging; keep 0 on prod ---- */
error_reporting(E_ALL);
ini_set('display_errors','0');

/* ---- Session ---- */
if (session_status() === PHP_SESSION_NONE) {
  @session_set_cookie_params(['path'=>'/','httponly'=>true,'samesite'=>'Lax','secure'=>true]);
  session_start();
}

/* ---- Minimal app URL helper (HTTPS + /elms prefix) ---- */
if (!function_exists('app_url')) {
  function app_url(string $path=''): string {
    $host = $_SERVER['HTTP_HOST'] ?? 'admin.edencampus.lk';
    $p = ($path !== '' && $path[0] !== '/') ? '/'.$path : $path;
    if (preg_match('~^https?://~i', $p)) return preg_replace('~^http://~i','https://',$p);
    return 'https://' . $host . '/elms' . $p;
  }
}

/* ---- Guard: allow student or admin roles ---- */
function ensure_student_or_admin(): void {
  $sid  = (int)($_SESSION['student_id'] ?? 0);
  $role = strtolower((string)($_SESSION['auth']['role'] ?? ($_SESSION['user']['role'] ?? ($_SESSION['role'] ?? ''))));
  if ($sid > 0 || in_array($role, ['student','super_admin','branch_admin','admin','coordinator','lecturer'], true)) return;
  $next = $_SERVER['REQUEST_URI'] ?? '/';
  header('Location: ' . app_url('/student/login.php?next=' . rawurlencode($next)));
  exit;
}
ensure_student_or_admin();

/* ---- DB + helpers ---- */
require_once __DIR__ . '/../../includes/db.php';
if (is_file(__DIR__ . '/../../includes/helpers.php')) require_once __DIR__ . '/../../includes/helpers.php';

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");
  $ok = $q && $q->num_rows>0; if ($q) $q->free(); return $ok;
}
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'"); $ok=$q && $q->num_rows>0; if($q)$q->free(); return $ok;
}
function fetch_one_assoc(mysqli_stmt $st): ?array {
  $row=null;
  if (method_exists($st,'get_result')) {
    $res=$st->get_result(); if($res){ $row=$res->fetch_assoc(); $res->free(); }
  } else {
    $meta=$st->result_metadata();
    if ($meta){
      $fields=$meta->fetch_fields(); $data=[]; $bind=[];
      foreach($fields as $f){ $data[$f->name]=null; $bind[]=&$data[$f->name]; }
      call_user_func_array([$st,'bind_result'],$bind);
      if ($st->fetch()) $row=$data;
    }
  }
  return $row;
}
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'] ?? 0);
$role          = strtolower((string)($_SESSION['auth']['role'] ?? ($_SESSION['user']['role'] ?? ($_SESSION['role'] ?? 'student'))));
$is_admin_like = in_array($role, ['super_admin','branch_admin','admin','coordinator','lecturer'], true);
$allow_resubmit_override = $is_admin_like && (($_GET['allowresubmit'] ?? '') === '1'); // Admin can enable per-URL

$assessment_id = filter_input(INPUT_GET,'assessment_id',FILTER_VALIDATE_INT) ?: 0;
$batch_id      = filter_input(INPUT_GET,'batch_id',FILTER_VALIDATE_INT) ?: 0;
$course_id     = filter_input(INPUT_GET,'course_id',FILTER_VALIDATE_INT) ?: 0;

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

/* ---- Fetch assessment ---- */
$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=fetch_one_assoc($st); $st->close();
} else {
  $sql = "SELECT 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
           WHERE a.id=? AND a.active=1
             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('i',$assessment_id);
  $st->execute(); $row=fetch_one_assoc($st); $st->close();
}
if (!$row) { http_response_code(404); die('Assessment not found or not available now.'); }

/* ---- Get previous submission (to enforce one-time rule) ---- */
$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=fetch_one_assoc($st); $st->close();
}
$already_submitted = !empty($prev);

/* ---- Can this user submit now? ----
   - Students: only if NEVER submitted before
   - Admin-like: can always submit/replace when ?allowresubmit=1 is present
*/
$can_submit_now = (!$already_submitted) || ($allow_resubmit_override);

/* ---- Handle submission (FILE REQUIRED) ---- */
$flash = '';
$flash_type = 'success';

if ($_SERVER['REQUEST_METHOD']==='POST') {
  if (!$can_submit_now) {
    // Student tried to resubmit without admin override
    http_response_code(403);
    $flash = 'Resubmission is disabled. Contact your coordinator to allow it.';
    $flash_type = 'danger';
  } elseif (!t_exists($mysqli,'lms_submissions')) {
    http_response_code(500);
    $flash = 'Server error: submissions table not found.';
    $flash_type = 'danger';
  } else {
    $content = trim((string)($_POST['content'] ?? ''));

    // required file validation
    $errors = [];
    if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
      $errors[] = 'Please attach a file.';
    } else {
      $f   = $_FILES['file'];
      $err = (int)($f['error'] ?? UPLOAD_ERR_NO_FILE);
      if ($err !== UPLOAD_ERR_OK) {
        $map = [
          UPLOAD_ERR_INI_SIZE=>'File too large (server limit).',
          UPLOAD_ERR_FORM_SIZE=>'File too large (form limit).',
          UPLOAD_ERR_PARTIAL=>'Upload was partial; try again.',
          UPLOAD_ERR_NO_FILE=>'No file uploaded; attach a file.',
          UPLOAD_ERR_NO_TMP_DIR=>'Server: missing temp folder.',
          UPLOAD_ERR_CANT_WRITE=>'Server: cannot write the file.',
          UPLOAD_ERR_EXTENSION=>'Upload blocked by a PHP extension.',
        ];
        $errors[] = 'Upload error: ' . ($map[$err] ?? ('Code '.$err));
      } else {
        $size = (int)($f['size'] ?? 0);
        if ($size < 1)            $errors[] = 'Empty file – attach a valid file.';
        if ($size > 25*1024*1024) $errors[] = 'File exceeds 25 MB limit.';
        $ext = strtolower(pathinfo((string)$f['name'], PATHINFO_EXTENSION));
        $allowed = ['pdf','doc','docx','ppt','pptx','xls','xlsx','txt','zip','rar','7z','jpg','jpeg','png','gif','mp4','avi','mkv'];
        if (!in_array($ext, $allowed, true)) $errors[] = 'File type not allowed.';
      }
    }

    if ($errors) {
      $flash = implode('<br>', array_map('esc', $errors));
      $flash_type = 'danger';
    } else {
      // save file to /elms/uploads/assessments
      $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']);
      $destAbs  = rtrim($dir,'/\\').'/'.$safeName;

      if (!move_uploaded_file($_FILES['file']['tmp_name'], $destAbs)) {
        $flash = 'Failed to save file on server.'; $flash_type = 'danger';
      } else {
        @chmod($destAbs, 0644);
        $fileRel = 'uploads/assessments/'.$safeName; // store RELATIVE path

        // Build column set dynamically (compatible with your schema)
        $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 (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');

        // Locate existing row (if any)
        $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();
          if (method_exists($chk,'get_result')) {
            $r=$chk->get_result(); $rowx=$r?$r->fetch_assoc():null; if($r)$r->free();
            $existingId = (int)($rowx['id'] ?? 0);
          } else {
            $idTmp=0; $chk->bind_result($idTmp); if($chk->fetch()) $existingId=(int)$idTmp;
          }
          $chk->close();
        }

        // Enforce one-time rule:
        if ($existingId && !$allow_resubmit_override) {
          // Student trying to replace: block
          $flash='Resubmission is disabled. Contact your coordinator to allow it.';
          $flash_type='danger';
          // Optionally remove the just-saved file to avoid orphan files
          @unlink($destAbs);
        } else {
          if ($existingId && $haveId) {
            // Admin override: update existing row in-place
            $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 replaced (admin override).'; $flash_type='success';
          } else {
            // First-time submission (or no row found)
            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.'; $flash_type='success';
            } else {
              $flash='Nothing to save (no compatible columns found in lms_submissions).'; $flash_type='danger';
            }
          }
        }
      }
    }
  }

  // Refresh previous row (in case it changed)
  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=fetch_one_assoc($st); $st->close();
    $already_submitted = !empty($prev);
  }
  // Recompute permission after POST
  $can_submit_now = (!$already_submitted) || ($allow_resubmit_override);
}

/* ---- Layout include ---- */
$top1 = __DIR__ . '/../studentlayout_top.php';
$bot1 = __DIR__ . '/../studentlayout_bottom.php';
$top2 = __DIR__ . '/../layout_top.php';
$bot2 = __DIR__ . '/../layout_bottom.php';
$top = is_file($top1) ? $top1 : $top2;
$bot = is_file($bot1) ? $bot1 : $bot2;

$PAGE_TITLE  = 'Submit';
$ACTIVE_MENU = 'assess';

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'>";
}
?>

<style>
/* ==== Clean single-column UI (scoped) ==== */
.subm{
  --ink:#0f172a; --muted:#65758a; --bg:#f6f8fb; --surface:#ffffff; --border:#e9eef5; --accent:#2563eb;
  color:var(--ink);
}
.subm .wrap{max-width:960px;margin:10px auto 24px}
.subm .panel{
  background:var(--surface); border:1px solid var(--border); border-radius:16px;
  box-shadow:0 10px 24px rgba(2,8,20,.05); padding:18px;
}
.subm .hero{margin-bottom:14px}
.subm h1{font-size:22px;font-weight:900;margin:0 0 6px}
.subm .chips{display:flex;flex-wrap:wrap;gap:8px}
.subm .chip{font-size:.83rem;border:1px solid var(--border);background:#fff;border-radius:999px;padding:6px 10px}
.subm .muted{color:var(--muted)}
.subm textarea, .subm input[type="file"]{
  width:100%;display:block;border:1px solid var(--border);border-radius:12px;background:#fff;padding:10px 12px;font:inherit
}
.subm textarea{min-height:140px;resize:vertical}
.subm .btn{
  display:inline-flex;align-items:center;gap:8px;border-radius:10px;border:1px solid transparent;
  padding:10px 14px;font-weight:700;cursor:pointer;text-decoration:none
}
.subm .btn-primary{background:var(--accent);color:#fff}
.subm .btn-ghost{background:#fff;border-color:var(--border);color:var(--ink)}
.subm .prev{
  background:#fafcff;border:1px dashed var(--border);border-radius:12px;padding:12px;margin-bottom:12px
}
</style>

<div class="subm">
  <div class="wrap">
    <!-- Header -->
    <div class="panel hero">
      <h1>Submit: <?= esc($row['title']) ?> <span class="muted">(<?= esc($row['type']) ?>)</span></h1>
      <div class="chips">
        <span class="chip">Total <strong><?= esc((string)$row['total_marks']) ?></strong></span>
        <?php if (!empty($row['open_at'])): ?><span class="chip">Open <?= esc($row['open_at']) ?></span><?php endif; ?>
        <?php if (!empty($row['close_at'])): ?><span class="chip">Close <?= esc($row['close_at']) ?></span><?php endif; ?>
        <?php if (!empty($row['due_at'])): ?><span class="chip">Due <?= esc($row['due_at']) ?></span><?php endif; ?>
      </div>
    </div>

    <?php if ($flash): ?>
      <div class="panel" style="margin-bottom:12px">
        <strong class="<?= $flash_type==='danger' ? 'text-danger' : 'text-success' ?>"><?= $flash ?></strong>
      </div>
    <?php endif; ?>

    <!-- Previous submission / control -->
    <div class="panel" style="margin-bottom:14px">
      <?php if ($prev): ?>
        <div class="prev">
          <div class="muted small 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'])):
              $p  = (string)$prev['file_path']; // e.g. 'uploads/assessments/xxx.docx'
              $dl = preg_match('~^https?://~i', $p) ? $p : app_url('/'.ltrim($p,'/'));
          ?>
            <a class="btn btn-ghost" target="_blank" href="<?= esc($dl) ?>" download>Download previous file</a>
          <?php endif; ?>
        </div>
      <?php else: ?>
        <div class="muted">No submission yet.</div>
      <?php endif; ?>

      <?php if ($already_submitted && !$allow_resubmit_override): ?>
        <div class="mt-2">
          <strong>Resubmission is disabled for students.</strong>
          <div class="muted small">If a correction is needed, please contact your coordinator.</div>
          <?php if ($is_admin_like): ?>
            <div class="mt-2">
              <a class="btn btn-ghost" href="<?= esc(app_url('/student/assessments/submit.php?assessment_id='.$assessment_id.($course_id?('&course_id='.(int)$course_id):'').($batch_id?('&batch_id='.(int)$batch_id):'').'&allowresubmit=1')) ?>">Enable resubmission (admin)</a>
            </div>
          <?php endif; ?>
        </div>
      <?php elseif ($allow_resubmit_override): ?>
        <div class="mt-2">
          <strong class="text-danger">Admin override active:</strong>
          <span class="muted small">New upload will replace the existing submission.</span>
        </div>
      <?php endif; ?>
    </div>

    <!-- Submission form -->
    <?php if ($can_submit_now): ?>
      <div class="panel">
        <?php if (!empty($row['description'])): ?>
          <div class="muted mb-3"><?= nl2br(esc((string)$row['description'])) ?></div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data" id="submissionForm">
          <label class="muted fw-bold">Answer / Notes (optional)</label>
          <textarea name="content" placeholder="Write your answer or attach a file…"></textarea>

          <div style="height:10px"></div>

          <!-- REQUIRED upload -->
          <label class="muted fw-bold">Attach file <span class="text-danger">*</span> (required)</label>
          <input type="file" name="file" id="fileInput" required />

          <div style="display:flex;gap:10px;margin-top:14px;align-items:center;flex-wrap:wrap">
            <button class="btn btn-primary" type="submit" id="submitBtn" disabled>Submit</button>
            <a class="btn btn-ghost" href="<?= esc(app_url('/student/assessments/index.php' . ($course_id?('?course_id='.(int)$course_id):''))) ?>">Back</a>
            <span class="muted" id="fileState">No file chosen.</span>
          </div>
          <div class="muted small mt-2">Allowed: pdf, doc(x), ppt(x), xls(x), txt, zip/rar/7z, jpg/png/gif, mp4/avi/mkv — Max 25 MB.</div>
        </form>
      </div>
    <?php endif; ?>
  </div>
</div>

<script>
(function(){
  const form  = document.getElementById('submissionForm');
  if (!form) return; // form hidden when already submitted
  const file  = document.getElementById('fileInput');
  const btn   = document.getElementById('submitBtn');
  const state = document.getElementById('fileState');

  function update(){
    if (!file.files || file.files.length === 0) {
      state && (state.textContent = 'No file chosen.');
      btn.disabled = true;
      btn.title = 'Attach a file to submit.';
    } else {
      const f = file.files[0];
      state && (state.textContent = 'Selected: ' + f.name + ' (' + new Intl.NumberFormat().format(f.size) + ' bytes)');
      btn.disabled = false;
      btn.title = '';
    }
  }
  update();
  file.addEventListener('change', update);

  // Hard guard: never submit without a file
  form.addEventListener('submit', function(e){
    if (!file.files || file.files.length === 0) {
      e.preventDefault();
      alert('Attach file is required.');
      file.focus();
    }
  });
})();
</script>

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