<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || !$user->isTeacher()) {
    header("Location: ../index.php");
    exit;
}

$fpdf_path = '../includes/fpdf/fpdf.php';
if (!file_exists($fpdf_path)) {
    // Fallback check
    if (file_exists('../includes/fpdf.php')) {
        $fpdf_path = '../includes/fpdf.php';
    } else {
        echo '<div style="font-family: sans-serif; padding: 20px; max-width: 600px; margin: 50px auto; border: 1px solid #f00; background: #fff0f0; color: #d00; border-radius: 5px;">';
        echo '<h3 style="margin-top:0;">FPDF Library Missing</h3>';
        echo '<p>To enable PDF export, you need to install the FPDF library.</p>';
        echo '<ol>';
        echo '<li>Download the ZIP file from <a href="http://www.fpdf.org" target="_blank">fpdf.org</a>.</li>';
        echo '<li>Extract it.</li>';
        echo '<li>Create a folder named <code>fpdf</code> inside your <code>includes</code> directory.</li>';
        echo '<li>Copy <code>fpdf.php</code> and the <code>font</code> directory into <code>includes/fpdf/</code>.</li>';
        echo '</ol>';
        echo '<p><strong>Expected Path:</strong> <code>.../includes/fpdf/fpdf.php</code></p>';
        echo '<p><button onclick="window.location.reload()" style="padding: 10px 15px; cursor: pointer;">I have installed it, Reload Page</button></p>';
        echo '</div>';
        exit;
    }
}

require_once $fpdf_path;

class PDF extends FPDF {
    protected $schoolName = "School CBT System";

    function setSchoolName($name) {
        $this->schoolName = $name;
    }

    function Header() {
        // Logo
        $logo = '../assets/logo.png';
        if (file_exists('../assets/logo.jpg')) $logo = '../assets/logo.jpg';
        
        // Centered Header Container
        $this->SetFont('Arial', 'B', 18);
        
        // Calculate X to center the block (Logo + Text) roughly
        // If logo exists, we place it, then text.
        
        if (file_exists($logo)) {
            $this->Image($logo, 10, 10, 25);
            $this->SetX(40); // Offset for text
        }
        
        $this->Cell(0, 10, strtoupper($this->schoolName), 0, 1, 'C');
        
        $this->SetFont('Arial', 'B', 10);
        $this->Cell(0, 5, 'COMPUTER BASED TESTING (CBT) SYSTEM', 0, 1, 'C');
        
        $this->Ln(10);
        $this->SetDrawColor(0,0,0);
        $this->SetLineWidth(0.5);
        $this->Line(10, 35, 200, 35);
        $this->Ln(10);
    }

    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(128);
        $this->Cell(0, 10, 'Generated on ' . date('d-M-Y h:i A') . ' - Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
    }
}

// Fetch Settings for School Name
$stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'school_name'");
$school_name = $stmt->fetchColumn() ?: 'CBT System';

$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->setSchoolName($school_name);
$pdf->AddPage();

