<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../vendor/fpdf.php';
requireLogin();

$student_id = intval($_GET['student_id'] ?? 0);
requireStudentAccess($student_id);
$student = getStudent($id = $student_id);
if (!$student) die('ไม่พบข้อมูลนักศึกษา');

$summary = getStudentSummary($student_id);
if (!$summary) die('ไม่พบข้อมูล');

$student_courses = getStudentCourses($student_id);
$completed_map = $summary['completed_map'];
$total_curriculum_credits = getTotalCurriculumCredits($student['curriculum_id']);
$transfer_credits_total = getTransferCreditsTotal($student_id);
$total_completed = getCompletedCreditsTotal($student_id);

class SummaryPDF extends FPDF {
    function header() {
        $this->SetFont('Courier', '', 10);
        $this->Cell(0, 8, iconv('UTF-8','cp874','ใบควบคุมผลการเรียน'), 0, 1, 'C');
        $this->Ln(2);
    }
    function footer() {
        $this->SetY(-15);
        $this->SetFont('Courier', '', 8);
        $this->Cell(0, 10, iconv('UTF-8','cp874','หน้าที่ ').$this->PageNo().'/{nb}', 0, 0, 'C');
    }
}

$pdf = new SummaryPDF('P', 'mm', 'A4');
$pdf->AliasNbPages();
$pdf->SetMargins(8, 10, 8);
$pdf->AddPage();

// Student info
$pdf->SetFont('Courier', '', 9);
$info = [
    ['รหัสนักศึกษา:', $student['student_code']],
    ['ชื่อ-นามสกุล:', $student['name_th'] . ' (' . $student['name_en'] . ')'],
    ['สาขาวิชา:', $student['curriculum_code'] . ' - ' . $student['curriculum_name']],
    ['คณะ:', $student['faculty'] ?: '-'],
    ['สถาบันที่จบ:', $student['graduated_institution'] ?: '-'],
    ['ปีการศึกษา:', $student['enrollment_year']],
];
foreach ($info as $row) {
    $pdf->Cell(45, 5, iconv('UTF-8','cp874',$row[0]), 0, 0);
    $pdf->Cell(0, 5, iconv('UTF-8','cp874//IGNORE',$row[1]), 0, 1);
}

$pdf->Ln(1);
$remaining = max(0, $total_curriculum_credits - $total_completed);
$pct = $total_curriculum_credits > 0 ? round(($total_completed / $total_curriculum_credits) * 100) : 0;
$pdf->SetFont('Courier', 'B', 9);
$pdf->Cell(0, 6, iconv('UTF-8','cp874','เทียบโอน: '.$transfer_credits_total.'  |  เรียนแล้ว: '.$total_completed.'  |  คงเหลือ: '.$remaining.'  |  คิดเป็น '.$pct.'%'), 0, 1);
$pdf->Ln(3);

// Render tree recursively
$level = 0;
renderPdfTree($summary['groups'], $pdf, $level);

// Summary table
$pdf->Ln(3);
$pdf->SetFont('Courier', 'B', 9);
$pdf->Cell(0, 6, iconv('UTF-8','cp874','--- สรุปรายวิชาที่เรียนผ่านแล้วทั้งหมด ---'), 0, 1);
$pdf->Ln(1);

$pdf->SetFont('Courier', '', 8);
$pdf->Cell(28, 4, iconv('UTF-8','cp874','รหัสวิชา'), 1, 0);
$pdf->Cell(46, 4, iconv('UTF-8','cp874','ชื่อวิชา'), 1, 0);
$pdf->Cell(12, 4, iconv('UTF-8','cp874','หน่วยกิต'), 1, 0, 'C');
$pdf->Cell(10, 4, iconv('UTF-8','cp874','เกรด'), 1, 0, 'C');
$pdf->Cell(16, 4, iconv('UTF-8','cp874','ภาคเรียน'), 1, 0, 'C');
$pdf->Cell(16, 4, iconv('UTF-8','cp874','ปีการศึกษา'), 1, 0, 'C');
$pdf->Cell(19, 4, iconv('UTF-8','cp874','ประเภท'), 1, 1);

