<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start(); // Start the session

if (!isset($_SESSION['email'])) {
    header("Location: ../index.php");
    exit();
}
require('../fpdf/fpdf.php');
include('../include/config.php'); // DB connection

class PDF extends FPDF {
    // Watermark & header
    function Header() {
        // Logo top-center
        if (file_exists('logo.png')) {
            $this->Image('logo.png', 85, 10, 40);
        }

        // Watermark
        if (file_exists('opacity.png')) {
            $this->SetAlpha(0.02); // low opacity
            $this->Image('opacity.png', 40, 60, 130);
            $this->SetAlpha(1); // reset opacity
        }

        $this->Ln(30);
        $this->SetFont('Arial', 'B', 16);
                $this->Ln(4);
                        $this->Cell(190, 10, 'UNICOHS UNIVERSITY COLLEGE', 0, 1, 'C');

        $this->Cell(190, 10, 'OFFICIAL  TRANSCRIPT', 0, 1, 'C');
        $this->Ln(3);
        $this->SetFont('Arial', '', 11);
        $this->Cell(190, 6, 'CONFIDENTIAL DOCUMENT - ISSUED BY REGISTRAR\'S OFFICE', 0, 1, 'C');
        $this->Ln(10);
    }

    // Footer with page number
    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 9);
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
    }

    // Transparency
    function SetAlpha($alpha, $bm='Normal') {
        static $extgstates = array();
        if (!isset($extgstates[$alpha.$bm])) {
            $n = count($extgstates)+1;
            $this->_newobj();
            $extgstates[$alpha.$bm] = $this->n;
            $this->_out('<</Type /ExtGState /ca '.$alpha.' /CA '.$alpha.' /BM /'.$bm.'>>');
            $this->_out('endobj');
        }
        $this->_out(sprintf('/GS%d gs', $extgstates[$alpha.$bm]));
    }
}

