<?php
$page_title = 'สรุปผลการเรียนแยกตามโครงสร้าง';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();

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

$summary = getStudentSummary($student_id);
$total_curriculum_credits = getTotalCurriculumCredits($student['curriculum_id']);
$transfer_credits_total = getTransferCreditsTotal($student_id);
$total_completed = getCompletedCreditsTotal($student_id);
$remaining = max(0, $total_curriculum_credits - $total_completed);
$pct = $total_curriculum_credits > 0 ? round(($total_completed / $total_curriculum_credits) * 100) : 0;

// ดึงข้อมูลชื่ออาจารย์ที่ปรึกษาจากระบบ
$advisor_name = '................................';
if (!empty($student['advisor_id'])) {
    $advisor = getUser($student['advisor_id']);
    if ($advisor) {
        $advisor_name = $advisor['name'];
    }
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<title>สรุปผลการเรียนแยกตามโครงสร้าง - <?= htmlspecialchars($student['student_code']) ?></title>
<style>
    @media print { .no-print { display: none; } body { font-family: 'TH Sarabun New', 'Leelawadee', 'Tahoma', sans-serif; } }
    body {
        font-family: 'TH Sarabun New', 'Leelawadee', 'Tahoma', sans-serif;
        font-size: 14px; padding: 20px; color: #333;
    }
    .header { text-align: center; border-bottom: 2px solid #333; padding-bottom: 10px; margin-bottom: 20px; }
    .header h1 { font-size: 22px; margin: 0; }
    .header h2 { font-size: 18px; margin: 5px 0; font-weight: normal; }
    .student-info { margin-bottom: 15px; }
    .student-info table { width: 100%; }
    .student-info td { padding: 2px 10px; }
    .credit-cards { display: flex; gap: 10px; margin-bottom: 15px; }
    .credit-card { flex: 1; padding: 8px; border-radius: 5px; text-align: center; font-size: 18px; }
    .section { margin-bottom: 15px; }
    .section-title { background: #0d6efd; color: white; padding: 5px 10px; font-size: 15px; font-weight: bold; }
    .subsection-title { background: #e9ecef; padding: 3px 10px; margin: 5px 0; font-size: 13px; font-weight: bold; color: #555; }
    .subsubsection-title { font-weight: bold; color: #666; margin: 3px 0; font-size: 12px; }
    table { width: 100%; border-collapse: collapse; margin: 5px 0; }
    th, td { border: 1px solid #ccc; padding: 3px 6px; text-align: left; font-size: 13px; }
    th { background: #f8f9fa; }
    .center { text-align: center; }
    .completed { background: #d4edda; }
    .transfer { background: #fff3cd; }
    .summary-row { background: #f0f0f0; font-weight: bold; }
    .footer { text-align: center; margin-top: 30px; padding-top: 10px; border-top: 1px solid #ccc; font-size: 12px; color: #666; }
    .btn-print { display: inline-block; padding: 8px 16px; background: #0d6efd; color: white; text-decoration: none; border-radius: 4px; margin-bottom: 15px; }
    .btn-print:hover { background: #0b5ed7; }
    .conclusion { text-align: center; font-size: 16px; margin: 15px 0; padding: 10px; border: 2px solid #28a745; border-radius: 5px; }
</style>
</head>
<body>
    <div class="no-print" style="margin-bottom:10px;">
        <a href="#" onclick="window.print();return false;" class="btn-print">🖨️ พิมพ์ / บันทึกเป็น PDF</a>
        <a href="../students/view.php?id=<?= $student_id ?>" class="btn-print" style="background:#6c757d;">⬅ กลับ</a>
    </div>

    <div class="header">
        <h1>สรุปผลการเรียน</h1>
        <h2>มหาวิทยาลัยตาปี</h2>
    </div>

    <div class="student-info">
        <table>
            <tr><td style="width:140px;"><strong>รหัสนักศึกษา:</strong></td><td><?= htmlspecialchars($student['student_code']) ?></td></tr>
            <tr><td><strong>ชื่อ-นามสกุล:</strong></td><td><?= htmlspecialchars($student['name_th']) ?> (<?= htmlspecialchars($student['name_en']) ?>)</td></tr>
            <tr><td><strong>สาขาวิชา:</strong></td><td><?= htmlspecialchars($student['curriculum_code']) ?> - <?= htmlspecialchars($student['curriculum_name']) ?></td></tr>
            <tr><td><strong>คณะ:</strong></td><td><?= htmlspecialchars($student['faculty'] ?: '-') ?></td></tr>
            <tr><td><strong>สถาบันที่จบ:</strong></td><td><?= htmlspecialchars($student['graduated_institution'] ?: '-') ?></td></tr>
            <tr><td><strong>ปีการศึกษา:</strong></td><td><?= $student['enrollment_year'] ?></td></tr>
        </table>
    </div>

    <div class="credit-cards">
        <div class="credit-card" style="background:#ffc107;">
            <strong><?= $transfer_credits_total ?></strong><br><small>หน่วยกิตเทียบโอน</small>
        </div>
        <div class="credit-card" style="background:#28a745;color:white;">
            <strong><?= $total_completed ?></strong><br><small>หน่วยกิตเรียนผ่านแล้ว</small>
        </div>
        <div class="credit-card" style="background:#0d6efd;color:white;">
            <strong><?= $remaining ?></strong><br><small>หน่วยกิตคงเหลือ</small>
        </div>
    </div>

    <div class="section">
        <div class="section-title">สรุปรายวิชาที่เรียนผ่านแล้วทั้งหมด (แยกตามโครงสร้างหลักสูตร)</div>
        <?php renderGroupedSummary($summary['groups']); ?>
        <table style="margin-top:10px;">
            <tr class="summary-row">
                <td colspan="2" class="center">รวมหน่วยกิตที่เรียนผ่านแล้วทั้งหมด</td>
                <td class="center"><?= $total_completed ?> หน่วยกิต</td><td colspan="4"></td>
            </tr>
        </table>
    </div>

    <div class="conclusion" style="border-color: <?= $remaining <= 0 ? '#28a745' : '#ffc107' ?>;">
        <?php if ($remaining <= 0): ?>
            <strong style="color:#28a745;">✓ ครบตามหลักสูตรแล้ว (<?= $total_completed ?> / <?= $total_curriculum_credits ?> หน่วยกิต)</strong>
        <?php else: ?>
            <strong>หน่วยกิตคงเหลือที่ต้องเรียน: <?= $remaining ?> หน่วยกิต (<?= $total_completed ?> / <?= $total_curriculum_credits ?> หน่วยกิต)</strong>
        <?php endif; ?>
    </div>

    <!-- ส่วนลงชื่อ 3 ช่องท้ายรายงาน -->
    <table style="width: 100%; border: none !important; margin-top: 50px; margin-bottom: 20px; page-break-inside: avoid;">
        <tr style="border: none !important;">
            <td style="width: 33%; text-align: center; border: none !important; padding: 10px; font-size: 14px; line-height: 1.8; vertical-align: top;">
                ............................................................<br>
                ( <?= htmlspecialchars($advisor_name) ?> )<br>
                อาจารย์ที่ปรึกษา<br>&nbsp;
            </td>
            <td style="width: 33%; text-align: center; border: none !important; padding: 10px; font-size: 14px; line-height: 1.8; vertical-align: top;">
                ............................................................<br>
                ( ............................................................ )<br>
                ประธานหลักสูตรสาขาวิชา<br><?= htmlspecialchars($student['curriculum_name']) ?>
            </td>
            <td style="width: 34%; text-align: center; border: none !important; padding: 10px; font-size: 14px; line-height: 1.8; vertical-align: top;">
                ............................................................<br>
                ( ............................................................ )<br>
                คณบดี<br><?= htmlspecialchars($student['faculty'] ?: 'คณะ................................') ?>
            </td>
        </tr>
    </table>

    <div class="footer">
        ระบบใบควบคุมผลการเรียน มหาวิทยาลัยตาปี<br>
        พิมพ์เมื่อ <?= date('d/m/Y H:i') ?> น.
    </div>
</body>
</html>

<?php
function renderGroupedSummary($nodes, $level = 0) {
    foreach ($nodes as $node) {
        $g = $node['group'];
        $has_completed = $node['completed_credits'] > 0;
        $has_courses = !empty($node['courses']);
        $has_children = !empty($node['children']);

        if (!$has_completed && !$has_children) continue;

        $style = $level == 0 ? 'section-title' : ($level == 1 ? 'subsection-title' : 'subsubsection-title');
        echo '<div style="margin-left:' . ($level * 10) . 'px;">';
        echo '<div class="' . $style . '">' . htmlspecialchars($g['name_th']);
        if ($g['min_credits'] > 0) echo ' (ไม่น้อยกว่า ' . $g['min_credits'] . ' หน่วยกิต)';
        if ($level == 0 && $has_completed) {
            echo ' <span style="font-weight:normal;font-size:12px;">— เรียนผ่านแล้ว ' . $node['completed_credits'] . ' หน่วยกิต</span>';
        }
        echo '</div>';

        if ($has_courses) {
            $group_total = 0;
            echo '<table style="table-layout: fixed; width: 100%;">';
            echo '<thead>';
            echo '<tr>';
            echo '<th class="center" style="width: 13%;">รหัสวิชา</th>';
            echo '<th style="width: 41%;">ชื่อวิชา</th>';
            echo '<th class="center" style="width: 10%;">หน่วยกิต</th>';
            echo '<th class="center" style="width: 8%;">เกรด</th>';
            echo '<th class="center" style="width: 10%;">ภาคเรียน</th>';
            echo '<th class="center" style="width: 10%;">ปีการศึกษา</th>';
            echo '<th class="center" style="width: 8%;">ประเภท</th>';
            echo '</tr>';
            echo '</thead>';
            echo '<tbody>';
            
            foreach ($node['courses'] as $course) {
                if (!isset($course['_completed'])) continue;
                $sc = $course['_completed'];
                $group_total += $sc['credits'];
                $type = htmlspecialchars($sc['course_type'] ?: ($sc['source_type'] == 'transfer' ? 'เทียบโอน' : 'เรียน'));
                $sem = $sc['semester'] ? 'ภาค ' . htmlspecialchars($sc['semester']) : '-';
                $yr = htmlspecialchars($sc['academic_year'] ?: '-');
                $row_class = $sc['source_type'] == 'transfer' ? 'transfer' : 'completed';
                
                echo '<tr class="' . $row_class . '">';
                echo '<td class="center"><code>' . htmlspecialchars($sc['course_code']) . '</code></td>';
                echo '<td>' . htmlspecialchars($sc['course_name_th']) . '</td>';
                echo '<td class="center">' . number_format($sc['credits'], 1) . '</td>';
                echo '<td class="center bold">' . htmlspecialchars($sc['grade'] ?: '-') . '</td>';
                echo '<td class="center">' . $sem . '</td>';
                echo '<td class="center">' . $yr . '</td>';
                echo '<td class="center">' . $type . '</td>';
                echo '</tr>';
            }
            
            echo '<tr class="summary-row">';
            echo '<td colspan="2" class="right bold" style="text-align: right; padding-right: 15px;">รวมหน่วยกิต</td>';
            echo '<td class="center bold">' . number_format($group_total, 1) . '</td>';
            echo '<td colspan="4"></td>';
            echo '</tr>';
            echo '</tbody></table>';
        }

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

        echo '</div>';
    }
}