$total = 0;
foreach ($student_courses as $sc) {
    $total += $sc['credits'];
    $name = mb_substr($sc['course_name_th'], 0, 24, 'UTF-8');
    $type = iconv('UTF-8','cp874//IGNORE', $sc['course_type'] ?: ($sc['source_type'] == 'transfer' ? 'เทียบโอน' : 'เรียน'));
    $sem = $sc['semester'] ? 'ภาค '.$sc['semester'] : '-';
    $yr = $sc['academic_year'] ?: '-';
    $grade = $sc['grade'] ?: '-';
    $pdf->SetFont('Courier', '', 8);
    $pdf->Cell(28, 4, iconv('UTF-8','cp874//IGNORE',$sc['course_code']), 1, 0);
    $pdf->Cell(46, 4, iconv('UTF-8','cp874//IGNORE',$name), 1, 0);
    $pdf->Cell(12, 4, $sc['credits'], 1, 0, 'C');
    $pdf->Cell(10, 4, $grade, 1, 0, 'C');
    $pdf->Cell(16, 4, iconv('UTF-8','cp874//IGNORE',$sem), 1, 0, 'C');
    $pdf->Cell(16, 4, iconv('UTF-8','cp874//IGNORE',$yr), 1, 0, 'C');
    $pdf->Cell(19, 4, $type, 1, 1);
}

$pdf->SetFont('Courier', 'B', 8);
$pdf->Cell(147, 5, iconv('UTF-8','cp874','รวมหน่วยกิตที่เรียนผ่านแล้วทั้งหมด: '.$total.' หน่วยกิต'), 0, 1);
$pdf->Ln(3);

if ($remaining <= 0) {
    $pdf->SetFont('Courier', 'B', 10);
    $pdf->Cell(0, 6, iconv('UTF-8','cp874','*** ครบตามหลักสูตรแล้ว ***'), 0, 1, 'C');
} else {
    $pdf->SetFont('Courier', '', 9);
    $pdf->Cell(0, 6, iconv('UTF-8','cp874','หน่วยกิตคงเหลือที่ต้องเรียน: '.$remaining.' หน่วยกิต'), 0, 1);
}

$filename = 'Summary_' . $student['student_code'] . '_' . date('Ymd') . '.pdf';
$pdf->Output('I', $filename);

// ============================================================
function renderPdfTree($nodes, &$pdf, $level) {
    foreach ($nodes as $node) {
        $g = $node['group'];
        $has_courses = !empty($node['courses']);
        $has_children = !empty($node['children']);

        $indent = $level * 4;
        $pdf->SetX(8 + $indent);

        if ($level == 0) {
            $pdf->SetFont('Courier', 'B', 9);
        } elseif ($level == 1) {
            $pdf->SetFont('Courier', 'B', 8);
        } else {
            $pdf->SetFont('Courier', '', 8);
        }

        $title = $g['name_th'];
        if ($g['min_credits'] > 0) $title .= ' ('.iconv('UTF-8','cp874','ไม่น้อยกว่า ').$g['min_credits'].iconv('UTF-8','cp874',' หน่วยกิต').')';
        $pdf->Cell(0, 5, iconv('UTF-8','cp874//IGNORE',$title), 0, 1);

        if ($has_courses) {
            $pdf->SetX(8 + $indent);
            $pdf->SetFont('Courier', '', 7);
            $pdf->Cell(30, 3, iconv('UTF-8','cp874','รหัสวิชา'), 0, 0);
            $pdf->Cell(50, 3, iconv('UTF-8','cp874','ชื่อวิชา'), 0, 0);
            $pdf->Cell(12, 3, iconv('UTF-8','cp874','หน่วยกิต'), 0, 0, 'C');
            $pdf->Cell(10, 3, iconv('UTF-8','cp874','เกรด'), 0, 0, 'C');
            $pdf->Cell(18, 3, iconv('UTF-8','cp874','ประเภท'), 0, 1);

            foreach ($node['courses'] as $course) {
                $status_text = '';
                $grade_text = '';
                if (isset($course['_completed'])) {
                    $sc = $course['_completed'];
                    $status_text = iconv('UTF-8','cp874//IGNORE', $sc['course_type'] ?: ($sc['source_type'] == 'transfer' ? 'เทียบโอน' : 'เรียนแล้ว'));
                    $grade_text = $sc['grade'] ?: '-';
                }
                $name = mb_substr($course['name_th'], 0, 28, 'UTF-8');
                $pdf->SetX(8 + $indent);
                $pdf->SetFont('Courier', '', 8);
                $pdf->Cell(30, 4, iconv('UTF-8','cp874//IGNORE',$course['code']), 0, 0);
                $pdf->Cell(50, 4, iconv('UTF-8','cp874//IGNORE',$name), 0, 0);
                $pdf->Cell(12, 4, $course['credits'], 0, 0, 'C');
                $pdf->Cell(10, 4, $grade_text, 0, 0, 'C');
                $pdf->Cell(18, 4, $status_text, 0, 1);
            }
            $pdf->Ln(1);
        }

        if ($has_children) {
            renderPdfTree($node['children'], $pdf, $level + 1);
        }
    }
}