if (isset($_GET['program']) && isset($_GET['intake'])) {
    $program = $_GET['program'];
    $intake = $_GET['intake'];

    // Fetch students
    $students = $conn->query("SELECT * FROM students WHERE program='$program' AND intake='$intake'");

    if ($students->num_rows == 0) {
        exit("<h3 style='color:red;text-align:center;'>No students found for $program ($intake)</h3>");
    }

    $pdf = new PDF();

    while ($student = $students->fetch_assoc()) {
        $pdf->AddPage();

        // --- Student Info ---
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(40, 8, 'Student Name:', 0, 0);
        $pdf->SetFont('Arial', '', 12);
        $pdf->Cell(70, 8, $student['studentname'], 0, 0);
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(30, 8, 'Student ID:', 0, 0);
        $pdf->SetFont('Arial', '', 12);
        $pdf->Cell(40, 8, $student['studentid'], 0, 1);

        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(40, 8, 'Program:', 0, 0);
        $pdf->SetFont('Arial', '', 12);
        $pdf->Cell(70, 8, $student['program'], 0, 0);
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(30, 8, 'Intake:', 0, 0);
        $pdf->SetFont('Arial', '', 12);
        $pdf->Cell(40, 8, $student['intake'], 0, 1);

        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(40, 8, 'Gender:', 0, 0);
        $pdf->SetFont('Arial', '', 12);
        $pdf->Cell(70, 8, ucfirst($student['gender']), 0, 0);
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(30, 8, 'Study Period:', 0, 0);
        $pdf->SetFont('Arial', '', 12);
        $pdf->Cell(40, 8, $student['start_year'] . " - " . $student['end_year'], 0, 1);
        $pdf->Ln(8);

        // --- Academic Results ---
        $pdf->SetFont('Arial', 'B', 14);
        $pdf->Cell(190, 10, 'Academic Results', 0, 1, 'L');
        $pdf->Ln(2);

        $results = $conn->query("
            SELECT year, term, course, ca, ca1, ca2, exam
            FROM results
            WHERE studentid = '{$student['studentid']}'
            ORDER BY year, term, course
        ");

        if ($results->num_rows == 0) {
            $pdf->Cell(190, 8, 'No results found.', 0, 1, 'C');
        } else {
            $currentYear = '';
            $currentTerm = '';

            while ($row = $results->fetch_assoc()) {
                $year = $row['year'];
                $term = $row['term'];

                // Ensure numeric values to avoid warnings
                $ca_total = (float)$row['ca'] + (float)$row['ca1'] + (float)$row['ca2'];
                $final_total = $ca_total + (float)$row['exam'];
                $comment = ($final_total >= 40) ? 'Cleared' : 'Not Cleared';

                if ($currentYear != $year || $currentTerm != $term) {
                    $currentYear = $year;
                    $currentTerm = $term;

                    $pdf->Ln(5);
                    $pdf->SetFont('Arial', 'B', 12);
                    $pdf->Cell(190, 8, "Year: $year  |  Semester: $term", 0, 1);
                    $pdf->SetFont('Arial', 'B', 11);
                    $pdf->Cell(110, 8, 'Course', 1);
                    $pdf->Cell(40, 8, 'Final Score', 1);
                    $pdf->Cell(40, 8, 'Comment', 1, 1);
                    $pdf->SetFont('Arial', '', 11);
                }

                $pdf->Cell(110, 8, $row['course'], 1);
                $pdf->Cell(40, 8, number_format($final_total, 1), 1);
                $pdf->Cell(40, 8, $comment, 1, 1);
            }
        }

        // --- Footer ---
        $pdf->Ln(15);
        $pdf->SetFont('Arial', 'I', 10);
        $pdf->Cell(190, 10, 'This transcript is issued by the Registrar\'s Office on ' . date("Y-m-d"), 0, 1, 'C');
        $pdf->Ln(10);
        $pdf->SetFont('Arial', '', 11);
        $pdf->Cell(190, 6, 'Registrar Signature: ___________________________', 0, 1, 'L');
        $pdf->Ln(5);
        $pdf->Cell(190, 6, 'College Seal: _________________________________', 0, 1, 'L');
    }

    // Output all students PDF directly
    $pdf->Output('D', "All_Transcripts_{$program}_{$intake}.pdf");
    exit;

} else {
?>
<?php include "../include/nav.php";?>
<div class="content">
<?php
// Fetch programs and intakes from database
$programs = $conn->query("SELECT DISTINCT program FROM students ORDER BY program");
$intakes = $conn->query("SELECT DISTINCT intake FROM students ORDER BY intake DESC");
?>

<form method="get" style="
    max-width: 450px;
    margin: 60px auto;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    padding: 30px;
    border: 1px solid #e0e0e0;
    border-radius: 12px;
    background: white;
    box-shadow: 0 8px 25px rgba(0,0,0,0.1);
">
    <h2 style="
        text-align: center;
        color: var(--primary);
        margin-bottom: 25px;
        font-size: 24px;
        font-weight: 600;
    ">Generate  Student Transcripts</h2>
    
    <div style="margin-bottom: 20px;">
        <label style="
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
            font-size: 14px;
        ">Program:</label>
        <select name="program" required style="
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 15px;
            background: white;
            transition: all 0.3s;
            appearance: none;
            background-image: url('data:image/svg+xml;utf8,<svg fill="%23d03f4d" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 12px center;
            background-size: 16px;
        " onfocus="this.style.borderColor='var(--primary)'; this.style.boxShadow='0 0 0 3px rgba(208,63,77,0.1)'" 
        onblur="this.style.borderColor='#e0e0e0'; this.style.boxShadow='none'">
            <option value="">Select Program</option>
            <?php while($program = $programs->fetch_assoc()): ?>
                <option value="<?php echo htmlspecialchars($program['program']); ?>">
                    <?php echo htmlspecialchars($program['program']); ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
    
    <div style="margin-bottom: 30px;">
        <label style="
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
            font-size: 14px;
        ">Intake:</label>
        <select name="intake" required style="
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 15px;
            background: white;
            transition: all 0.3s;
            appearance: none;
            background-image: url('data:image/svg+xml;utf8,<svg fill="%23d03f4d" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 12px center;
            background-size: 16px;
        " onfocus="this.style.borderColor='var(--primary)'; this.style.boxShadow='0 0 0 3px rgba(208,63,77,0.1)'" 
        onblur="this.style.borderColor='#e0e0e0'; this.style.boxShadow='none'">
            <option value="">Select Intake</option>
            <?php while($intake = $intakes->fetch_assoc()): ?>
                <option value="<?php echo htmlspecialchars($intake['intake']); ?>">
                    <?php echo htmlspecialchars($intake['intake']); ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
    
    <button type="submit" style="
        width: 100%;
        padding: 14px 20px;
        background:var(--primary);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(208,63,77,0.3);
    " onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 20px rgba(208,63,77,0.4)'" 
    onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 15px rgba(208,63,77,0.3)'">
        📄 Generate PDF Transcripts
    </button>
    
    <div style="
        margin-top: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 6px;
        text-align: center;
        font-size: 13px;
        color: #666;
    ">
        <strong>Note:</strong> This will generate transcripts for all students in the selected program and intake.
    </div>
</form>
</div>
<?php
}
?>
