<?php
session_start();
require_once 'classes/Auth.php';
require_once 'classes/TranscriptModel.php';
require_once __DIR__ . '/phpqrcode/qrlib.php';
$auth = new Auth();
$currentUser = $auth->guard();
$tm = new TranscriptModel();
$admissionno = $_GET['admissionno'] ?? '';
$startYear = $_GET['start_year'] ?? '2021/2022';
$endYear = $_GET['end_year'] ?? '2024/2025';
$student = $results = null;
$qrWebPath = '';
if ($admissionno) {
    $student = $tm->getStudentByAdmissionNo($admissionno);
    $results = $tm->getTranscriptRecords($admissionno, $startYear, $endYear);
    if ($student && $results) {
        $createdBy = $currentUser['id'] ?? null;
        $token = $tm->getOrCreateVerificationToken($admissionno, $startYear, $endYear, $createdBy);
        $qrDirFs = __DIR__ . '/qrcodes/';
        if (!file_exists($qrDirFs)) mkdir($qrDirFs, 0777, true);
        $safeAdmissionNo = str_replace(['/', '\\', ' '], '_', $admissionno);
        $qrFilename = "{$safeAdmissionNo}_{$token}.png";
        $qrFileFs = $qrDirFs . $qrFilename;
        $qrWebPath = "qrcodes/" . $qrFilename;
        if (!file_exists($qrFileFs)) {
            $verifyUrl = "https://dcubeeresultportal3.com/rexchristus/verify-transcript.php?token={$token}";
            QRcode::png($verifyUrl, $qrFileFs, QR_ECLEVEL_L, 4);
        }
    }
}

