<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="wrapper">
        <div class="content"></div>
        <div class="text-center mx-auto mb-4" style="max-width: 700px;">
            <h2 class="text-dark" style="font-family: Arial, sans-serif;">Report Card Management</h2>
        </div>

        <div class="row g-2 align-items-center justify-content-center mb-3">
            <div class="col-auto"><label for="schoolYearSelect" class="col-form-label">School year</label></div>
            <div class="col-auto">
                <select id="schoolYearSelect" class="form-select form-select-sm" style="min-width: 200px;"></select>
            </div>
            <div class="col-auto"><label for="semesterSelect" class="col-form-label">Semester</label></div>
            <div class="col-auto">
                <select id="semesterSelect" class="form-select form-select-sm" style="min-width: 160px;"></select>
            </div>
            <div class="col-auto"><label for="reportDate" class="col-form-label">Report Date</label></div>
            <div class="col-auto">
                <input type="date" id="reportDate" class="form-control form-control-sm" style="min-width: 170px;" />
            </div>
        </div>

        <form id="classForm" class="mb-3" onsubmit="return false;">
            <div class="row align-items-end justify-content-center g-2">
                <div class="col-md-4 mb-2">
                    <label for="class_section_id">Select Class Section</label>
                    <select class="form-control" id="class_section_id"></select>
                </div>
                <div class="col-md-4 d-flex gap-2 mb-2 justify-content-center">
                    <button type="button" class="btn btn-primary" id="viewClassBtn">View All Reports</button>
                    <a href="#" class="btn btn-secondary external-link" id="printClassBtn" target="_blank">Print</a>
                    <a id="downloadClassBtn" href="#" class="btn btn-success external-link" target="_blank">Download</a>
                </div>
            </div>
        </form>

        <form id="studentForm" class="mb-3" onsubmit="return false;">
            <div class="row align-items-end justify-content-center g-2">
                <div class="col-md-4 mb-2">
                    <label for="student_id">Select Student</label>
                    <select class="form-control" id="student_id"></select>
                </div>
                <div class="col-md-4 d-flex gap-2 mb-2 justify-content-center">
                    <button type="button" class="btn btn-primary" id="viewStudentBtn">View Report</button>
                    <a href="#" class="btn btn-secondary external-link" id="printStudentBtn" target="_blank">Print</a>
                    <a id="downloadStudentBtn" href="#" class="btn btn-success external-link" target="_blank">Download</a>
                </div>
            </div>
            <div class="text-muted small text-center" id="ackStatus"></div>
        </form>

        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between">
                    <div>
                        <h5 class="mb-1">Report Card Completeness</h5>
                        <div class="text-muted small">Check grades, comments, and final scores for the selected class.</div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-primary btn-sm" id="checkCompletenessBtn">Check Completeness</button>
                    </div>
                </div>
                <div id="completenessStatus" class="text-muted small mt-2"></div>
                <div id="completenessSummary" class="mt-2"></div>
                <div id="completenessTableWrap" class="table-responsive mt-3" hidden>
                    <table class="table table-sm table-bordered align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 28%;">Student</th>
                                <th style="width: 15%;">Status</th>
                                <th>Missing</th>
                                <th>Warnings</th>
                                <th style="width: 16%;">Viewed</th>
                                <th style="width: 16%;">Signed</th>
                            </tr>
                        </thead>
                        <tbody id="completenessBody"></tbody>
                    </table>
                </div>
            </div>
        </div>

        <iframe id="studentReportFrame" style="width:100%; height:600px; border:1px solid #ccc;" hidden></iframe>
        <iframe id="classReportFrame" style="width:100%; height:600px; border:1px solid #ccc;" hidden></iframe>
    </div>
