<?php
// Printable Assessment Report (A4) – EDEN header + course/module resolver + single-tick award + Email/WhatsApp/PDF buttons
// /elms/lecturer/assessments/report.php
declare(strict_types=1);
@header('Content-Type: text/html; charset=utf-8');
if (session_status() === PHP_SESSION_NONE) session_start();
date_default_timezone_set('Asia/Colombo');

/* ---------- helpers ---------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
function table_exists(mysqli $db,string $t):bool{ $t=$db->real_escape_string($t); $r=$db->query("SHOW TABLES LIKE '$t'"); $ok=$r && $r->num_rows>0; if($r)$r->free(); return $ok; }
function col_exists(mysqli $db,string $t,string $c):bool{ $t=str_replace('`','``',$t); $c=$db->real_escape_string($c); $r=$db->query("SHOW COLUMNS FROM `$t` LIKE '$c'"); $ok=$r && $r->num_rows>0; if($r)$r->free(); return $ok; }
function get_int(...$keys):int{ foreach($keys as $k){ if(isset($_GET[$k]) && is_numeric($_GET[$k])) return (int)$_GET[$k]; } return 0; }

/* ---------- auth (soft; keep your ACLs) ---------- */
$role = strtolower((string)($_SESSION['user']['role'] ?? $_SESSION['role'] ?? ''));
if (!in_array($role, ['lecturer','course_coordinator','coordinator','admin','super_admin','branch_admin','student'], true)) {
  http_response_code(403); echo 'Forbidden'; exit;
}

/* ---------- DB ---------- */
$ROOT = rtrim($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__,2), '/');
$tried=[]; $try=function(string $p)use(&$tried){ $tried[]=$p; if(is_file($p)){ require_once $p; return true; } return false; };
$try($ROOT.'/elms/includes/db.php') || $try(__DIR__.'/../../includes/db.php') || $try(__DIR__.'/../includes/db.php');
if (!isset($mysqli) || !($mysqli instanceof mysqli)) { if (isset($conn) && $conn instanceof mysqli) $mysqli=$conn; }
if (!isset($mysqli) || !($mysqli instanceof mysqli)) { http_response_code(500); echo "<h3>DB not initialized</h3><pre>".esc(implode("\n",$tried))."</pre>"; exit; }
@$mysqli->set_charset('utf8mb4');

/* ---------- params ---------- */
$submissionId = get_int('id','sid','submission_id');