// include header like users.php (tries several common locations; falls back to minimal header)
$headerFiles = ['header.php','includes/header.php','partials/header.php','templates/header.php'];
$headerIncluded = false;
foreach ($headerFiles as $hf) {
    $path = __DIR__ . '/' . $hf;
    if (file_exists($path)) { include $path; $headerIncluded = true; break; }
}
if (!$headerIncluded) {
    // minimal fallback header (includes bootstrap + basic styles)
    ?>
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Transcript - Rexchristus College</title>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
      <style>
        .student-card{border-left:4px solid #0d6efd;background:#f8f9fa;padding:12px;border-radius:6px}
        .page-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem}
        .brand-logo{display:flex;align-items:center;gap:.75rem}
        .brand-logo .logo {width:44px;height:44px;background:linear-gradient(135deg,#0d6efd,#4ea8ff);border-radius:8px;color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700}
        @media print{.no-print{display:none !important}}
      </style>
    </head>
    <body class="p-4">
    <div class="container">
    <?php
} else {
    // assume header opened container; if not, ensure content begins in a container
    // nothing to do here
}




// NEW: try to include sidebar exactly like users.php and open content column if present
$sidebarFiles = ['sidebar.php','includes/sidebar.php','qdmin/partials/sidebar.php','templates/sidebar.php'];
$sidebarPath = null;
foreach ($sidebarFiles as $sf) {
    $p = __DIR__ . '/' . $sf;
    if (file_exists($p)) { $sidebarPath = $p; break; }
}
$layoutHasSidebar = false;
if ($sidebarPath) {
    // start a row with sidebar column and a main content column
    echo '<div class="row">';
    echo '<div class="col-md-3 d-none d-md-block">';
    include $sidebarPath;
    echo '</div>'; // end sidebar col
    echo '<div class="col-md-9">'; // start main content col
    $layoutHasSidebar = true;
}
?>
  <div class="d-flex justify-content-between mb-3 page-header">
    <div>
      <div class="brand-logo">
        <div class="logo">RC</div>
        <div>
          <h4 class="mb-0">Transcript</h4>
          <small class="text-muted">Rexchristus College — Student Transcript</small>
        </div>
      </div>
    </div>
    <div>
      <?php if($currentUser): ?>
        <div class="text-end">Logged in: <?= htmlspecialchars($currentUser['name']) ?> — <a href="logout.php">Logout</a></div>
      <?php else: ?>
        <a class="btn btn-primary" href="login.php">Login</a>
      <?php endif; ?>
    </div>
  </div>

  <form class="row g-2 no-print mb-3" method="GET">
    <div class="col-auto"><input class="form-control" name="admissionno" placeholder="Admission no" value="<?= htmlspecialchars($admissionno) ?>" required></div>
    <div class="col-auto"><input class="form-control" name="start_year" value="<?= htmlspecialchars($startYear) ?>"></div>
    <div class="col-auto"><input class="form-control" name="end_year" value="<?= htmlspecialchars($endYear) ?>"></div>
    <div class="col-auto"><button class="btn btn-primary">Show Transcript</button></div>
  </form>
  <?php if($student): ?>
    <div class="student-card mb-3">
      <div class="row">
        <div class="col-md-8">
          <strong><?= htmlspecialchars($student['lname'] . ' ' . $student['fname']) ?></strong><br>
          <small>Admission No: <?= htmlspecialchars($student['admissionno']) ?> | Class: <?= htmlspecialchars($student['class']) ?></small>
        </div>
        <div class="col-md-4 text-end">
          <?php if($qrWebPath): ?><a href="<?= htmlspecialchars($qrWebPath) ?>" target="_blank"><img src="<?= htmlspecialchars($qrWebPath) ?>" alt="QR" width="90"></a><div><small>Scan or click to verify</small></div><?php endif; ?>
        </div>
      </div>
    </div>
    <?php if($results): ?>
      <?php $grouped = []; foreach($results as $r) $grouped[$r['year']][] = $r; ?>
      <div id="transcript-area">
      <?php foreach($grouped as $year => $rows): $classLabel = $rows[0]['class'] ?? ''; $yearTotal = 0; $yearCount = 0; ?>
        <h5 class="mt-4">Class: <?= htmlspecialchars($classLabel) ?> — <?= htmlspecialchars($year) ?></h5>
        <table class="table table-bordered">
          <thead class="table-light"><tr><th>S/N</th><th>Subject</th><th>Term</th><th>Total First</th><th>Total Second</th><th>Total Third</th><th>Average</th><th>Grade</th><th>Remarks</th></tr></thead>
          <tbody><?php $sn=1; foreach($rows as $r): $yearTotal += (float)$r['avg']; $yearCount++; ?><tr><td><?= $sn++ ?></td><td><?= htmlspecialchars($r['subject']) ?></td><td><?= htmlspecialchars($r['term']) ?></td><td><?= htmlspecialchars($r['totalfirst']) ?></td><td><?= htmlspecialchars($r['totalsecond']) ?></td><td><?= htmlspecialchars($r['totalthird']) ?></td><td><?= number_format((float)$r['avg'], 2) ?></td><td><?= htmlspecialchars($r['grade']) ?></td><td><?= htmlspecialchars($r['remarks']) ?></td></tr><?php endforeach; ?></tbody>
          <tfoot><tr class="table-light"><td colspan="6" class="text-end"><strong>Yearly Average:</strong></td><td colspan="3"><strong><?= $yearCount ? number_format($yearTotal / $yearCount, 2) : '0.00' ?></strong></td></tr></tfoot>
        </table>
      <?php endforeach; ?>
      </div>
      <div class="d-flex justify-content-end mt-3 no-print">
        <button id="printBtn" class="btn btn-success me-2">🖨 Print</button>
      </div>
      <script>
        document.getElementById('printBtn').addEventListener('click', function(){
          fetch('recordPrint.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ admissionno: <?= json_encode($admissionno) ?> }) }).then(()=> { window.print(); }).catch(()=> { window.print(); });
        });
      </script>
    <?php else: ?><div class="alert alert-warning">No results found in selected range.</div><?php endif; ?>
  <?php elseif($admissionno): ?><div class="alert alert-danger">Student not found.</div><?php endif; ?>

<?php
// include footer like users.php (tries several common locations; falls back to minimal footer)
$footerFiles = ['footer.php','includes/footer.php','partials/footer.php','templates/footer.php'];
$footerIncluded = false;
foreach ($footerFiles as $ff) {
    $path = __DIR__ . '/' . $ff;
    if (file_exists($path)) { include $path; $footerIncluded = true; break; }
}

// NEW: if we opened a main content column because sidebar was included, close the column/row before footer
if (!isset($layoutHasSidebar)) $layoutHasSidebar = false;
if (!$footerIncluded) {
    if ($layoutHasSidebar) {
        echo '</div>'; // close .col-md-9
        echo '</div>'; // close .row
    }
    // minimal fallback footer (close container/body/html and include bootstrap bundle)
    ?>
    </div> <!-- /.container -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    <?php
} else {
    // footer file was included by users.php pattern — ensure we still close content wrappers if needed
    if ($layoutHasSidebar) {
        echo '</div>'; // close .col-md-9
        echo '</div>'; // close .row
    }
}
?>
