<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['student_id'])) {
    ob_start();
    require_once('tcpdf/tcpdf.php');
    require_once('db_connection.php');

    $student_id = $_POST['student_id'];
    $term = $_POST['report_term'];
    $year = $_POST['report_year'];

    // Fetch END OF TERM results from RESULTS table
    $stmt_end = $pdo->prepare("SELECT * FROM RESULTS WHERE STUDENT_ID = ? AND TERM = ? AND YEAR = ?");
    $stmt_end->execute([$student_id, $term, $year]);
    $end_result = $stmt_end->fetch(PDO::FETCH_ASSOC);

    // Fetch MIDTERM results from MIDTERM_RESULTS table
    $stmt_mid = $pdo->prepare("SELECT * FROM midterm_results WHERE STUDENT_ID = ? AND TERM = ? AND YEAR = ?");
    $stmt_mid->execute([$student_id, $term, $year]);
    $mid_result = $stmt_mid->fetch(PDO::FETCH_ASSOC);

    if (!$end_result && !$mid_result) {
        http_response_code(404);
        echo "No results found for this student in the selected term/year.";
        exit;
    }

    $pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->SetCreator('Luzira COU Primary School');
    $pdf->SetAuthor('Luzira COU Primary School');
    $pdf->SetTitle("Student Report - $student_id");
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(5, 5, 5);
    $pdf->SetAutoPageBreak(TRUE, 10);
    $pdf->SetFont('helvetica', '', 10);
    $pdf->AddPage();

    $pdf->Image('logo.png', 7, 5, 20);
    $pdf->SetFont('helvetica', 'B', 16);
    $pdf->Cell(0, 10, 'LUZIRA CHURCH OF UGANDA PRIMARY SCHOOL', 0, 1, 'C');
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 5, "STUDENT'S PROGRESSIVE REPORT - $term $year", 0, 1, 'C');
    $pdf->Ln(8);

    // Basic student info
    $source = $end_result ?: $mid_result;
    $pdf->SetFont('helvetica', '', 11);
    $pdf->writeHTML("
        <strong>Student ID:</strong> {$source['STUDENT_ID']}<br>
        <strong>Name:</strong> {$source['STUDENT_NAME']}<br>
        <strong>Class:</strong> {$source['CLASS']}<br>
        <strong>Sex:</strong> {$source['SEX']}
    ", true, false, false, false, '');

    // === Midterm Results Section ===
    if ($mid_result) {
        $pdf->Ln(5);
        $pdf->SetFont('helvetica', 'B', 11);
        $pdf->Cell(0, 6, 'MIDTERM RESULTS', 0, 1, 'L');
        $pdf->SetFont('helvetica', '', 11);

        // Styled midterm table
        $mid_table = '
        <style>
            table { border-collapse: collapse; width: 100%; }
            th, td { border: 1px solid #4CAF50; padding: 6px; }
            th { background-color: #4CAF50; color: white; }
            tr:nth-child(even) { background-color: #f2fff2; }
            tr:nth-child(odd) { background-color: #e6ffe6; }
            td:first-child { font-weight: bold; width: 50%; }
        </style>
        <table>';
        foreach ($mid_result as $key => $value) {
            if (!in_array($key, ['STUDENT_ID', 'STUDENT_NAME', 'CLASS', 'SEX', 'TERM', 'YEAR'])) {
                $label = ucwords(strtolower(str_replace('_', ' ', $key)));
                $mid_table .= "<tr><td>$label</td><td>$value</td></tr>";
            }
        }
        $mid_table .= '</table>';
        $pdf->writeHTML($mid_table, true, false, false, false, '');
    }

    // === End of Term Results Section ===
    if ($end_result) {
        $pdf->Ln(8);
        $pdf->SetFont('helvetica', 'B', 11);
        $pdf->Cell(0, 6, 'END OF TERM RESULTS', 0, 1, 'L');
        $pdf->SetFont('helvetica', '', 11);

        // Styled end term table
        $end_table = '
        <style>
            table { border-collapse: collapse; width: 100%; }
            th, td { border: 1px solid #007bff; padding: 6px; }
            th { background-color: #007bff; color: white; }
            tr:nth-child(even) { background-color: #e6f0ff; }
            tr:nth-child(odd) { background-color: #cce0ff; }
            td:first-child { font-weight: bold; width: 50%; }
        </style>
        <table>';
        foreach ($end_result as $key => $value) {
            if (!in_array($key, ['STUDENT_ID', 'STUDENT_NAME', 'CLASS', 'SEX', 'TERM', 'YEAR'])) {
                $label = ucwords(strtolower(str_replace('_', ' ', $key)));
                $end_table .= "<tr><td>$label</td><td>$value</td></tr>";
            }
        }
        $end_table .= '</table>';
        $pdf->writeHTML($end_table, true, false, false, false, '');
    }


    // Signature
    $pdf->Ln(12);
    $pdf->writeHTML('<strong>Headteacher\'s Signature:</strong>', true, false, false, false, '');
    $pdf->Image('signature.png', $pdf->GetX(), $pdf->GetY(), 30);
    $pdf->Ln(20);

    // Disclaimer
    $pdf->SetFont('', 'BI');
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFillColor(0, 0, 0);
    $pdf->Cell(0, 6, 'Disclaimer: These results can be verified via our website https://luziracouprimaryschool.com/', 0, 1, 'R', true);
    $pdf->SetTextColor(0, 0, 0);

    ob_end_clean();
    $pdf->Output("Student_Report_$student_id.pdf", 'I');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Verify Student Report</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background: #f1f1f1;
      margin: 0;
      padding: 0;
    }
    .container {
      max-width: 500px;
      margin: 30px auto;
      background: #fff;
      padding: 20px 30px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h2 {
      text-align: center;
      margin-bottom: 20px;
    }
    label {
      display: block;
      margin-top: 10px;
    }
    input, select, button {
      width: 100%;
      padding: 8px;
      margin-top: 5px;
      border-radius: 4px;
      border: 1px solid #ccc;
    }
    button {
      background-color: #28a745;
      color: white;
      border: none;
      margin-top: 15px;
      cursor: pointer;
    }
    button:hover {
      background-color: #218838;
    }
    #reportFrame {
      width: 100%;
      height: 600px;
      border: none;
      display: none;
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>Verify Student Report</h2>
    <form id="verifyForm" method="POST" target="reportFrame">
      <label for="student_id">Student ID:</label>
      <input type="text" id="student_id" name="student_id" required>

      <label for="report_term">Term:</label>
      <select id="report_term" name="report_term" required>
        <option value="Term 1">Term 1</option>
        <option value="Term 2">Term 2</option>
        <option value="Term 3">Term 3</option>
      </select>

      <label for="report_year">Year:</label>
      <input type="number" id="report_year" name="report_year" required>

      <button type="submit">Verify Report</button>
    </form>

    <iframe id="reportFrame" name="reportFrame"></iframe>
  </div>

  <script>
    const form = document.getElementById('verifyForm');
    const frame = document.getElementById('reportFrame');

    form.addEventListener('submit', function () {
      frame.style.display = 'block';
    });
  </script>
</body>
</html>