/* =========== PICKER when no id =========== */
if ($submissionId <= 0) {
  $studentTable = table_exists($mysqli,'studentss') ? 'studentss' : 'students';
  $stuNameCol   = col_exists($mysqli,$studentTable,'full_name') ? 'full_name' : (col_exists($mysqli,$studentTable,'name') ? 'name' : 'id');
  $assTitleCol  = col_exists($mysqli,'lms_assessments','title') ? 'title' : (col_exists($mysqli,'lms_assessments','name') ? 'name' : 'id');
  $rows=[];
  if (table_exists($mysqli,'lms_submissions')) {
    $sql="SELECT s.id, a.$assTitleCol AS atitle, st.$stuNameCol AS sname, s.submitted_at
          FROM lms_submissions s
          LEFT JOIN lms_assessments a ON a.id=s.assessment_id
          LEFT JOIN $studentTable st ON st.id=s.student_id
          ORDER BY s.id DESC LIMIT 40";
    if ($res=$mysqli->query($sql)) { while($r=$res->fetch_assoc()) $rows[]=$r; $res->free(); }
  } ?>
  <!doctype html>
  <meta charset="utf-8"><title>Assessment Report – Pick</title>
  <style>body{font:14px system-ui,Segoe UI,Arial;margin:20px}table{border-collapse:collapse;width:100%}th,td{border:1px solid #e5e7eb;padding:8px}th{background:#f3f4f6;text-align:left}a.btn{display:inline-block;padding:6px 10px;border:1px solid #444;text-decoration:none;margin-bottom:12px}</style>
  <a class="btn" href="javascript:history.back()">← Back</a>
  <h2>Pick a submission</h2>
  <?php if(!$rows): ?>
    <p>No submissions yet. Open from the Grading page or pass <code>?id=SUBMISSION_ID</code>.</p>
  <?php else: ?>
    <table>
      <thead><tr><th>ID</th><th>Assessment</th><th>Student</th><th>Submitted</th><th></th></tr></thead>
      <tbody><?php foreach($rows as $r): ?><tr>
        <td>#<?= (int)$r['id'] ?></td><td><?= esc($r['atitle'] ?? '') ?></td><td><?= esc($r['sname'] ?? '') ?></td><td><?= esc($r['submitted_at'] ?? '') ?></td>
        <td><a href="?id=<?= (int)$r['id'] ?>">Open</a></td></tr><?php endforeach; ?></tbody>
    </table>
  <?php endif; exit; }

/* ---------- load submission + joins ---------- */
$studentTable = table_exists($mysqli,'studentss') ? 'studentss' : 'students';
$assTitleCol  = col_exists($mysqli,'lms_assessments','title') ? 'title' : (col_exists($mysqli,'lms_assessments','name')?'name':'id');
$stuNameCol   = col_exists($mysqli,$studentTable,'full_name') ? 'full_name' : (col_exists($mysqli,$studentTable,'name') ? 'name' : 'id');

$sql="SELECT s.*, a.$assTitleCol AS assessment_title, a.id AS assessment_id,
             st.$stuNameCol AS student_name, st.id AS student_id,
             st.*
      FROM lms_submissions s
      JOIN lms_assessments a ON a.id=s.assessment_id
      JOIN $studentTable st ON st.id=s.student_id
      WHERE s.id=?";
$st=$mysqli->prepare($sql); $st->bind_param('i',$submissionId); $st->execute();
$sub=$st->get_result()->fetch_assoc(); $st->close();
if(!$sub){ echo 'Not found.'; exit; }

/* ---------- Course / Module resolution ---------- */
$courseName=''; $moduleName=''; $courseId=null; $moduleId=null;

/* ids in submission or assessment */
foreach(['course_id','courseID','cid'] as $k) if(isset($sub[$k]) && is_numeric($sub[$k])){$courseId=(int)$sub[$k];break;}
foreach(['module_id','course_module_id','mid'] as $k) if(isset($sub[$k]) && is_numeric($sub[$k])){$moduleId=(int)$sub[$k];break;}
if(!$courseId){
  $ra=$mysqli->query("SELECT * FROM lms_assessments WHERE id=".(int)$sub['assessment_id']); 
  if($ra && $aa=$ra->fetch_assoc()){ if(isset($aa['course_id'])) $courseId=(int)$aa['course_id']; if(isset($aa['module_id'])) $moduleId=(int)$aa['module_id']; }
  if($ra) $ra->free();
}

/* direct names in rows */
foreach(['course_name','course','programme','program'] as $k) if(!$courseName && !empty($sub[$k])) $courseName=(string)$sub[$k];
foreach(['module_name','module','subject','paper']      as $k) if(!$moduleName && !empty($sub[$k])) $moduleName=(string)$sub[$k];

/* map module -> course_id */
if(!$courseId && $moduleId){
  foreach(['lms_modules','modules','course_modules'] as $mt) if(table_exists($mysqli,$mt) && col_exists($mysqli,$mt,'id')){
    $cidCol = col_exists($mysqli,$mt,'course_id') ? 'course_id' : null;
    if($cidCol){
      $r=$mysqli->query("SELECT `$cidCol` AS cid FROM `$mt` WHERE id=".$moduleId);
      if($r && $x=$r->fetch_assoc()) $courseId = (int)$x['cid'];
      if($r) $r->free();
      if($courseId) break;
    }
  }
}

/* lookup course/module names */
if(!$courseName && $courseId){
  $pickCourseTbl = table_exists($mysqli,'courses') ? 'courses' : (table_exists($mysqli,'lms_courses') ? 'lms_courses' : null);
  if($pickCourseTbl){
    $nameCol = col_exists($mysqli,$pickCourseTbl,'name') ? 'name' : (col_exists($mysqli,$pickCourseTbl,'title') ? 'title' : (col_exists($mysqli,$pickCourseTbl,'full_name') ? 'full_name' : null));
    if($nameCol){
      $r=$mysqli->query("SELECT `$nameCol` AS nm FROM `$pickCourseTbl` WHERE id=".$courseId);
      if($r && $x=$r->fetch_assoc()) $courseName=(string)$x['nm'];
      if($r) $r->free();
    }
  }
}
if(!$moduleName && $moduleId){
  $pickModTbl = table_exists($mysqli,'lms_modules') ? 'lms_modules' : (table_exists($mysqli,'modules') ? 'modules' : (table_exists($mysqli,'course_modules') ? 'course_modules' : null));
  if($pickModTbl){
    $nameCol = col_exists($mysqli,$pickModTbl,'name') ? 'name' : (col_exists($mysqli,$pickModTbl,'title') ? 'title' : (col_exists($mysqli,$pickModTbl,'full_name') ? 'full_name' : null));
    if($nameCol){
      $r=$mysqli->query("SELECT `$nameCol` AS nm FROM `$pickModTbl` WHERE id=".$moduleId);
      if($r && $x=$r->fetch_assoc()) $moduleName=(string)$x['nm'];
      if($r) $r->free();
    }
  }
}

/* ---------- branch / batch / contact ---------- */
$branchStr=''; foreach(['branch_name','branch','centre_name','center'] as $c) if(!$branchStr && !empty($sub[$c])) $branchStr=(string)$sub[$c];
if (!$branchStr && isset($sub['branch_id'])) $branchStr='ID: '.$sub['branch_id'];
$batch = isset($sub['batch_id']) ? (string)$sub['batch_id'] : '';

$studentPhone=''; foreach(['whatsapp','phone','mobile','contact','tel'] as $pc) if(!$studentPhone && !empty($sub[$pc])) $studentPhone=preg_replace('/\D+/','',(string)$sub[$pc]);
$studentEmail=''; foreach(['email','student_email','email_address','mail'] as $ec) if(!$studentEmail && !empty($sub[$ec])) $studentEmail=(string)$sub[$ec];

/* ---------- marks & grade ---------- */
$C_TOTAL = col_exists($mysqli,'lms_submissions','total_marks')    ? 'total_marks'    : null;
$C_OBT   = col_exists($mysqli,'lms_submissions','obtained_marks') ? 'obtained_marks' : null;
$C_SCORE = col_exists($mysqli,'lms_submissions','final_score')    ? 'final_score' : (col_exists($mysqli,'lms_submissions','score') ? 'score' : null);
$C_GRADE = col_exists($mysqli,'lms_submissions','grade_letter')   ? 'grade_letter'   : null;

$tot = $C_TOTAL && isset($sub[$C_TOTAL]) ? (float)$sub[$C_TOTAL] : null;
$obt = $C_OBT   && isset($sub[$C_OBT])   ? (float)$sub[$C_OBT]   : null;

$pct = null;
if ($tot && $tot>0 && $obt!==null) $pct = 100.0*$obt/$tot;
elseif ($C_SCORE && isset($sub[$C_SCORE])) $pct = (float)$sub[$C_SCORE];

$grade = $C_GRADE && !empty($sub[$C_GRADE]) ? (string)$sub[$C_GRADE]
       : ($pct!==null ? ($pct>=80?'A':($pct>=65?'B':($pct>=50?'C':($pct>=40?'D':'F')))) : '—');

/* ---------- Criteria Template(s) ---------- */
$LOS=[];
if (table_exists($mysqli,'lms_assessment_criteria_sets') && col_exists($mysqli,'lms_assessment_criteria_sets','info_json')) {
  // assessment-level
  $st=$mysqli->prepare("SELECT info_json FROM lms_assessment_criteria_sets
                        WHERE template_type='assessment' AND assessment_id=? AND status='active'
                        ORDER BY id DESC LIMIT 1");
  $st->bind_param('i',$sub['assessment_id']); $st->execute();
  $row=$st->get_result()->fetch_assoc(); $st->close();

  // fallback: course-level
  if(!$row && $courseId){
    $st=$mysqli->prepare("SELECT info_json FROM lms_assessment_criteria_sets
                          WHERE template_type='course' AND course_id=? AND status='active'
                          ORDER BY id DESC LIMIT 1");
    $st->bind_param('i',$courseId); $st->execute(); $row=$st->get_result()->fetch_assoc(); $st->close();
  }
  // fallback: module-level
  if(!$row && $moduleId){
    $st=$mysqli->prepare("SELECT info_json FROM lms_assessment_criteria_sets
                          WHERE template_type='module' AND module_id=? AND status='active'
                          ORDER BY id DESC LIMIT 1");
    $st->bind_param('i',$moduleId); $st->execute(); $row=$st->get_result()->fetch_assoc(); $st->close();
  }

  if($row){
    $data=json_decode((string)$row['info_json'], true);
    if (is_array($data) && isset($data['los']) && is_array($data['los'])) {
      foreach($data['los'] as $i=>$lo){
        $code = $lo['code'] ?? ('LO'.($i+1));
        $text = $lo['text'] ?? '';
        $raw  = $lo['codes'] ?? ($lo['codes_csv'] ?? ($lo['codes_label'] ?? ($lo['codes_text'] ?? '')));
        if (is_array($raw))      $codes = implode(',', array_filter($raw));
        else {
          $m = preg_match_all('/[PMD]\d+/i', (string)$raw, $mm) ? array_map('strtoupper',$mm[0]) : [];
          $codes = implode(',', array_unique($m? $m : []));
        }
        $LOS[] = ['code'=>$code,'text'=>$text,'codes'=>$codes];
      }
    }
  }
}

/* ---------- award (single tick highest only) ---------- */
$award = ['P'=>false,'M'=>false,'D'=>false];
if ($pct !== null){
  if     ($pct >= 80) $award = ['P'=>false,'M'=>false,'D'=>true];
  elseif ($pct >= 65) $award = ['P'=>false,'M'=>true,'D'=>false];
  elseif ($pct >= 40) $award = ['P'=>true ,'M'=>false,'D'=>false];
}

/* ---------- share links ---------- */
$lecturerName = (string)($_SESSION['user']['name'] ?? $_SESSION['user']['full_name'] ?? 'Lecturer');
$today = date('Y-m-d');
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https' : 'http';
$baseUrl = $scheme.'://'.$_SERVER['HTTP_HOST'];
$viewUrl = $baseUrl.dirname($_SERVER['REQUEST_URI']).'/report.php?id='.$submissionId;
$pdfUrl  = $baseUrl.dirname($_SERVER['REQUEST_URI']).'/report.pdf.php?id='.$submissionId;

$waText = rawurlencode("Hi ".($sub['student_name'] ?? '').", here is your assessment report for \"".($sub['assessment_title'] ?? 'Assessment')."\".\nMarks: ".($obt!==null?$obt:'—')."/".($tot!==null?$tot:'—')." (".($pct!==null?round($pct):'—')."%, Grade $grade)\n$viewUrl");
$waHref = $studentPhone ? "https://wa.me/$studentPhone?text=$waText" : "https://wa.me/?text=$waText";

/* ---------- optional email send (fallback to PHP mail) ---------- */
$sentMsg='';
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['send_email'] ?? '')==='1') {
  // Try PHPMailer if present (vendor/autoload.php), else fallback to mail()
  $htmlSummary = "<div style='font:14px Arial;color:#111'>
  <h3 style='margin:0 0 8px'>Assessment Report</h3>
  <p><b>Student:</b> ".esc($sub['student_name'] ?? '')."<br>
     <b>Course:</b> ".esc($courseName ?: '-')."<br>
     <b>Module:</b> ".esc($moduleName ?: '-')."<br>
     <b>Assessment:</b> ".esc($sub['assessment_title'] ?? '')."</p>
  <p><b>Marks:</b> ".($obt!==null?esc((string)$obt):'—')."/".($tot!==null?esc((string)$tot):'—')." (".($pct!==null?round($pct,2).'%' :'—').") — Grade <b>".esc($grade)."</b></p>
  <p>View/Download: <a href=\"".esc($viewUrl)."\">".esc($viewUrl)."</a></p></div>";

  // Attach PDF if Dompdf is available by calling report.pdf.php and capturing bytes
  $pdfBytes = @file_get_contents($pdfUrl.'&as=bytes=1'); // if your server blocks, this will be empty; still OK

  if (is_file($ROOT.'/vendor/autoload.php')) {
    require_once $ROOT.'/vendor/autoload.php';
    if (class_exists('PHPMailer\PHPMailer\PHPMailer') && $studentEmail) {
      $mail = new PHPMailer\PHPMailer\PHPMailer(true);
      try {
        // If your server supports direct mail, leave SMTP off. If you want SMTP, uncomment and set creds.
        // $mail->isSMTP(); $mail->Host='smtp.example.com'; $mail->SMTPAuth=true; $mail->Username=''; $mail->Password=''; $mail->SMTPSecure=PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; $mail->Port=587;

        $mail->setFrom('no-reply@'.$_SERVER['HTTP_HOST'],'EdenCampus');
        $mail->addAddress($studentEmail, $sub['student_name'] ?? '');
        $mail->Subject = 'Assessment Report – '.($sub['assessment_title'] ?? 'Assessment');
        $mail->isHTML(true);
        $mail->Body = $htmlSummary;
        if ($pdfBytes) $mail->addStringAttachment($pdfBytes,'Assessment-Report.pdf','base64','application/pdf');
        $mail->send(); $sentMsg = 'Email sent to '.$studentEmail;
      } catch (Exception $e) { $sentMsg = 'Email failed: '.$mail->ErrorInfo; }
    } else { $sentMsg = 'PHPMailer not found or no student email.'; }
  } else {
    if ($studentEmail) {
      $headers="MIME-Version: 1.0\r\nContent-type: text/html; charset=UTF-8\r\nFrom: EdenCampus <no-reply@".$_SERVER['HTTP_HOST'].">\r\n";
      $ok=@mail($studentEmail,'Assessment Report – '.($sub['assessment_title'] ?? 'Assessment'),$htmlSummary,$headers);
      $sentMsg = $ok ? ('Email sent to '.$studentEmail) : 'Email sending failed (server mail not configured).';
    } else $sentMsg='No student email on record.';
  }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= esc($courseName ?: 'Assessment Report') ?> – <?= esc($sub['assessment_title'] ?? 'Assessment') ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  @page { size: A4; margin: 14mm; }
  body{font:13px/1.5 "Times New Roman", Georgia, serif; color:#111}
  table{border-collapse:collapse; width:100%}
  th, td{border:1px solid #000; padding:6px}
  .grid2{display:grid; grid-template-columns:1fr 1fr; gap:10px}
  .box{border:1px solid #000; border-top:0}
  .center{text-align:center}
  .small{font-size:12px}
  .btn{display:inline-block; padding:6px 10px; border:1px solid #444; margin:6px 6px 12px 0; text-decoration:none; color:#111; background:#f4f4f4}
  .note{margin:6px 0 10px; color:#065f46; background:#ecfdf5; border:1px solid #a7f3d0; padding:8px 10px}
  .masthead{display:flex; align-items:center; gap:12px; margin-bottom:8px}
  .brand-logo{width:78px;height:auto}
  .brand-text{flex:1}
  .brand-title{font-size:20px; font-weight:800; letter-spacing:.3px}
  .brand-sub{font-size:14px; margin-top:2px}
  .brand-course{font-size:15px; font-weight:700; margin-top:2px}
  @media print {.btn,.note{display:none}}
</style>
</head>
<body>

<a class="btn" href="<?= esc($pdfUrl) ?>">⬇ Download PDF</a>
<a class="btn" href="javascript:window.print()">🖨️ Print</a>
<?php if($studentEmail): ?>
<form method="post" style="display:inline">
  <input type="hidden" name="send_email" value="1">
  <button class="btn" type="submit">✉️ Email to <?= esc($studentEmail) ?></button>
</form>
<?php endif; ?>
<a class="btn" target="_blank" href="<?= esc($waHref) ?>">🟢 WhatsApp</a>
<a class="btn" href="grade.php?id=<?= (int)$submissionId ?>">← Back</a>
<?php if($sentMsg): ?><div class="note"><?= esc($sentMsg) ?></div><?php endif; ?>

<!-- Masthead with EDEN logo -->
<div class="masthead">
  <img class="brand-logo" src="/elms/includes/logo/edden_logo.jpg" alt="EDEN CAMPUS" onerror="this.style.display='none'">
  <div class="brand-text">
    <div class="brand-title">EDEN CAMPUS</div>
    <div class="brand-sub">Assessment Report</div>
    <div class="brand-course"><?= esc($courseName ?: '—') ?></div>
    <div class="small"><?= 'Assignment – '.esc($sub['assessment_title'] ?? 'Assessment') ?></div>
  </div>
</div>

<table>
  <tr><th style="width:160px">Student Name</th><td><?= esc($sub['student_name'] ?? '') ?></td></tr>
  <tr><th>Student ID</th><td><?= esc((string)($sub['student_id'] ?? '')) ?></td></tr>
  <tr><th>Course</th><td><?= esc($courseName ?: '—') ?></td></tr>
  <tr><th>Module</th><td><?= esc($moduleName ?: '—') ?></td></tr>
  <tr><th>Branch</th><td><?= esc($branchStr ?: '—') ?></td></tr>
  <tr><th>Batch No</th><td><?= esc($batch ?: '—') ?></td></tr>
  <tr><th>Lecturer</th><td><?= esc($lecturerName) ?></td></tr>
  <tr><th>Date Submitted</th><td><?= esc($sub['submitted_at'] ?? '') ?></td></tr>
</table>

<div class="box">
  <table>
    <tr>
      <th style="width:55%">List which assessment criteria the Lecturer has awarded.<br>
        <span class="small">(To be filled by the Lecturer)</span></th>
      <th class="center" style="width:15%">Pass</th>
      <th class="center" style="width:15%">Merit</th>
      <th class="center" style="width:15%">Distinction</th>
    </tr>
    <tr>
      <td>Overall Award</td>
      <td class="center"><?= $award['P'] ? '✓' : '' ?></td>
      <td class="center"><?= $award['M'] ? '✓' : '' ?></td>
      <td class="center"><?= $award['D'] ? '✓' : '' ?></td>
    </tr>
  </table>
</div>

<?php if (!empty($LOS)): ?>
  <div class="box" style="margin-top:8px">
    <table>
      <tr><th style="width:10%">LO</th><th>Covered Assessment Criteria</th><th style="width:28%">Codes (P/M/D)</th></tr>
      <?php foreach($LOS as $lo): ?>
        <tr>
          <th><?= esc($lo['code']) ?>:</th>
          <td><?= esc($lo['text']) ?></td>
          <td><?= esc($lo['codes'] ?: '—') ?></td>
        </tr>
      <?php endforeach; ?>
    </table>
  </div>
<?php endif; ?>

<div class="grid2" style="margin-top:8px">
  <table>
    <tr><th class="center" colspan="2">Marks Summary</th></tr>
    <tr><th>Total Marks</th><td><?= $tot!==null ? esc((string)$tot) : '—' ?></td></tr>
    <tr><th>Obtained Marks</th><td><?= $obt!==null ? esc((string)$obt) : '—' ?></td></tr>
    <tr><th>Percentage</th><td><?= $pct!==null ? round($pct,2).'%' : '—' ?></td></tr>
    <tr><th>Grade</th><td><?= esc($grade) ?></td></tr>
  </table>

  <table>
    <tr><th class="center" colspan="2">Signatures</th></tr>
    <tr><th style="width:40%">Lecturer signature</th><td>&nbsp;</td></tr>
    <tr><th>Student Signature</th><td>&nbsp;</td></tr>
    <tr><th>Date</th><td><?= esc($today) ?></td></tr>
  </table>
</div>

<p class="small" style="margin-top:6px">Generated by EdenCampus ELMS · <?= esc(date('Y-m-d H:i')) ?></p>
</body>
</html>
