<?php
$page_title = 'หลักสูตรเทคโนโลยีดิจิทัล (DT)';
require_once __DIR__ . '/../includes/functions.php';

if (isStudent()) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

require_once __DIR__ . '/../includes/header.php';

$curriculum = getDB()->prepare("SELECT * FROM curricula WHERE code = 'DT'");
$curriculum->execute();
$curriculum = $curriculum->fetch();

if (!$curriculum) {
    echo '<div class="alert alert-danger">ไม่พบข้อมูลหลักสูตร กรุณา import ข้อมูลก่อน</div>';
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

$tree = buildGroupTree($curriculum['id']);
$is_dbc = false;
?>
<div class="card">
    <div class="card-header bg-primary text-white">
        <h4 class="mb-0"><i class="bi bi-book"></i> หลักสูตรวิทยาศาสตรบัณฑิต สาขาวิชาเทคโนโลยีดิจิทัล (DT)</h4>
    </div>
    <div class="card-body">
        <div class="row mb-3">
            <div class="col-md-4"><strong>จำนวนหน่วยกิตรวม:</strong> <?= $curriculum['total_credits'] ?> หน่วยกิต</div>
        </div>
        <hr>
        <?php renderCurriculumTree($tree, $is_dbc); ?>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>

<?php
function renderCurriculumTree($nodes, $is_dbc, $level = 0) {
    $accent = $is_dbc ? 'success' : 'primary';
    foreach ($nodes as $node) {
        $g = $node['group'];
        $has_children = !empty($node['children']);
        $has_courses = !empty($node['courses']);

        echo '<div class="mb-3">';
        echo '<h' . (3 + $level) . ' class="text-' . ($level == 0 ? $accent : 'secondary') . '">';
        echo htmlspecialchars($g['name_th']);
        if ($g['min_credits'] > 0) {
            echo ' <small class="text-muted">(ไม่น้อยกว่า ' . $g['min_credits'] . ' หน่วยกิต)</small>';
        }
        echo '</h' . (3 + $level) . '>';

        if ($has_courses) {
            echo '<div class="table-responsive">';
            echo '<table class="table table-sm table-bordered">';
            echo '<thead class="table-light"><tr><th>รหัสวิชา</th><th>ชื่อวิชา</th><th>ชื่อวิชา (EN)</th><th>หน่วยกิต</th></tr></thead>';
            echo '<tbody>';
            foreach ($node['courses'] as $c) {
                echo '<tr class="course-item">';
                echo '<td><code>' . htmlspecialchars($c['code']) . '</code></td>';
                echo '<td>' . htmlspecialchars($c['name_th']) . '</td>';
                echo '<td><small class="text-muted">' . htmlspecialchars($c['name_en']) . '</small></td>';
                echo '<td><span class="badge-credit">' . $c['credits'] . '(' . $c['lecture_hours'] . '-' . $c['practice_hours'] . '-' . $c['self_study_hours'] . ')</span></td>';
                echo '</tr>';
            }
            echo '</tbody></table></div>';
        }

        if ($has_children) {
            echo '<div class="ms-' . ($level > 0 ? 3 : 0) . '">';
            renderCurriculumTree($node['children'], $is_dbc, $level + 1);
            echo '</div>';
        }

        echo '</div>';
    }
}