</div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const API = <?= json_encode(site_url('api/printables/report-card/meta')) ?>;
  const COMPLETENESS_API = <?= json_encode(site_url('api/printables/report-card/completeness')) ?>;
  const ACK_API = <?= json_encode(site_url('api/printables/report-card/ack')) ?>;

  // add cache-busting cb param
  const withCB = (u) => u + (u.includes('?') ? '&' : '?') + 'cb=' + Date.now();

  const urlStudent = (id, y, s, d=false, rd=null) =>
    withCB(`<?= site_url('report-card/student') ?>/${encodeURIComponent(id)}?school_year=${encodeURIComponent(y)}${s?('&semester='+encodeURIComponent(s)) : ''}${d?'&download=1':''}${rd?('&report_date='+encodeURIComponent(rd)) : ''}`);

  const urlClass   = (cid, y, s, d=false, rd=null) =>
    withCB(`<?= site_url('report-card/class') ?>/${encodeURIComponent(cid)}?school_year=${encodeURIComponent(y)}${s?('&semester='+encodeURIComponent(s)) : ''}${d?'&download=1':''}${rd?('&report_date='+encodeURIComponent(rd)) : ''}`);

  const $year   = document.getElementById('schoolYearSelect');
  const $student= document.getElementById('student_id');
  const $class  = document.getElementById('class_section_id');
  const $sem    = document.getElementById('semesterSelect');
  const $rdate  = document.getElementById('reportDate');
  const $viewS  = document.getElementById('viewStudentBtn');
  const $viewC  = document.getElementById('viewClassBtn');
  const $printS = document.getElementById('printStudentBtn');
  const $dlS    = document.getElementById('downloadStudentBtn');
  const $printC = document.getElementById('printClassBtn');
  const $dlC    = document.getElementById('downloadClassBtn');
  const $iframeS= document.getElementById('studentReportFrame');
  const $iframeC= document.getElementById('classReportFrame');
  const $checkCompleteness = document.getElementById('checkCompletenessBtn');
  const $completenessStatus = document.getElementById('completenessStatus');
  const $completenessSummary = document.getElementById('completenessSummary');
  const $completenessWrap = document.getElementById('completenessTableWrap');
  const $completenessBody = document.getElementById('completenessBody');
  const $ackStatus = document.getElementById('ackStatus');

  function opt(el, val, label) {
    const o = document.createElement('option'); o.value = String(val); o.textContent = label; el.appendChild(o);
  }

  async function loadMeta(year=null, sem=null){
    let url = year ? (API + '?school_year=' + encodeURIComponent(year)) : API;
    if (sem) url += (url.indexOf('?')>-1?'&':'?') + 'semester=' + encodeURIComponent(sem);
    const res = await fetch(url, { credentials: 'same-origin' });
    const data = await res.json();
    if (!res.ok || data?.ok === false) throw new Error('Failed to load data');

    // Years
    $year.innerHTML = '';
    (data.schoolYears || []).forEach(y => opt($year, y, y));
    if (data.selectedYear) $year.value = data.selectedYear;

    // Semesters
    $sem.innerHTML = '';
    (data.semesters || []).forEach(s => opt($sem, s, s));
    if (data.selectedSemester) $sem.value = data.selectedSemester;

    // Students
    $student.innerHTML = '';
    const students = (data.students || []);
    if (students.length === 0) {
      opt($student, '', 'No students found');
    } else {
      students.forEach(s => {
        const classLabel = (s.class_section_name || '').trim();
        const suffix = classLabel ? ` — ${classLabel}` : '';
        opt($student, s.id, `${s.firstname} ${s.lastname}${suffix}`);
      });
    }

    // Classes
    $class.innerHTML = '';
    (data.classSections || []).forEach(c => opt($class, c.class_section_id || c.id, c.class_section_name));

    updateAckStatus();
  }

  async function updateAckStatus() {
    if (! $ackStatus) return;
    const sid = $student.value;
    const y = $year.value || '';
    const s = $sem.value || '';
    if (!sid) {
      $ackStatus.textContent = '';
      return;
    }
    try {
      const url = `${ACK_API}?student_id=${encodeURIComponent(sid)}&school_year=${encodeURIComponent(y)}&semester=${encodeURIComponent(s)}`;
      const res = await fetch(url, { credentials: 'same-origin' });
      const data = await res.json();
      if (!res.ok || data?.ok === false) {
        $ackStatus.textContent = 'Parent acknowledgement: unavailable';
        return;
      }
      const viewed = data.viewed_at ? `Viewed: ${data.viewed_at}` : 'Viewed: not yet';
      const signed = data.signed_at
        ? `Signed: ${data.signed_at} (${data.signed_name || 'name missing'})`
        : 'Signed: not yet';
      $ackStatus.textContent = `Parent acknowledgement — ${viewed} · ${signed}`;
    } catch (err) {
      $ackStatus.textContent = 'Parent acknowledgement: unavailable';
    }
  }

  $year.addEventListener('change', function(){ loadMeta(this.value, $sem.value).catch(console.error); });
  $sem.addEventListener('change', function(){ loadMeta($year.value, this.value).catch(console.error); });
  $student.addEventListener('change', function(){ updateAckStatus(); });

  $viewS.addEventListener('click', function(){
    const sid = $student.value; const y = $year.value; const s=$sem.value;
    const rd = $rdate.value;
    if (!sid || !y) return;
    $iframeS.removeAttribute('hidden');
    $iframeS.src = urlStudent(sid, y, s, false, rd);
  });

  $viewC.addEventListener('click', function(){
    const cid = $class.value; const y = $year.value; const s=$sem.value;
    const rd = $rdate.value;
    if (!cid || !y) return;
    $iframeC.removeAttribute('hidden');
    $iframeC.src = urlClass(cid, y, s, false, rd);
  });

  const openExternal = (el, href) => {
    if (!href) return;
    el.href = href;
    el.setAttribute('target', '_blank');
    window.open(href, '_blank', 'noopener');
  };

  $printS.addEventListener('click', function(e){
    e.preventDefault();
    const sid=$student.value, y=$year.value, s=$sem.value;
    const rd = $rdate.value;
    if(!sid||!y) return;
    openExternal(this, urlStudent(sid,y,s,false,rd));
  });

  $dlS.addEventListener('click', function(e){
    e.preventDefault();
    const sid=$student.value, y=$year.value, s=$sem.value;
    const rd = $rdate.value;
    if(!sid||!y) return;
    openExternal(this, urlStudent(sid,y,s,true,rd));
  });

  $printC.addEventListener('click', function(e){
    e.preventDefault();
    const cid=$class.value, y=$year.value, s=$sem.value;
    const rd = $rdate.value;
    if(!cid||!y) return;
    openExternal(this, urlClass(cid,y,s,false,rd));
  });

  $dlC.addEventListener('click', function(e){
    e.preventDefault();
    const cid=$class.value, y=$year.value, s=$sem.value;
    const rd = $rdate.value;
    if(!cid||!y) return;
    openExternal(this, urlClass(cid,y,s,true,rd));
  });

  const setCompletenessStatus = (msg, isError=false) => {
    $completenessStatus.textContent = msg || '';
    $completenessStatus.classList.toggle('text-danger', !!isError);
  };

  const renderCompleteness = (data) => {
    const students = Array.isArray(data?.students) ? data.students : [];
    $completenessBody.innerHTML = '';
    if (students.length === 0) {
      $completenessWrap.hidden = true;
      $completenessSummary.textContent = 'No students found for the selected class.';
      return;
    }

    const summary = data?.summary || {};
    const total = summary.total ?? students.length;
    const complete = summary.complete ?? 0;
    const incomplete = summary.incomplete ?? (total - complete);
    const warnings = summary.warnings ?? 0;
    const note = data?.used_fallback ? ' (roster uses year-only assignments)' : '';
    $completenessSummary.textContent = `Complete: ${complete}/${total} | Incomplete: ${incomplete} | With warnings: ${warnings}${note}`;

    students.forEach((row) => {
      const missing = Array.isArray(row.missing) ? row.missing : [];
      const warningsList = Array.isArray(row.warnings) ? row.warnings : [];
      const isComplete = !!row.complete;
      const status = isComplete ? (warningsList.length ? 'Complete (warnings)' : 'Complete') : 'Missing data';
      const tr = document.createElement('tr');
      if (!isComplete) tr.classList.add('table-warning');
      const tdName = document.createElement('td');
      tdName.textContent = row.name || 'N/A';
      const tdStatus = document.createElement('td');
      tdStatus.textContent = status;
      const tdMissing = document.createElement('td');
      tdMissing.textContent = missing.length ? missing.join(', ') : 'None';
      const tdWarnings = document.createElement('td');
      tdWarnings.textContent = warningsList.length ? warningsList.join(', ') : 'None';
      const tdViewed = document.createElement('td');
      tdViewed.textContent = row.viewed_at ? row.viewed_at : 'Not viewed';
      const tdSigned = document.createElement('td');
      tdSigned.textContent = row.signed_at
        ? `${row.signed_at}${row.signed_name ? ` (${row.signed_name})` : ''}`
        : 'Not signed';
      tr.appendChild(tdName);
      tr.appendChild(tdStatus);
      tr.appendChild(tdMissing);
      tr.appendChild(tdWarnings);
      tr.appendChild(tdViewed);
      tr.appendChild(tdSigned);
      $completenessBody.appendChild(tr);
    });
    $completenessWrap.hidden = false;
  };

  $checkCompleteness.addEventListener('click', async function(){
    const cid = $class.value;
    const y = $year.value;
    const s = $sem.value;
    if (!cid || !y) {
      setCompletenessStatus('Select a class and school year first.', true);
      return;
    }
    setCompletenessStatus('Checking completeness...');
    $completenessSummary.textContent = '';
    $completenessWrap.hidden = true;
    $completenessBody.innerHTML = '';
    try {
      const url = withCB(`${COMPLETENESS_API}?class_section_id=${encodeURIComponent(cid)}&school_year=${encodeURIComponent(y)}${s?('&semester='+encodeURIComponent(s)) : ''}`);
      const res = await fetch(url, { credentials: 'same-origin' });
      const data = await res.json();
      if (!res.ok || data?.ok === false) {
        throw new Error(data?.message || 'Failed to load completeness report.');
      }
      setCompletenessStatus('');
      renderCompleteness(data);
    } catch (err) {
      setCompletenessStatus(err?.message || 'Failed to load completeness report.', true);
    }
  });

  // Default report date to today unless already set
  if (!$rdate.value) {
    const today = new Date();
    const pad = (n) => String(n).padStart(2,'0');
    $rdate.value = `${today.getFullYear()}-${pad(today.getMonth()+1)}-${pad(today.getDate())}`;
  }

  loadMeta('<?= esc($schoolYear ?? '') ?>','<?= esc($semester ?? '') ?>').catch(console.error);
});
</script>
<?= $this->endSection() ?>