if (isset($_GET['result_id'])) {
    // SINGLE RESULT EXPORT
    $result_id = $_GET['result_id'];
    $stmt = $pdo->prepare("
        SELECT r.*, e.title as exam_title, e.session, e.term, u.username, u.full_name, c.class_name
        FROM results r 
        JOIN exams e ON r.exam_id = e.exam_id 
        JOIN users u ON r.user_id = u.user_id 
        LEFT JOIN classes c ON u.class_id = c.class_id
        WHERE r.result_id = ?
    ");
    $stmt->execute([$result_id]);
    $res = $stmt->fetch();

    if (!$res) die("Result not found.");

    $pdf->SetFont('Arial', 'B', 16);
    $pdf->SetFillColor(230, 230, 230);
    $pdf->Cell(0, 12, 'OFFICIAL RESULT SLIP', 0, 1, 'C', true);
    $pdf->Ln(10);

    $pdf->SetFont('Arial', '', 12);
    
    // Student Details Box
    $pdf->SetFillColor(250, 250, 250);
    $pdf->Rect(10, $pdf->GetY(), 190, 45, 'F');
    $pdf->Rect(10, $pdf->GetY(), 190, 45, 'D');
    
    $pdf->SetXY(15, $pdf->GetY() + 5);
    $pdf->SetFont('Arial', 'B', 12); $pdf->Cell(40, 8, 'Student Name:', 0, 0);
    $pdf->SetFont('Arial', '', 12);  $pdf->Cell(0, 8, ($res['full_name'] ? $res['full_name'] : $res['username']), 0, 1);
    
    $pdf->SetX(15);
    $pdf->SetFont('Arial', 'B', 12); $pdf->Cell(40, 8, 'Class:', 0, 0);
    $pdf->SetFont('Arial', '', 12);  $pdf->Cell(0, 8, ($res['class_name'] ?: 'N/A'), 0, 1);

    $pdf->SetX(15);
    $pdf->SetFont('Arial', 'B', 12); $pdf->Cell(40, 8, 'Exam:', 0, 0);
    $pdf->SetFont('Arial', '', 12);  $pdf->Cell(0, 8, $res['exam_title'], 0, 1);

    $pdf->SetX(15);
    $pdf->SetFont('Arial', 'B', 12); $pdf->Cell(40, 8, 'Session/Term:', 0, 0);
    $pdf->SetFont('Arial', '', 12);  $pdf->Cell(0, 8, $res['session'] . ' ' . $res['term'], 0, 1);

    $pdf->Ln(20);
    
    // Score Section
    $pdf->SetFont('Arial', 'B', 14);
    $pdf->Cell(0, 10, 'PERFORMANCE SUMMARY', 0, 1, 'L');
    $pdf->SetLineWidth(0.2);
    $pdf->Line(10, $pdf->GetY(), 200, $pdf->GetY());
    $pdf->Ln(5);

    $percent = ($res['score'] / $res['total_questions']) * 100;
    
    // Grade Logic
    $grade = 'F';
    $remark = 'Fail';
    $color = [200, 0, 0]; // Red
    
    if ($percent >= 70) { $grade = 'A'; $remark = 'Excellent'; $color = [0, 128, 0]; }
    elseif ($percent >= 60) { $grade = 'B'; $remark = 'Very Good'; $color = [0, 100, 0]; }
    elseif ($percent >= 50) { $grade = 'C'; $remark = 'Good'; $color = [0, 0, 128]; }
    elseif ($percent >= 45) { $grade = 'D'; $remark = 'Fair'; $color = [204, 204, 0]; }
    elseif ($percent >= 40) { $grade = 'E'; $remark = 'Pass'; $color = [255, 165, 0]; }
    
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(60, 10, 'Score Obtained:', 1, 0);
    $pdf->SetFont('Arial', '', 12);
    $pdf->Cell(0, 10, $res['score'] . ' / ' . $res['total_questions'], 1, 1);
    
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(60, 10, 'Percentage:', 1, 0);
    $pdf->SetFont('Arial', '', 12);
    $pdf->Cell(0, 10, number_format($percent, 2) . '%', 1, 1);
    
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(60, 10, 'Grade:', 1, 0);
    $pdf->SetTextColor($color[0], $color[1], $color[2]);
    $pdf->SetFont('Arial', 'B', 14);
    $pdf->Cell(0, 10, $grade . ' (' . $remark . ')', 1, 1);
    $pdf->SetTextColor(0);

    $pdf->Ln(30);
    $pdf->SetFont('Arial', '', 10);
    $pdf->Cell(0, 5, '__________________________', 0, 1, 'R');
    $pdf->Cell(0, 5, 'Principal\'s Signature', 0, 1, 'R');

    $pdf->Output('I', 'Result_' . preg_replace('/[^a-zA-Z0-9]/', '_', $res['username']) . '.pdf');

} elseif (isset($_GET['exam_id'])) {
    // BROADSHEET EXPORT
    $exam_id = $_GET['exam_id'];
    $stmt = $pdo->prepare("SELECT * FROM exams WHERE exam_id = ?");
    $stmt->execute([$exam_id]);
    $exam = $stmt->fetch();

    if (!$exam) die("Exam not found.");

    $stmt = $pdo->prepare("
        SELECT r.*, u.username, u.full_name 
        FROM results r 
        JOIN users u ON r.user_id = u.user_id 
        WHERE r.exam_id = ? 
        ORDER BY r.score DESC
    ");
    $stmt->execute([$exam_id]);
    $results = $stmt->fetchAll();

    $pdf->SetFont('Arial', 'B', 14);
    $pdf->Cell(0, 10, 'EXAM BROADSHEET', 0, 1, 'C');
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(0, 10, strtoupper($exam['title']), 0, 1, 'C');
    $pdf->SetFont('Arial', '', 10);
    $pdf->Cell(0, 6, $exam['session'] . ' ' . $exam['term'], 0, 1, 'C');
    $pdf->Ln(5);

    // Table Header
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetFillColor(50, 50, 50);
    $pdf->SetTextColor(255);
    $pdf->Cell(15, 10, 'S/N', 1, 0, 'C', true);
    $pdf->Cell(70, 10, 'Student Name', 1, 0, 'L', true);
    $pdf->Cell(25, 10, 'Score', 1, 0, 'C', true);
    $pdf->Cell(25, 10, 'Total', 1, 0, 'C', true);
    $pdf->Cell(25, 10, '%', 1, 0, 'C', true);
    $pdf->Cell(30, 10, 'Grade', 1, 1, 'C', true);

    // Table Body
    $pdf->SetFont('Arial', '', 10);
    $pdf->SetTextColor(0);
    $pdf->SetFillColor(240, 240, 240);
    
    $sn = 1;
    $fill = false;
    foreach ($results as $r) {
        $percent = ($r['score'] / $r['total_questions']) * 100;
        $grade = 'F';
        if ($percent >= 70) $grade = 'A';
        elseif ($percent >= 60) $grade = 'B';
        elseif ($percent >= 50) $grade = 'C';
        elseif ($percent >= 45) $grade = 'D';
        elseif ($percent >= 40) $grade = 'E';

        $name = $r['full_name'] ? $r['full_name'] : $r['username'];

        $pdf->Cell(15, 8, $sn++, 1, 0, 'C', $fill);
        $pdf->Cell(70, 8, substr($name, 0, 35), 1, 0, 'L', $fill);
        $pdf->Cell(25, 8, $r['score'], 1, 0, 'C', $fill);
        $pdf->Cell(25, 8, $r['total_questions'], 1, 0, 'C', $fill);
        $pdf->Cell(25, 8, number_format($percent, 1) . '%', 1, 0, 'C', $fill);
        $pdf->Cell(30, 8, $grade, 1, 1, 'C', $fill);
        
        $fill = !$fill; // Alternating colors
    }

    $pdf->Output('I', 'Broadsheet_' . preg_replace('/[^a-zA-Z0-9]/', '_', $exam['title']) . '.pdf');

} elseif (isset($_GET['type']) && $_GET['type'] === 'timetable' && isset($_GET['user_id'])) {
    $user_id = (int)$_GET['user_id'];
    $stmtU = $pdo->prepare("
        SELECT u.username, u.full_name, c.class_name 
        FROM users u
        LEFT JOIN classes c ON u.class_id = c.class_id
        WHERE u.user_id = ?
    ");
    $stmtU->execute([$user_id]);
    $stu = $stmtU->fetch();
    if (!$stu) die("Student not found.");
    $stmtTT = $pdo->prepare("
        SELECT e.title, e.session, e.term, s.name AS subject_name,
               COALESCE(ses.slot_start, e.start_at) AS start_at,
               COALESCE(ses.slot_end, e.end_at) AS end_at
        FROM exam_assignments ea
        JOIN exams e ON ea.exam_id = e.exam_id
        LEFT JOIN subjects s ON e.subject_id = s.subject_id
        LEFT JOIN student_exam_schedule ses ON ses.exam_id = e.exam_id AND ses.user_id = ea.user_id
        WHERE ea.user_id = ?
        ORDER BY start_at ASC
    ");
    $stmtTT->execute([$user_id]);
    $rows = $stmtTT->fetchAll();
    $pdf->SetFont('Arial', 'B', 14);
    $pdf->Cell(0, 10, 'STUDENT EXAM TIMETABLE', 0, 1, 'C');
    $pdf->SetFont('Arial', '', 12);
    $name = $stu['full_name'] ? $stu['full_name'] : $stu['username'];
    $pdf->Cell(0, 8, 'Student: ' . $name, 0, 1, 'L');
    $pdf->Cell(0, 8, 'Class: ' . ($stu['class_name'] ?: 'N/A'), 0, 1, 'L');
    $pdf->Ln(5);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetFillColor(50,50,50);
    $pdf->SetTextColor(255);
    $pdf->Cell(70, 10, 'Exam Title', 1, 0, 'L', true);
    $pdf->Cell(35, 10, 'Subject', 1, 0, 'L', true);
    $pdf->Cell(35, 10, 'Session/Term', 1, 0, 'L', true);
    $pdf->Cell(25, 10, 'Start', 1, 0, 'C', true);
    $pdf->Cell(25, 10, 'End', 1, 1, 'C', true);
    $pdf->SetFont('Arial', '', 10);
    $pdf->SetTextColor(0);
    $pdf->SetFillColor(240,240,240);
    $fill = false;
    foreach ($rows as $r) {
        $pdf->Cell(70, 8, substr($r['title'],0,38), 1, 0, 'L', $fill);
        $pdf->Cell(35, 8, substr($r['subject_name'] ?: '',0,18), 1, 0, 'L', $fill);
        $pdf->Cell(35, 8, ($r['session'] ?: '-') . ' ' . ($r['term'] ?: '-'), 1, 0, 'L', $fill);
        $pdf->Cell(25, 8, ($r['start_at'] ? date('d/m H:i', strtotime($r['start_at'])) : '-'), 1, 0, 'C', $fill);
        $pdf->Cell(25, 8, ($r['end_at'] ? date('d/m H:i', strtotime($r['end_at'])) : '-'), 1, 1, 'C', $fill);
        $fill = !$fill;
    }
    $pdf->Output('I', 'Timetable_' . preg_replace('/[^a-zA-Z0-9]/', '_', $name) . '.pdf');
} elseif (isset($_GET['type']) && $_GET['type'] === 'exam_schedule' && isset($_GET['exam_id'])) {
    $exam_id = (int)$_GET['exam_id'];
    $stmtE = $pdo->prepare("
        SELECT e.*, s.name AS subject_name, c.class_name
        FROM exams e
        LEFT JOIN subjects s ON e.subject_id = s.subject_id
        LEFT JOIN classes c ON e.class_id = c.class_id
        WHERE e.exam_id = ?
    ");
    $stmtE->execute([$exam_id]);
    $exam = $stmtE->fetch();
    if (!$exam) die("Exam not found.");
    $stmtRows = $pdo->prepare("
        SELECT u.username, u.full_name, c.class_name,
               COALESCE(ses.slot_start, e.start_at) AS start_at,
               COALESCE(ses.slot_end, e.end_at) AS end_at
        FROM exam_assignments ea
        JOIN users u ON ea.user_id = u.user_id
        LEFT JOIN classes c ON u.class_id = c.class_id
        JOIN exams e ON ea.exam_id = e.exam_id
        LEFT JOIN student_exam_schedule ses ON ses.exam_id = ea.exam_id AND ses.user_id = ea.user_id
        WHERE ea.exam_id = ?
        ORDER BY start_at ASC, u.username ASC
    ");
    $stmtRows->execute([$exam_id]);
    $rows = $stmtRows->fetchAll();
    $pdf->SetFont('Arial', 'B', 14);
    $pdf->Cell(0, 10, 'EXAM TIMETABLE (BY STUDENT)', 0, 1, 'C');
    $pdf->SetFont('Arial', '', 10);
    $pdf->Cell(0, 6, strtoupper($exam['title']) . ' - ' . ($exam['subject_name'] ?: ''), 0, 1, 'C');
    $pdf->Cell(0, 6, ($exam['session'] ?: '-') . ' ' . ($exam['term'] ?: '-') . ' | Class: ' . ($exam['class_name'] ?: 'All'), 0, 1, 'C');
    $pdf->Ln(5);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetFillColor(50,50,50);
    $pdf->SetTextColor(255);
    $pdf->Cell(70, 10, 'Student', 1, 0, 'L', true);
    $pdf->Cell(35, 10, 'Class', 1, 0, 'L', true);
    $pdf->Cell(35, 10, 'Session/Term', 1, 0, 'L', true);
    $pdf->Cell(25, 10, 'Start', 1, 0, 'C', true);
    $pdf->Cell(25, 10, 'End', 1, 1, 'C', true);
    $pdf->SetFont('Arial', '', 10);
    $pdf->SetTextColor(0);
    $pdf->SetFillColor(240,240,240);
    $fill = false;
    foreach ($rows as $r) {
        $name = $r['full_name'] ? $r['full_name'] : $r['username'];
        $pdf->Cell(70, 8, substr($name,0,38), 1, 0, 'L', $fill);
        $pdf->Cell(35, 8, substr($r['class_name'] ?: '',0,18), 1, 0, 'L', $fill);
        $pdf->Cell(35, 8, ($exam['session'] ?: '-') . ' ' . ($exam['term'] ?: '-'), 1, 0, 'L', $fill);
        $pdf->Cell(25, 8, ($r['start_at'] ? date('d/m H:i', strtotime($r['start_at'])) : '-'), 1, 0, 'C', $fill);
        $pdf->Cell(25, 8, ($r['end_at'] ? date('d/m H:i', strtotime($r['end_at'])) : '-'), 1, 1, 'C', $fill);
        $fill = !$fill;
    }
    $pdf->Output('I', 'Exam_Timetable_' . preg_replace('/[^a-zA-Z0-9]/', '_', $exam['title']) . '.pdf');
} else {
    echo "No valid parameters provided.";
}
