<?php
require_once '../../config/config.php';

$assignmentId = isset($_GET['assignment_id']) ? (int)$_GET['assignment_id'] : 0;
if ($assignmentId <= 0) { http_response_code(400); echo 'Invalid assignment_id'; exit; }

// Get latest approved submission for this assignment
$sql = "SELECT qss.id, qss.template_json
        FROM qp_setter_submissions qss
        WHERE qss.assignment_id = ?
        ORDER BY qss.id DESC LIMIT 1";
$st = $pdo->prepare($sql); $st->execute([$assignmentId]);
$row = $st->fetch(PDO::FETCH_ASSOC);
if(!$row){ echo '<h3>No submission found for this assignment.</h3>'; exit; }

$tplRaw = (string)($row['template_json'] ?? '');
$tplDecoded = html_entity_decode($tplRaw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$tpl = json_decode($tplDecoded, true);
if (json_last_error() !== JSON_ERROR_NONE) { echo '<h3>Invalid submission data.</h3>'; exit; }

// Normalize to sections array like master-qp-setter-submissions-view.php
$sections = [];
if (is_array($tpl)) {
    // Case 1: already an array of sections
    $isAssoc = fn($arr)=> array_keys($arr)!==range(0,count($arr)-1);
    if (!empty($tpl) && isset($tpl[0]) && (is_array($tpl[0]) || is_object($tpl[0]))) {
        $sections = $tpl;
    } elseif (isset($tpl['sections']) && is_array($tpl['sections'])) {
        $sections = $tpl['sections'];
    }
}

// Load dynamic header details (subject/course/college/exam)
$h = null;
try {
  // Preferred: resolve by assignment's exam_subject_id
  $sqlH = "SELECT 
            e.exam_name, e.academic_year, e.semester, subj.sem_type,
            subj.subject_code, subj.subject_name, subj.semester AS subject_semester,
            crs.course_name,
            col.college_name, col.address, col.location
          FROM qp_setter_assignments qps
          LEFT JOIN exam_subjects es ON qps.exam_subject_id = es.exam_subject_id
          LEFT JOIN subjects subj ON es.subject_id = subj.subject_id
          LEFT JOIN courses crs ON subj.course_id = crs.course_id
          LEFT JOIN exams e ON COALESCE(es.exam_id, qps.exam_id) = e.exam_id
          LEFT JOIN colleges col ON crs.college_id = col.college_id
          WHERE qps.id = ? LIMIT 1";
  $p = $pdo->prepare($sqlH); $p->execute([$assignmentId]); $h = $p->fetch(PDO::FETCH_ASSOC);
  if (!$h || empty($h['subject_code'])) {
    // Fallback via pattern -> subject
    $sqlH = "SELECT 
              e.exam_name, e.academic_year, e.semester, subj.sem_type,
              subj.subject_code, subj.subject_name, subj.semester AS subject_semester,
              crs.course_name,
              col.college_name, col.address, col.location
            FROM qp_setter_assignments qps
            LEFT JOIN question_patterns qp ON qps.pattern_id = qp.pattern_id
            LEFT JOIN subjects subj ON qp.subject_id = subj.subject_id
            LEFT JOIN courses crs ON subj.course_id = crs.course_id
            LEFT JOIN colleges col ON crs.college_id = col.college_id
            LEFT JOIN exams e ON qps.exam_id = e.exam_id
            WHERE qps.id = ? LIMIT 1";
    $p = $pdo->prepare($sqlH); $p->execute([$assignmentId]); $h = $p->fetch(PDO::FETCH_ASSOC);
  }
  if (!$h || empty($h['subject_code'])) {
    // Fallback through question_paper_orders using staff setter
      $sqlH = "SELECT e.exam_name, e.academic_year, e.semester, subj.sem_type, subj.subject_code, subj.subject_name, subj.semester AS subject_semester,
                    crs.course_name, col.college_name, col.address, col.location
             FROM qp_setter_assignments qps
             LEFT JOIN question_paper_orders qpo ON qpo.setter_id = qps.staff_id
             LEFT JOIN exam_subjects es ON qpo.exam_subject_id = es.exam_subject_id
             LEFT JOIN subjects subj ON es.subject_id = subj.subject_id
             LEFT JOIN courses crs ON subj.course_id = crs.course_id
             LEFT JOIN exams e ON es.exam_id = e.exam_id
             LEFT JOIN colleges col ON crs.college_id = col.college_id
             WHERE qps.id = ? LIMIT 1";
    $p = $pdo->prepare($sqlH); $p->execute([$assignmentId]); $h = $p->fetch(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) { $h = null; }

function toRomanLocal($num){
  $map = ['M'=>1000,'CM'=>900,'D'=>500,'CD'=>400,'C'=>100,'XC'=>90,'L'=>50,'XL'=>40,'X'=>10,'IX'=>9,'V'=>5,'IV'=>4,'I'=>1];
  $res=''; foreach($map as $r=>$v){ while($num >= $v){ $res.=$r; $num-=$v; } } return $res?:'';
}

function toUpperLocal($str){
  $s = trim((string)$str);
  if ($s === '') return '';
  return function_exists('mb_strtoupper') ? mb_strtoupper($s, 'UTF-8') : strtoupper($s);
}

$header = [
  'college_name' => $h['college_name'] ?? 'M.I.E.T. ENGINEERING COLLEGE',
  'address' => $h['address'] ?? '',
  'location' => $h['location'] ?? '',
  'academic_year' => $h['academic_year'] ?? '',
  'semester_num' => (int)($h['subject_semester'] ?? ($h['semester'] ?? 0)),
  'sem_type' => $h['sem_type'] ?? '',
  'course_name' => $h['course_name'] ?? '',
  'subject_code' => $h['subject_code'] ?? '',
  'subject_name' => $h['subject_name'] ?? ''
];
$header['semester_roman'] = $header['semester_num'] ? toRomanLocal($header['semester_num']) : '';

// Process sections dynamically - use actual section names and question numbers
$processedSections = [];
$partA = [];
$partB = [];

foreach ($sections as $sec) {
  $qs = isset($sec['questions']) && is_array($sec['questions']) ? $sec['questions'] : [];
  if (empty($qs)) continue;
  
  $sectionName = isset($sec['section_name']) ? $sec['section_name'] : 'Section';
  $sectionQuestions = [];
  
  foreach ($qs as $q) {
    $qNo = isset($q['question_no']) ? $q['question_no'] : '';
    $sectionQuestions[] = $q;
    
    // Try to extract numeric part for Part A/B classification
    if (preg_match('/^(\d+)/', $qNo, $matches)) {
      $num = (int)$matches[1];
      if ($num >= 1 && $num <= 6) {
        $partA[$qNo] = $q;
      } elseif ($num >= 7 && $num <= 9) {
        $partB[$qNo] = $q;
      }
    }
  }
  
  if (!empty($sectionQuestions)) {
    $processedSections[] = [
      'name' => $sectionName,
      'questions' => $sectionQuestions
    ];
  }
}

// If no Part A/B classification worked, use first section as Part A and second as Part B
if (empty($partA) && empty($partB) && !empty($processedSections)) {
  foreach ($processedSections as $idx => $sec) {
    if ($idx === 0) { // First section as Part A
      foreach ($sec['questions'] as $i => $q) {
        $partA[$i+1] = $q;
      }
    } elseif ($idx === 1) { // Second section as Part B
      foreach ($sec['questions'] as $i => $q) {
        $partB[$i+7] = $q;
      }
    }
  }
}

// Load marks per question for sections
$sectionMarks = [];
try {
  $ps = $pdo->prepare("SELECT ps.section_name, ps.marks_per_question, ps.num_questions, ps.section_total FROM pattern_sections ps JOIN qp_setter_assignments qps ON qps.pattern_id = ps.pattern_id WHERE qps.id = ?");
  $ps->execute([$assignmentId]);
  foreach ($ps->fetchAll(PDO::FETCH_ASSOC) as $r) {
    $nm = trim((string)($r['section_name'] ?? ''));
    if ($nm !== '') {
      $sectionMarks[$nm] = [
        'mpq' => (float)($r['marks_per_question'] ?? 0),
        'nq'  => (int)($r['num_questions'] ?? 0),
        'total' => (float)($r['section_total'] ?? 0)
      ];
    }
  }
} catch (Throwable $e) { $sectionMarks = []; }

// Build CO-BTL weightage matrix
function norm_btl($v){
  $s = strtolower(trim((string)$v));
  if ($s==='') return '';
  if (strpos($s,'remember')!==false) return 'Remembering';
  if (strpos($s,'understand')!==false) return 'Understanding';
  if (strpos($s,'apply')!==false) return 'Applying';
  if (strpos($s,'analy')!==false) return 'Analyzing';
  if (strpos($s,'evaluate')!==false) return 'Evaluating';
  if (strpos($s,'creat')!==false) return 'Creating';
  if (preg_match('/\bL?1\b/i',$s)) return 'Remembering';
  if (preg_match('/\bL?2\b/i',$s)) return 'Understanding';
  if (preg_match('/\bL?3\b/i',$s)) return 'Applying';
  if (preg_match('/\bL?4\b/i',$s)) return 'Analyzing';
  if (preg_match('/\bL?5\b/i',$s)) return 'Evaluating';
  if (preg_match('/\bL?6\b/i',$s)) return 'Creating';
  return ucfirst($s);
}
function base_qno($q){ $s=strtolower(trim((string)$q)); $p=explode('-', $s); return $p[0]??$s; }

$weight = [
  'Remembering'=>[1=>0,2=>0,3=>0,4=>0,5=>0],
  'Understanding'=>[1=>0,2=>0,3=>0,4=>0,5=>0],
  'Applying'=>[1=>0,2=>0,3=>0,4=>0,5=>0],
  'Analyzing'=>[1=>0,2=>0,3=>0,4=>0,5=>0],
  'Evaluating'=>[1=>0,2=>0,3=>0,4=>0,5=>0],
  'Creating'=>[1=>0,2=>0,3=>0,4=>0,5=>0],
];

foreach ($processedSections as $sec) {
  $secName = $sec['name'] ?? ($sec['section_name'] ?? '');
  $mpq = isset($sectionMarks[$secName]['mpq']) ? (float)$sectionMarks[$secName]['mpq'] : ( (isset($sectionMarks[$secName]) && is_numeric($sectionMarks[$secName])) ? (float)$sectionMarks[$secName] : 0.0 );
  if ($mpq <= 0) $mpq = 1.0;
  $seen = [];
  $qs = isset($sec['questions']) && is_array($sec['questions']) ? $sec['questions'] : [];
  foreach ($qs as $q) {
    $bq = base_qno($q['question_no'] ?? '');
    if (isset($seen[$bq])) continue; // count OR variants once
    $seen[$bq] = true;
    $coRaw = $q['co'] ?? ($q['co_codes'] ?? '');
    $btlRaw = $q['btl'] ?? ($q['cognitive_level'] ?? '');
    $btl = norm_btl($btlRaw);
    if ($btl === '') continue;
    $cos = [];
    if (is_string($coRaw) && preg_match_all('/CO\s*([1-5])|\b([1-5])\b/i', $coRaw, $m)) {
      foreach ($m[1] as $i=>$g1){ $n = $g1 !== '' ? $g1 : $m[2][$i]; if ($n !== '') $cos[(int)$n]=true; }
    }
    if (empty($cos)) $cos[1]=true;
    foreach (array_keys($cos) as $coNum) { if ($coNum>=1 && $coNum<=5) $weight[$btl][$coNum] += $mpq; }
  }
}

// Very simple renderer for print; adjust sections as needed
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Question Paper</title>
  <style>
    /* Use Times New Roman everywhere for print */
    body { font-family: "Times New Roman", Times, serif; color:#000; margin:10mm; }
    .page { width: 100%; page-break-inside: avoid; }
    .hdr { text-align:center; }
    .hdr h1 { font-size:14px; margin:0; font-family: "Times New Roman", Times, serif; }
    .hdr h2 { font-size:12px; margin:0; font-family: "Times New Roman", Times, serif; }
    .hdr-center { text-align:center; display:flex; flex-direction:column; gap:2px; font-family: "Times New Roman", Times, serif; }
    .hdr-center .line-main { font-size:14px; font-weight:700; letter-spacing:0.3px; }
    .hdr-center .line-sub { font-size:12px; font-weight:700; }
    .hdr-center .line-small { font-size:12px; }
    .hdr-center .line-note { font-size:11px; font-style:italic; }
    .meta-grid { display:grid; grid-template-columns:1fr 1fr; gap:4px 12px; font-size:11px; margin-top:6px; }
    .tbl { width:100%; border-collapse:collapse; font-size:11px; page-break-inside: auto; font-family: "Times New Roman", Times, serif; }
    .tbl th, .tbl td { border:1px solid #000; padding:4px; vertical-align:top; }
    .tbl tr { page-break-inside: avoid; }
    .part-title { text-align:center; font-weight:700; font-size:11px; margin:8px 0 4px; page-break-after: avoid; }
    .note { text-align:center; font-size:10px; color:#a00; }
    .or { text-align:center; font-size:11px; }
    .grid { width:100%; border-collapse:collapse; font-size:11px; margin-top:20px; page-break-inside: auto; font-family: "Times New Roman", Times, serif; }
    .grid th, .grid td { border:1px solid #000; padding:4px; text-align:center; }
    .grid tr { page-break-inside: avoid; }
    .small { font-size:10px; }
    .weightage-title { text-align:center; font-weight:700; margin:20px 0 10px; page-break-before: auto; }
    .weightage-section { page-break-before: auto; }
    @media print { 
      .no-print { display:none; }
      body { margin: 5mm; }
      .page { page-break-inside: avoid; }
      .tbl { page-break-inside: auto; }
      .grid { page-break-inside: auto; }
    }
  </style>
</head>
<body>
  <div class="no-print" style="text-align:right; margin-bottom:8px;"><button onclick="window.print()">Print</button></div>
  <div class="page">
    <?php 
      // Dynamic branding similar to appointment order, with staff-college fallback
      $branding = null;
      try {
        $bq = $pdo->prepare("SELECT 
                                col.college_name, col.address, col.location, col.logo, col.seal,
                                c.logo AS staff_logo, c.seal AS staff_seal
                              FROM qp_setter_assignments qps
                              LEFT JOIN question_patterns qp ON qps.pattern_id = qp.pattern_id
                              LEFT JOIN exam_subjects es ON qp.exam_subject_id = es.exam_subject_id
                              LEFT JOIN subjects subj ON es.subject_id = subj.subject_id
                              LEFT JOIN courses crs ON subj.course_id = crs.course_id
                              LEFT JOIN colleges col ON crs.college_id = col.college_id
                              LEFT JOIN staff s ON qps.staff_id = s.staff_id
                              LEFT JOIN colleges c ON s.college_id = c.college_id
                              WHERE qps.id = ? LIMIT 1");
        $bq->execute([$assignmentId]);
        $branding = $bq->fetch(PDO::FETCH_ASSOC);
        if ($branding) {
          if (empty($branding['logo']) && !empty($branding['staff_logo'])) { $branding['logo'] = $branding['staff_logo']; }
          if (empty($branding['seal']) && !empty($branding['staff_seal'])) { $branding['seal'] = $branding['staff_seal']; }
        }
      } catch (Throwable $e) { $branding = null; }
      // Resolve asset PUBLIC URLs using BASE_URL, prefer data/college/, fallback to uploads/
      $logoPath = '';
      $sealPath = '';
      $publicBase = (defined('BASE_URL') ? rtrim(BASE_URL, '/').'/' : '../../');
      if (!empty($branding['logo'])) {
        $cand1 = realpath(__DIR__ . '../../data/college/' . $branding['logo']);
        $cand2 = realpath(__DIR__ . '/../../uploads/' . $branding['logo']);
        if ($cand1 && is_file($cand1)) { $logoPath = $publicBase . 'data/college/' . rawurlencode($branding['logo']); }
        elseif ($cand2 && is_file($cand2)) { $logoPath = $publicBase . 'uploads/' . rawurlencode($branding['logo']); }
        else { $logoPath = $publicBase . 'data/college/' . rawurlencode($branding['logo']); }
      }
      if (!empty($branding['seal'])) {
        $scand1 = realpath(__DIR__ . '/../../data/college/' . $branding['seal']);
        $scand2 = realpath(__DIR__ . '/../../uploads/' . $branding['seal']);
        if ($scand1 && is_file($scand1)) { $sealPath = $publicBase . 'data/college/' . rawurlencode($branding['seal']); }
        elseif ($scand2 && is_file($scand2)) { $sealPath = $publicBase . 'uploads/' . rawurlencode($branding['seal']); }
        else { $sealPath = $publicBase . 'data/college/' . rawurlencode($branding['seal']); }
      }
    ?>
    <div class="hdr" style="display:grid; grid-template-columns:70px 1fr 70px; align-items:center; gap:12px; border-bottom:1px solid #000; padding-bottom:6px; margin-bottom:8px;">
      <div style="display:flex; align-items:center; justify-content:center;">
        <?php if (!empty($logoPath)): ?>
        <img src="<?php echo $logoPath; ?>" alt="Logo" style="width:70px; height:70px; object-fit:contain;" onerror="this.style.display='none'">
        <?php else: ?>
        <div style="width:70px; height:70px; border:1px solid #ddd; color:#999; display:flex; align-items:center; justify-content:center; font-size:10px;">LOGO</div>
        <?php endif; ?>
      </div>
      <div class="hdr-center">
        <div class="line-main"><?php echo htmlspecialchars(toUpperLocal(($branding['college_name'] ?? '') ?: $header['college_name'])); ?></div>
        <div class="line-sub">(AUTONOMOUS)</div>
        <?php if (!empty($branding['address'])): ?><div class="line-small"><?php echo htmlspecialchars($branding['address']); ?></div><?php endif; ?>
        <?php if (!empty($branding['location'])): ?><div class="line-small"><?php echo htmlspecialchars($branding['location']); ?></div><?php endif; ?>
        <?php if ($examTitle = trim((string)($h['exam_name'] ?? ''))): ?><div class="line-small"><?php echo htmlspecialchars($examTitle); ?></div><?php endif; ?>
        <?php $acadLine = trim(($header['academic_year'] ?? '')) !== '' || trim(($header['sem_type'] ?? '')) !== '' ? trim(($header['academic_year'] ?? '')) . (trim(($header['academic_year'] ?? '')) !== '' && trim(($header['sem_type'] ?? '')) !== '' ? ' – ' : '') . trim(($header['sem_type'] ?? '')) . (trim(($header['sem_type'] ?? '')) !== '' ? ' Semester' : '') : ''; ?>
        <?php if ($acadLine !== ''): ?><div class="line-small"><?php echo htmlspecialchars($acadLine); ?></div><?php endif; ?>
        <?php if ($courseName = trim((string)($header['course_name'] ?? ''))): ?><div class="line-small"><?php echo htmlspecialchars($courseName); ?></div><?php endif; ?>
        <?php if ($semLine = ($header['semester_roman'] ? ($header['semester_roman'].' Semester') : '')): ?><div class="line-small"><?php echo htmlspecialchars($semLine); ?></div><?php endif; ?>
        <?php $subjectLine = trim(($header['subject_code'] ?? '')) !== '' || trim(($header['subject_name'] ?? '')) !== '' ? trim(($header['subject_code'] ?? '')) . (trim(($header['subject_code'] ?? '')) !== '' && trim(($header['subject_name'] ?? '')) !== '' ? ' - ' : '') . trim(($header['subject_name'] ?? '')) : ''; ?>
        <?php if ($subjectLine !== ''): ?><div class="line-small"><?php echo htmlspecialchars($subjectLine); ?></div><?php endif; ?>
        <div class="line-note">(Use of Charts/Tables is permitted)</div>
      </div>
       <div style="display:flex; align-items:center; justify-content:center;">
         <?php if (!empty($sealPath)): ?>
         <img src="<?php echo $sealPath; ?>" alt="Seal" style="width:70px; height:70px; object-fit:contain;" onerror="this.style.display='none'">
        <?php else: ?>
        <div style="width:70px; height:70px; border:1px solid #ddd; color:#999; display:flex; align-items:center; justify-content:center; font-size:10px;">SEAL</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Register number boxes moved to top-left with Times font -->
    <div style="display:flex; justify-content:flex-start; margin:4px 0 6px; font-family:'Times New Roman', Times, serif;">
      <div style="font-size:12px; margin-right:8px; align-self:center;">Reg. No.</div>
      <div aria-label="Register Number" role="group">
        <?php for($i=0;$i<10;$i++): ?>
          <span style="display:inline-block; width:14px; height:18px; border:1px solid #000; margin-left:2px; vertical-align:middle;"></span>
        <?php endfor; ?>
      </div>
    </div>

    <div class="meta-grid" style="margin:6px 0 8px;">
      <div>Date : ________</div>
      <div>Session : FN</div>
      <div>Time : 2 Hrs.</div>
      <div>Maximum Marks: 60</div>
    </div>

    <?php if (!empty($processedSections)): ?>
      <?php foreach ($processedSections as $section): ?>
        <?php 
          $secName = $section['name'] ?? '';
          $nq = isset($sectionMarks[$secName]['nq']) ? (int)$sectionMarks[$secName]['nq'] : 0;
          $mpq = isset($sectionMarks[$secName]['mpq']) ? (float)$sectionMarks[$secName]['mpq'] : 0.0;
          $stotal = isset($sectionMarks[$secName]['total']) ? (float)$sectionMarks[$secName]['total'] : (($nq&&$mpq)?($nq*$mpq):0);
        ?>
        <div class="part-title" style="position:relative;">
          <?php echo htmlspecialchars($secName); ?>
          <?php if ($nq || $mpq || $stotal): ?>
            <span style="position:absolute; right:0; top:0; font-weight:700; font-size:11px;">
              <?php echo ($nq?:''); ?><?php echo $nq? ' × ' : ''; ?><?php echo $mpq?:''; ?><?php echo ($nq&&$mpq)?' = ':''; ?><?php echo $stotal?:''; ?>
            </span>
          <?php endif; ?>
        </div>
        <table class="tbl">
          <thead><tr><th style="width:40px;">Q. No.</th><th>Questions</th><th style="width:40px;">CO</th><th style="width:40px;">BTL</th></tr></thead>
          <tbody>
            <?php 
              // Group by base question number to render OR variants together
              $groups = [];
              foreach (($section['questions'] ?? []) as $q) {
                $b = base_qno($q['question_no'] ?? '');
                if (!isset($groups[$b])) $groups[$b] = [];
                $groups[$b][] = $q;
              }
              foreach ($groups as $base => $items): 
                $first = $items[0];
                $coCell = (string)($first['co'] ?? ($first['co_codes'] ?? ''));
                $btlCell = (string)($first['btl'] ?? ($first['cognitive_level'] ?? ''));
            ?>
            <tr>
              <td><?php echo htmlspecialchars((string)$base); ?></td>
              <td>
                <?php if (count($items) > 1): ?>
                  <div>(a) <?php echo !empty($items[0]['question_text']) ? $items[0]['question_text'] : htmlspecialchars((string)($items[0]['text'] ?? '')); ?></div>
                  <div class="or">Or</div>
                  <div>(b) <?php echo !empty($items[1]['question_text']) ? $items[1]['question_text'] : htmlspecialchars((string)($items[1]['text'] ?? '')); ?></div>
                <?php else: ?>
                  <?php $q=$items[0]; echo !empty($q['question_text']) ? $q['question_text'] : htmlspecialchars((string)($q['text'] ?? '')); ?>
                <?php endif; ?>
              </td>
              <td><?php echo htmlspecialchars($coCell); ?></td>
              <td><?php echo htmlspecialchars($btlCell); ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endforeach; ?>
    <?php else: ?>
      <div class="part-title">Question Paper</div>
      <div class="small" style="text-align:center; margin-bottom:8px;">No structured sections found in submission.</div>
    <?php endif; ?>

    <div class="weightage-section">
      <div class="weightage-title">Weightage of CO</div>
      <table class="grid">
      <thead>
        <tr>
          <th>BTL</th><th>CO1</th><th>CO2</th><th>CO3</th><th>CO4</th><th>CO5</th><th>Total Marks</th><th>Total Marks (%)</th>
        </tr>
      </thead>
      <tbody>
        <?php 
          $btlOrder = ['Remembering','Understanding','Applying','Analyzing','Evaluating','Creating'];
          $btlLabels = [
            'Remembering'=>'Remember (L1)',
            'Understanding'=>'Understand (L2)',
            'Applying'=>'Apply (L3)',
            'Analyzing'=>'Analyze (L4)',
            'Evaluating'=>'Evaluate (L5)',
            'Creating'=>'Create (L6)'
          ];
          $grandTotal = 0;
          foreach ($btlOrder as $b) { 
            $co1 = $weight[$b][1]; $co2 = $weight[$b][2]; $co3 = $weight[$b][3]; $co4 = $weight[$b][4]; $co5 = $weight[$b][5];
            $rowTotal = $co1 + $co2 + $co3 + $co4 + $co5; $grandTotal += $rowTotal;
        ?>
        <tr>
          <td style="text-align:left;"><?php echo $btlLabels[$b]; ?></td>
          <td><?php echo $co1 ?: ''; ?></td>
          <td><?php echo $co2 ?: ''; ?></td>
          <td><?php echo $co3 ?: ''; ?></td>
          <td><?php echo $co4 ?: ''; ?></td>
          <td><?php echo $co5 ?: ''; ?></td>
          <td><?php echo $rowTotal ?: ''; ?></td>
          <td><?php echo $grandTotal > 0 ? round(($rowTotal/$grandTotal)*100) . '%' : ''; ?></td>
        </tr>
        <?php } ?>
        <tr>
          <td><strong>Total Marks</strong></td>
          <?php 
            $sum = [1=>0,2=>0,3=>0,4=>0,5=>0];
            foreach ($weight as $b=>$arr) { foreach ($arr as $co=>$v) { $sum[$co]+=$v; } }
            $sumTotal = $sum[1]+$sum[2]+$sum[3]+$sum[4]+$sum[5];
          ?>
          <td><strong><?php echo $sum[1] ?: ''; ?></strong></td>
          <td><strong><?php echo $sum[2] ?: ''; ?></strong></td>
          <td><strong><?php echo $sum[3] ?: ''; ?></strong></td>
          <td><strong><?php echo $sum[4] ?: ''; ?></strong></td>
          <td><strong><?php echo $sum[5] ?: ''; ?></strong></td>
          <td><strong><?php echo $sumTotal ?: ''; ?></strong></td>
          <td></td>
        </tr>
      </tbody>
      </table>
    </div>
  </div>
</body>
</html>


