<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AscImportModel;
use App\Models\AscPeriodModel;
use App\Models\AscSubjectModel;
use App\Models\AscTeacherModel;
use App\Models\AscClassModel;
use App\Models\AscScheduleModel;
use App\Models\SchoolSettingModel;

class AscSchedule extends BaseController
{
    protected $importModel;
    protected $periodModel;
    protected $subjectModel;
    protected $teacherModel;
    protected $classModel;
    protected $scheduleModel;

    public function __construct()
    {
        $this->importModel   = new AscImportModel();
        $this->periodModel   = new AscPeriodModel();
        $this->subjectModel  = new AscSubjectModel();
        $this->teacherModel  = new AscTeacherModel();
        $this->classModel    = new AscClassModel();
        $this->scheduleModel = new AscScheduleModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    // ── RESOLVE IMPORT ID ──────────────────────────────────────────────────
    // Ambil import_id dari query string atau pakai yang aktif
    private function resolveImportId()
    {
        $importId = (int) $this->request->getGet('import_id');

        if ($importId) {
            return $importId;
        }

        $active = $this->importModel->getActive();
        return $active ? $active['id'] : null;
    }

    // ── DATA UMUM UNTUK VIEW ───────────────────────────────────────────────
    // Data yang dipakai bersama di semua view jadwal
    private function getCommonData($importId)
    {
        return [
            'import'       => $this->importModel->find($importId),
            'imports'      => $this->importModel->getAll(),
            'periods'      => $this->periodModel->getByImport($importId),
            'teachers'     => $this->teacherModel->getByImport($importId),
            'grade_levels' => $this->classModel->getGradeLevels($importId),
            'days'         => $this->scheduleModel->getDayList($importId),
        ];
    }

    // ══════════════════════════════════════════════════════════════════════
    // JADWAL KESELURUHAN
    // ══════════════════════════════════════════════════════════════════════

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId = $this->resolveImportId();

        if (!$importId) {
            return redirect()->to('/asc-import')
                ->with('error', 'Belum ada jadwal aktif. Silakan import jadwal terlebih dahulu.');
        }

        // Filter grade level (default: semua)
        $gradeLevel = $this->request->getGet('grade') ? (int) $this->request->getGet('grade') : null;

        // Ambil semua kelas sesuai filter
        $classes = $gradeLevel
            ? $this->classModel->getByGrade($importId, $gradeLevel)
            : $this->classModel->getByImport($importId);

        // Ambil grid data
        $gridData = $this->scheduleModel->getGridData($importId, $gradeLevel);

        $data = array_merge($this->getCommonData($importId), [
            'title'       => 'Jadwal Keseluruhan',
            'import_id'   => $importId,
            'grade_level' => $gradeLevel,
            'classes'     => $classes,
            'grid_data'   => $gridData,
        ]);

        return view('asc/schedule/index', $data);
    }

    // ══════════════════════════════════════════════════════════════════════
    // JADWAL PER KELAS
    // ══════════════════════════════════════════════════════════════════════

    public function byClass()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId   = $this->resolveImportId();
        $classAscId = $this->request->getGet('class_id');

        if (!$importId) {
            return redirect()->to('/asc-import')
                ->with('error', 'Belum ada jadwal aktif.');
        }

        // Default: kelas pertama
        $classes = $this->classModel->getByImport($importId);
        if (!$classAscId && !empty($classes)) {
            $classAscId = $classes[0]['asc_id'];
        }

        $scheduleData = $classAscId
            ? $this->scheduleModel->getByClass($importId, $classAscId)
            : [];

        // Info kelas yang dipilih
        $selectedClass = null;
        foreach ($classes as $c) {
            if ($c['asc_id'] === $classAscId) {
                $selectedClass = $c;
                break;
            }
        }

        $data = array_merge($this->getCommonData($importId), [
            'title'          => 'Jadwal Per Kelas',
            'import_id'      => $importId,
            'classes'        => $classes,
            'class_asc_id'   => $classAscId,
            'selected_class' => $selectedClass,
            'schedule_data'  => $scheduleData,
        ]);

        return view('asc/schedule/by_class', $data);
    }

    // ══════════════════════════════════════════════════════════════════════
    // JADWAL PER GURU
    // ══════════════════════════════════════════════════════════════════════

    public function byTeacher()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId      = $this->resolveImportId();
        $teacherAscId  = $this->request->getGet('teacher_id');

        if (!$importId) {
            return redirect()->to('/asc-import')
                ->with('error', 'Belum ada jadwal aktif.');
        }

        // Default: guru pertama
        $teachers = $this->teacherModel->getByImport($importId);
        if (!$teacherAscId && !empty($teachers)) {
            $teacherAscId = $teachers[0]['asc_id'];
        }

        $scheduleData = $teacherAscId
            ? $this->scheduleModel->getByTeacher($importId, $teacherAscId)
            : [];

        // Info guru yang dipilih
        $selectedTeacher = null;
        foreach ($teachers as $t) {
            if ($t['asc_id'] === $teacherAscId) {
                $selectedTeacher = $t;
                break;
            }
        }

        // Hitung total jam guru ini
        $totalHours = 0;
        foreach ($scheduleData as $day) {
            $totalHours += count($day);
        }

        $data = array_merge($this->getCommonData($importId), [
            'title'           => 'Jadwal Per Guru',
            'import_id'       => $importId,
            'teacher_asc_id'  => $teacherAscId,
            'selected_teacher'=> $selectedTeacher,
            'schedule_data'   => $scheduleData,
            'total_hours'     => $totalHours,
        ]);

        return view('asc/schedule/by_teacher', $data);
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT EXCEL — KESELURUHAN
    // ══════════════════════════════════════════════════════════════════════

    public function exportExcel()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId   = $this->resolveImportId();
        $gradeLevel = $this->request->getGet('grade') ? (int) $this->request->getGet('grade') : null;

        if (!$importId) {
            return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        }

        $import   = $this->importModel->find($importId);
        $classes  = $gradeLevel
            ? $this->classModel->getByGrade($importId, $gradeLevel)
            : $this->classModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $gridData = $this->scheduleModel->getGridData($importId, $gradeLevel);

        $this->generateExcel($import, $classes, $periods, $days, $teachers, $gridData, $gradeLevel);
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT EXCEL — PER KELAS
    // ══════════════════════════════════════════════════════════════════════

    public function exportClassExcel()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId   = $this->resolveImportId();
        $classAscId = $this->request->getGet('class_id');

        if (!$importId || !$classAscId) {
            return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        }

        $import       = $this->importModel->find($importId);
        $periods      = $this->periodModel->getByImport($importId);
        $days         = $this->scheduleModel->getDayList($importId);
        $teachers     = $this->teacherModel->getByImport($importId);
        $scheduleData = $this->scheduleModel->getByClass($importId, $classAscId);

        // Ambil info kelas
        $classes    = $this->classModel->getByImport($importId);
        $classInfo  = null;
        foreach ($classes as $c) {
            if ($c['asc_id'] === $classAscId) {
                $classInfo = $c;
                break;
            }
        }

        $this->generateClassExcel($import, $classInfo, $periods, $days, $teachers, $scheduleData);
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT EXCEL — PER GURU
    // ══════════════════════════════════════════════════════════════════════

    public function exportTeacherExcel()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId     = $this->resolveImportId();
        $teacherAscId = $this->request->getGet('teacher_id');

        if (!$importId || !$teacherAscId) {
            return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        }

        $import       = $this->importModel->find($importId);
        $periods      = $this->periodModel->getByImport($importId);
        $days         = $this->scheduleModel->getDayList($importId);
        $scheduleData = $this->scheduleModel->getByTeacher($importId, $teacherAscId);

        // Ambil info guru
        $teachers      = $this->teacherModel->getByImport($importId);
        $teacherInfo   = null;
        foreach ($teachers as $t) {
            if ($t['asc_id'] === $teacherAscId) {
                $teacherInfo = $t;
                break;
            }
        }

        $this->generateTeacherExcel($import, $teacherInfo, $periods, $days, $scheduleData, $teachers);
    }

    // ── GENERATE EXCEL KESELURUHAN (UPDATE) ─────────────────────────────────

    private function generateExcel($import, $classes, $periods, $days, $teachers, $gridData, $gradeLevel = null, $showTime = true)
    {
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $spreadsheet->getProperties()
            ->setTitle('Jadwal Pelajaran ' . $import['name'])
            ->setCreator('aSc Timetables Importer');

        // Ambil nama sekolah dari settings
        $schoolSettingModel = new \App\Models\SchoolSettingModel();
        $schoolSettings = $schoolSettingModel->getSettings();
        $schoolName = $schoolSettings['school_name'] ?? 'Sekolah';

        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Jadwal');

        $Coord = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::class;

        // Warna lookup: short_code => hex tanpa #
        $teacherColors = [];
        foreach ($teachers as $t) {
            $teacherColors[$t['short_code']] = ltrim($t['color'], '#');
        }

        $colFirst  = 3;  // kolom C = kelas pertama
        $totalCols = $colFirst + count($classes) - 1;
        $lastColStr = $Coord::stringFromColumnIndex($totalCols);

        // ── Baris 1: Nama Sekolah ───────────────────────────────────────────
        $sheet->mergeCells("A1:{$lastColStr}1");
        $sheet->setCellValue('A1', strtoupper($schoolName));
        $sheet->getStyle('A1')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 16],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
        ]);
        $sheet->getRowDimension(1)->setRowHeight(28);

        // ── Baris 2: Judul ───────────────────────────────────────────────
        $gradeSuffix2 = $gradeLevel ? " — Kelas {$gradeLevel}" : '';
        $sheet->mergeCells("A2:{$lastColStr}2");
        $sheet->setCellValue('A2', 'JADWAL PELAJARAN ' . strtoupper($import['name']) . $gradeSuffix2);
        $sheet->getStyle('A2')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 14],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
        ]);
        $sheet->getRowDimension(2)->setRowHeight(24);

        // ── Baris 3: Tahun ajaran ────────────────────────────────────────
        $sheet->mergeCells("A3:{$lastColStr}3");
        $sheet->setCellValue('A3', 'Tahun Ajaran ' . $import['academic_year'] . ' — Semester ' . $import['semester']);
        $sheet->getStyle('A3')->applyFromArray([
            'font'      => ['size' => 10],
            'alignment' => ['horizontal' => 'center'],
        ]);

        // ── Baris 5: Header kolom ────────────────────────────────────────
        $headerStyle = [
            'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
            'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
        ];
        $sheet->setCellValue('A5', 'Hari');
        $sheet->setCellValue('B5', 'Jam');
        $sheet->getStyle('A5:B5')->applyFromArray($headerStyle);
        $sheet->getColumnDimension('A')->setWidth(9);
        $sheet->getColumnDimension('B')->setWidth(8);

        foreach ($classes as $idx => $class) {
            $col = $Coord::stringFromColumnIndex($colFirst + $idx);
            $sheet->setCellValue($col . '5', $class['name']);
            $sheet->getStyle($col . '5')->applyFromArray($headerStyle);
            $sheet->getColumnDimension($col)->setWidth(11);
        }
        $sheet->getRowDimension(5)->setRowHeight(22);

        // ── Baris data ───────────────────────────────────────────────────
        $dataRow = 6;
        foreach ($days as $day) {
            $dayNum      = $day['day_number'];
            $dayStartRow = $dataRow;

            foreach ($periods as $period) {
                $pNum = $period['period_number'];

                // Kolom Hari
                $sheet->setCellValue('A' . $dataRow, strtoupper(substr($day['day_name'], 0, 3)));
                $sheet->getStyle('A' . $dataRow)->applyFromArray([
                    'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
                    'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
                    'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
                    'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
                ]);

                // Kolom Jam
                $sheet->setCellValue('B' . $dataRow, $showTime ? ($pNum . "\n" . substr($period['start_time'], 0, 5)) : ('Jam ' . $pNum));
                $sheet->getStyle('B' . $dataRow)->applyFromArray([
                    'font'      => ['bold' => true, 'size' => 8, 'color' => ['rgb' => 'FFFFFF']],
                    'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '2d4f7c']],
                    'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
                    'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
                ]);

                // Sel per kelas
                foreach ($classes as $idx => $class) {
                    $col  = $Coord::stringFromColumnIndex($colFirst + $idx);
                    $addr = $col . $dataRow;
                    $slot = $gridData[$dayNum][$pNum][$class['asc_id']] ?? null;

                    if ($slot) {
                        $displayTeacherCode = $slot['display_teacher_code'] ?? $slot['teacher_code'];
                        $bg = $teacherColors[$displayTeacherCode] ?? 'FFFFFF';
                        $fg = $this->getExcelTextColor($bg);
                        $displayCode = $slot['display_code'] ?? $slot['subject_code'];
                        $sheet->setCellValue($addr, $displayCode . "\n[" . $displayTeacherCode . "]");
                        $sheet->getStyle($addr)->applyFromArray([
                            'font'      => ['bold' => true, 'size' => 8, 'color' => ['rgb' => $fg]],
                            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bg]],
                            'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
                            'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                        ]);
                    } else {
                        $sheet->getStyle($addr)->applyFromArray([
                            'fill'    => ['fillType' => 'solid', 'startColor' => ['rgb' => 'F5F5F5']],
                            'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'DDDDDD']]],
                        ]);
                    }
                }

                $sheet->getRowDimension($dataRow)->setRowHeight(30);
                $dataRow++;
            }

            // Merge kolom Hari untuk semua periode hari ini
            if (count($periods) > 1) {
                $sheet->mergeCells('A' . $dayStartRow . ':A' . ($dataRow - 1));
            }

            // Garis pemisah antar hari
            $sheet->getRowDimension($dataRow)->setRowHeight(4);
            $sheet->mergeCells("A{$dataRow}:{$lastColStr}{$dataRow}");
            $sheet->getStyle("A{$dataRow}:{$lastColStr}{$dataRow}")->applyFromArray([
                'fill' => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
            ]);
            $dataRow++;
        }

        // ── Legenda guru di bawah (dengan layout grid rapi) ─────────────────
        $dataRow++;
        $sheet->mergeCells("A{$dataRow}:{$lastColStr}{$dataRow}");
        $sheet->setCellValue('A' . $dataRow, 'KETERANGAN KODE GURU');
        $sheet->getStyle('A' . $dataRow)->applyFromArray([
            'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 10],
            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
            'alignment' => ['horizontal' => 'center'],
        ]);
        $sheet->getRowDimension($dataRow)->setRowHeight(18);
        $dataRow++;

        // Hitung berapa kolom untuk legenda (maksimal 4 kolom)
        $legendCols = 4;
        $legendPerCol = ceil(count($teachers) / $legendCols);
        $legendStartRow = $dataRow;

        // Header legenda per kolom
        for ($col = 0; $col < $legendCols; $col++) {
            $colLetter = $Coord::stringFromColumnIndex($col + 1);
            $sheet->setCellValue($colLetter . $dataRow, 'Kode');
            $sheet->setCellValue($Coord::stringFromColumnIndex($col + 2) . $dataRow, 'Nama Guru');
            $sheet->mergeCells($Coord::stringFromColumnIndex($col + 2) . $dataRow . ':' . $Coord::stringFromColumnIndex($col + 3) . $dataRow);
            $sheet->getStyle($colLetter . $dataRow . ':' . $Coord::stringFromColumnIndex($col + 3) . $dataRow)->applyFromArray([
                'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '2d4f7c']],
                'alignment' => ['horizontal' => 'center'],
                'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
            ]);
        }
        $dataRow++;

        // Isi data legenda dengan layout grid (4 kolom)
        $teacherArray = array_values($teachers);
        for ($i = 0; $i < $legendPerCol; $i++) {
            for ($col = 0; $col < $legendCols; $col++) {
                $idx = $i + ($col * $legendPerCol);
                if (!isset($teacherArray[$idx])) continue;

                $teacher = $teacherArray[$idx];
                $bg = ltrim($teacher['color'], '#');
                $fg = $this->getExcelTextColor($bg);
                $colLetter = $Coord::stringFromColumnIndex($col * 4 + 1);
                
                $sheet->setCellValue($colLetter . $dataRow, $teacher['short_code']);
                $sheet->setCellValue($Coord::stringFromColumnIndex($col * 4 + 2) . $dataRow, $teacher['name']);
                $sheet->mergeCells($Coord::stringFromColumnIndex($col * 4 + 2) . $dataRow . ':' . $Coord::stringFromColumnIndex($col * 4 + 3) . $dataRow);
                
                $sheet->getStyle($colLetter . $dataRow)->applyFromArray([
                    'font'      => ['bold' => true, 'color' => ['rgb' => $fg], 'size' => 9],
                    'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bg]],
                    'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
                    'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                ]);
                $sheet->getStyle($Coord::stringFromColumnIndex($col * 4 + 2) . $dataRow . ':' . $Coord::stringFromColumnIndex($col * 4 + 3) . $dataRow)->applyFromArray([
                    'font'    => ['size' => 9],
                    'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                    'alignment' => ['vertical' => 'center'],
                ]);
            }
            $dataRow++;
        }

        // Freeze: beku header atas + kolom Hari & Jam
        $sheet->freezePane('C6');

        // Output
        $gradeSuffix = $gradeLevel ? "_kelas{$gradeLevel}" : '_semua';
        $filename    = 'jadwal' . $gradeSuffix . '_' . date('Ymd') . '.xlsx';

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT PDF — KESELURUHAN (INDEX)
    // ══════════════════════════════════════════════════════════════════════

    public function exportPdf()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId   = $this->resolveImportId();
        $gradeLevel = $this->request->getGet('grade') ? (int) $this->request->getGet('grade') : null;

        if (!$importId) {
            return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        }

        $import   = $this->importModel->find($importId);
        $classes  = $gradeLevel
            ? $this->classModel->getByGrade($importId, $gradeLevel)
            : $this->classModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $gridData = $this->scheduleModel->getGridData($importId, $gradeLevel);

        // Generate HTML untuk PDF
        $html = $this->buildSchedulePdfHtml($import, $classes, $periods, $days, $teachers, $gridData, $gradeLevel);

        $mpdf = new \Mpdf\Mpdf([
            'orientation' => 'L',
            'margin_top'  => 10,
            'margin_bottom' => 10,
            'margin_left' => 8,
            'margin_right' => 8,
            'default_font_size' => 9,
            'default_font' => 'dejavusans',
        ]);

        $mpdf->WriteHTML($html);

        $gradeSuffix = $gradeLevel ? "_kelas{$gradeLevel}" : '_semua';
        $filename    = 'jadwal' . $gradeSuffix . '_' . date('Ymd') . '.pdf';
        $mpdf->Output($filename, 'D');
        exit;
    }

    private function buildSchedulePdfHtml($import, $classes, $periods, $days, $teachers, $gridData, $gradeLevel = null, $showTime = true)
        {
            // Ambil nama sekolah dari settings
            $schoolSettingModel = new \App\Models\SchoolSettingModel();
            $schoolSettings = $schoolSettingModel->getSettings();
            $schoolName = $schoolSettings['school_name'] ?? 'Sekolah';

            $gradeSuffix = $gradeLevel ? " — Kelas {$gradeLevel}" : '';

            $html = '
            <style>
                body { font-family: dejavusans, sans-serif; font-size: 8pt; margin: 0; padding: 0; }
                h1 { font-size: 12pt; margin: 0 0 2px; text-align: center; }
                h2 { font-size: 10pt; margin: 0 0 2px; text-align: center; }
                h4 { font-size: 8.5pt; margin: 0 0 6px; text-align: center; color: #555; }
                table { width: 100%; border-collapse: collapse; margin-bottom: 8px; }
                th {
                    background: #1e3a5f; color: #fff; font-size: 8pt;
                    padding: 4px 3px; text-align: center; border: 1px solid #555;
                }
                td {
                    padding: 4px 3px; text-align: center;
                    border: 1px solid #ccc; font-size: 7.5pt;
                    vertical-align: middle;
                }
                .td-hari-separator {
                    background: #1e3a5f; color: #fff;
                    font-weight: bold; font-size: 8.5pt;
                    text-align: left;
                    padding: 5px 8px;
                }
                .td-jam {
                    background: #f0f4f8; font-weight: bold;
                }
                .td-empty { background: #fafafa; }
                .legend-title {
                    background: #1e3a5f; color: #fff;
                    font-weight: bold; text-align: center;
                    padding: 5px 8px;
                    font-size: 9.5pt;
                    margin-top: 12px;
                }
                .legend-table {
                    width: 100%;
                    border-collapse: collapse;
                    margin-top: 2px;
                }
                .legend-table th, .legend-table td {
                    border: 1px solid #aaa;
                    padding: 4px 6px;
                    font-size: 9pt;
                }
                .legend-table th {
                    background: #2d4f7c;
                    color: #fff;
                    text-align: center;
                }
                .legend-table .code-cell {
                    text-align: center;
                    font-weight: bold;
                    width: 35px;
                }
                .legend-table .name-cell {
                    text-align: left;
                }
                tr { page-break-inside: avoid; }
                .clearfix { clear: both; }
            </style>';

            // Header
            $html .= '<h1>' . strtoupper(htmlspecialchars($schoolName)) . '</h1>';
            $html .= '<h2>JADWAL PELAJARAN ' . strtoupper(htmlspecialchars($import['name'])) . $gradeSuffix . '</h2>';
            $html .= '<h4>Tahun Ajaran ' . htmlspecialchars($import['academic_year']) . ' — Semester ' . htmlspecialchars($import['semester']) . '</h4>';

            // Tabel jadwal
            $html .= '<table>';
            
            // Header kelas
            $html .= '<thead>';
            $html .= '<tr>';
            $html .= '<th style="width:6%">Jam</th>';
            foreach ($classes as $class) {
                $html .= '<th style="width:' . round(94 / count($classes), 1) . '%">' . htmlspecialchars($class['name']) . '</th>';
            }
            $html .= '</tr>';
            $html .= '</thead>';

            $html .= '<tbody>';
            foreach ($days as $dayIdx => $day) {
                $dayNum = $day['day_number'];
                $dayName = $day['day_name'];
                $colspan = count($classes) + 1;

                // Day name header separator row (prevents rowspan split bugs)
                $html .= '<tr style="page-break-inside: avoid; page-break-after: avoid;">';
                $html .= '<td colspan="' . $colspan . '" class="td-hari-separator">';
                $html .= strtoupper($dayName);
                $html .= '</td>';
                $html .= '</tr>';

                foreach ($periods as $pIdx => $period) {
                    $pNum = $period['period_number'];

                    $html .= '<tr style="page-break-inside: avoid;">';
                    
                    $html .= '<td class="td-jam">';
                    $html .= '<strong>' . $pNum . '</strong>';
                    if ($showTime) {
                        $html .= '<br><span style="font-size:6pt">' . substr($period['start_time'], 0, 5) . '</span>';
                    }
                    $html .= '</td>';

                    foreach ($classes as $class) {
                        $slot = $gridData[$dayNum][$pNum][$class['asc_id']] ?? null;
                        
                        if ($slot) {
                            $bg = ltrim($slot['teacher_color'], '#');
                            $fg = $this->getExcelTextColor($bg);
                            $html .= '<td style="background:#' . $bg . ';color:#' . $fg . ';font-weight:bold">';
                            $displayCode = $slot['display_code'] ?? $slot['subject_code'];
                            $displayTeacherCode = $slot['display_teacher_code'] ?? $slot['teacher_code'];
                            $html .= htmlspecialchars($displayCode) . '<br>';
                            $html .= '<span style="font-size:6pt">[' . htmlspecialchars($displayTeacherCode) . ']</span>';
                            $html .= '</td>';
                        } else {
                            $html .= '<td class="td-empty">&nbsp;</td>';
                        }
                    }
                    
                    $html .= '</tr>';
                }

                // Spacing spacer between days
                if ($dayIdx < count($days) - 1) {
                    $html .= '<tr><td colspan="' . $colspan . '" style="height:3px;background:#f0f4f8;padding:0;border:none"></td></tr>';
                }
                $html .= '</tbody>';
            }
            $html .= '</table>';

            // ── LEGENDA GURU (GRID 4 KOLOM dengan struktur tabel yang benar) ─────
            $html .= '<div class="legend-title">KETERANGAN KODE GURU</div>';
            
            // Buat array guru dalam grid 4 kolom
            $teacherArray = array_values($teachers);
            $legendCols = 4;
            $legendRows = ceil(count($teacherArray) / $legendCols);
            
            // Buat matriks 2D untuk grid
            $grid = [];
            for ($row = 0; $row < $legendRows; $row++) {
                for ($col = 0; $col < $legendCols; $col++) {
                    $idx = $row + ($col * $legendRows);
                    if (isset($teacherArray[$idx])) {
                        $grid[$row][$col] = $teacherArray[$idx];
                    } else {
                        $grid[$row][$col] = null;
                    }
                }
            }
            
            $html .= '<table class="legend-table">';
            
            // Header tabel legend
            $html .= '<tr>';
            for ($col = 0; $col < $legendCols; $col++) {
                $html .= '<th style="width:6%">Kode</th>';
                $html .= '<th style="width:19%">Nama Guru</th>';
            }
            $html .= '</tr>';
            
            // Isi data legend
            for ($row = 0; $row < $legendRows; $row++) {
                $html .= '<tr>';
                for ($col = 0; $col < $legendCols; $col++) {
                    $teacher = $grid[$row][$col] ?? null;
                    if ($teacher) {
                        $bg = ltrim($teacher['color'], '#');
                        $fg = $this->getExcelTextColor($bg);
                        $html .= '<td class="code-cell" style="background:#' . $bg . ';color:#' . $fg . ';font-weight:bold">';
                        $html .= htmlspecialchars($teacher['short_code']);
                        $html .= '</td>';
                        $html .= '<td class="name-cell" style="background:#' . $bg . '20">';
                        $html .= htmlspecialchars($teacher['name']);
                        $html .= '</td>';
                    } else {
                        $html .= '<td class="code-cell"> </td>';
                        $html .= '<td class="name-cell"> </td>';
                    }
                }
                $html .= '</tr>';
            }
            
            $html .= '</table>';

            return $html;
        }

    // ── Write satu sheet (satu hari) ───────────────────────────────────────



    // ── Write sheet legenda guru ───────────────────────────────────────────



    // ── Generate Excel per kelas ───────────────────────────────────────────

    private function generateClassExcel($import, $classInfo, $periods, $days, $teachers, $scheduleData, $showTime = true)
    {
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Jadwal ' . ($classInfo['name'] ?? 'Kelas'));

        // Ambil nama sekolah
        $schoolSettingModel = new \App\Models\SchoolSettingModel();
        $schoolSettings = $schoolSettingModel->getSettings();
        $schoolName = $schoolSettings['school_name'] ?? 'Sekolah';

        $Coord = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::class;

        // Warna guru
        $teacherColors = [];
        foreach ($teachers as $t) {
            $teacherColors[$t['short_code']] = ltrim($t['color'], '#');
        }

        $colDays = count($days);
        $lastDataCol = $colDays + 1;
        $lastColStr  = $Coord::stringFromColumnIndex($lastDataCol);

        // ── Page Setup A4 Landscape ──────────────────────────────────────────
        $spreadsheet->getActiveSheet()->getPageSetup()
            ->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4)
            ->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
        
        // Set margin
        $spreadsheet->getActiveSheet()->getPageMargins()
            ->setTop(0.5)
            ->setBottom(0.5)
            ->setLeft(0.5)
            ->setRight(0.5);

        // ── Baris 1: Nama Sekolah ───────────────────────────────────────────
        $sheet->mergeCells("A1:{$lastColStr}1");
        $sheet->setCellValue('A1', strtoupper($schoolName));
        $sheet->getStyle('A1')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 14],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
        ]);
        $sheet->getRowDimension(1)->setRowHeight(24);

        // ── Baris 2: Judul ──────────────────────────────────────────────────
        $sheet->mergeCells("A2:{$lastColStr}2");
        $sheet->setCellValue('A2', 'JADWAL PELAJARAN KELAS ' . strtoupper($classInfo['name'] ?? ''));
        $sheet->getStyle('A2')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 12],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
        ]);
        $sheet->getRowDimension(2)->setRowHeight(22);

        // ── Baris 3: Tahun ajaran ───────────────────────────────────────────
        $sheet->mergeCells("A3:{$lastColStr}3");
        $sheet->setCellValue('A3', $import['academic_year'] . ' — Semester ' . $import['semester']);
        $sheet->getStyle('A3')->applyFromArray([
            'font'      => ['size' => 9],
            'alignment' => ['horizontal' => 'center'],
        ]);

        // ── Baris 5: Header (Jam di kiri, Hari sebagai kolom) ────────────────
        $headerStyle = [
            'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
            'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
        ];

        $sheet->setCellValue('A5', 'Jam');
        $sheet->getStyle('A5')->applyFromArray($headerStyle);
        $sheet->getColumnDimension('A')->setWidth(14);

        foreach ($days as $idx => $day) {
            $col = $Coord::stringFromColumnIndex($idx + 2);
            $sheet->setCellValue($col . '5', $day['day_name']);
            $sheet->getStyle($col . '5')->applyFromArray($headerStyle);
            $sheet->getColumnDimension($col)->setWidth(12);
        }
        $sheet->getRowDimension(5)->setRowHeight(22);

        // ── Baris data (setiap baris = satu jam) ─────────────────────────────
        $dataRow = 6;
        $usedTeachers = [];

        foreach ($periods as $period) {
            $pNum = $period['period_number'];
            
            // Kolom Jam
            $sheet->setCellValue('A' . $dataRow, $showTime ? ($pNum . "\n(" . substr($period['start_time'], 0, 5) . '-' . substr($period['end_time'], 0, 5) . ")") : ('Jam ' . $pNum));
            $sheet->getStyle('A' . $dataRow)->applyFromArray([
                'font'      => ['bold' => true, 'size' => 9, 'color' => ['rgb' => 'FFFFFF']],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '2d4f7c']],
                'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
                'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
            ]);

            // Kolom per Hari
            foreach ($days as $idx => $day) {
                $col = $Coord::stringFromColumnIndex($idx + 2);
                $addr = $col . $dataRow;
                $slot = $scheduleData[$day['day_number']][$pNum] ?? null;

                if ($slot) {
                    $displayTeacherCode = $slot['display_teacher_code'] ?? $slot['teacher_code'];
                    $bg = $teacherColors[$displayTeacherCode] ?? 'FFFFFF';
                    $fg = $this->getExcelTextColor($bg);
                    $displayCode = $slot['display_code'] ?? $slot['subject_code'];
                    $sheet->setCellValue($addr, $displayCode . "\n[" . $displayTeacherCode . "]");
                    $sheet->getStyle($addr)->applyFromArray([
                        'font'      => ['bold' => true, 'size' => 9, 'color' => ['rgb' => $fg]],
                        'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bg]],
                        'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
                        'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                    ]);
                    $usedTeachers[$displayTeacherCode] = [
                        'teacher_code' => $displayTeacherCode,
                        'teacher_name' => $slot['display_teacher_name'] ?? $slot['teacher_name'],
                        'teacher_color' => $slot['teacher_color']
                    ];
                } else {
                    $sheet->getStyle($addr)->applyFromArray([
                        'fill'    => ['fillType' => 'solid', 'startColor' => ['rgb' => 'FAFAFA']],
                        'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'DDDDDD']]],
                    ]);
                }
            }

            $sheet->getRowDimension($dataRow)->setRowHeight(32);
            $dataRow++;
        }

        // ── Legenda guru (2 kolom saja, lebih rapi) ──────────────────────────
        if (!empty($usedTeachers)) {
            $dataRow++;
            $sheet->mergeCells("A{$dataRow}:{$lastColStr}{$dataRow}");
            $sheet->setCellValue('A' . $dataRow, 'KETERANGAN KODE GURU');
            $sheet->getStyle('A' . $dataRow)->applyFromArray([
                'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 10],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
                'alignment' => ['horizontal' => 'center'],
            ]);
            $sheet->getRowDimension($dataRow)->setRowHeight(20);
            $dataRow++;

            // Filter guru yang digunakan
            $usedTeacherList = array_values($usedTeachers);
            
            // 2 kolom legenda
            $legendCols = 2;
            $legendRows = ceil(count($usedTeacherList) / $legendCols);
            
            // Header legenda (2 kolom)
            for ($col = 0; $col < $legendCols; $col++) {
                $colLetter = $Coord::stringFromColumnIndex($col * 3 + 1);
                $sheet->setCellValue($colLetter . $dataRow, 'Kode');
                $sheet->setCellValue($Coord::stringFromColumnIndex($col * 3 + 2) . $dataRow, 'Nama Guru');
                $sheet->mergeCells($Coord::stringFromColumnIndex($col * 3 + 2) . $dataRow . ':' . $Coord::stringFromColumnIndex($col * 3 + 2) . $dataRow);
                $sheet->getStyle($colLetter . $dataRow . ':' . $Coord::stringFromColumnIndex($col * 3 + 2) . $dataRow)->applyFromArray([
                    'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
                    'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '2d4f7c']],
                    'alignment' => ['horizontal' => 'center'],
                    'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
                ]);
            }
            $dataRow++;

            // Isi data legenda
            $teacherArray = $usedTeacherList;
            for ($i = 0; $i < $legendRows; $i++) {
                // Kolom 1
                $idx1 = $i;
                if (isset($teacherArray[$idx1])) {
                    $teacher = $teacherArray[$idx1];
                    $bg = ltrim($teacher['teacher_color'] ?? '#CCCCCC', '#');
                    $fg = $this->getExcelTextColor($bg);
                    $sheet->setCellValue('A' . $dataRow, $teacher['teacher_code']);
                    $sheet->setCellValue('B' . $dataRow, $teacher['teacher_name']);
                    $sheet->getStyle('A' . $dataRow)->applyFromArray([
                        'font'      => ['bold' => true, 'color' => ['rgb' => $fg], 'size' => 9],
                        'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bg]],
                        'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
                        'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                    ]);
                    $sheet->getStyle('B' . $dataRow)->applyFromArray([
                        'font'    => ['size' => 9],
                        'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                        'alignment' => ['vertical' => 'center'],
                    ]);
                } else {
                    $sheet->setCellValue('A' . $dataRow, '');
                    $sheet->setCellValue('B' . $dataRow, '');
                    $sheet->getStyle('A' . $dataRow . ':B' . $dataRow)->applyFromArray([
                        'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'DDDDDD']]],
                    ]);
                }
                
                // Kolom 2
                $idx2 = $i + $legendRows;
                if (isset($teacherArray[$idx2])) {
                    $teacher = $teacherArray[$idx2];
                    $bg = ltrim($teacher['teacher_color'] ?? '#CCCCCC', '#');
                    $fg = $this->getExcelTextColor($bg);
                    $colLetterD = $Coord::stringFromColumnIndex(4);
                    $colLetterE = $Coord::stringFromColumnIndex(5);
                    $sheet->setCellValue($colLetterD . $dataRow, $teacher['teacher_code']);
                    $sheet->setCellValue($colLetterE . $dataRow, $teacher['teacher_name']);
                    $sheet->getStyle($colLetterD . $dataRow)->applyFromArray([
                        'font'      => ['bold' => true, 'color' => ['rgb' => $fg], 'size' => 9],
                        'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bg]],
                        'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
                        'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                    ]);
                    $sheet->getStyle($colLetterE . $dataRow)->applyFromArray([
                        'font'    => ['size' => 9],
                        'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                        'alignment' => ['vertical' => 'center'],
                    ]);
                } else {
                    $colLetterD = $Coord::stringFromColumnIndex(4);
                    $colLetterE = $Coord::stringFromColumnIndex(5);
                    $sheet->setCellValue($colLetterD . $dataRow, '');
                    $sheet->setCellValue($colLetterE . $dataRow, '');
                    $sheet->getStyle($colLetterD . $dataRow . ':' . $colLetterE . $dataRow)->applyFromArray([
                        'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'DDDDDD']]],
                    ]);
                }
                
                $sheet->getRowDimension($dataRow)->setRowHeight(18);
                $dataRow++;
            }
        }

        // Set print area
        $sheet->getPageSetup()->setPrintArea("A1:{$lastColStr}" . ($dataRow - 1));
        
        // Freeze pane
        $sheet->freezePane('B6');

        $filename = 'jadwal_kelas_' . ($classInfo['name'] ?? 'x') . '_' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    public function exportClassPdf()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId   = $this->resolveImportId();
        $classAscId = $this->request->getGet('class_id');

        if (!$importId || !$classAscId) {
            return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        }

        $import   = $this->importModel->find($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $scheduleData = $this->scheduleModel->getByClass($importId, $classAscId);

        // Ambil info kelas
        $classes = $this->classModel->getByImport($importId);
        $classInfo = null;
        foreach ($classes as $c) {
            if ($c['asc_id'] === $classAscId) {
                $classInfo = $c;
                break;
            }
        }

        // Lookup warna guru (untuk tabel, bukan legend)
        $teacherColors = [];
        foreach ($teachers as $t) {
            $teacherColors[$t['short_code']] = $t['color'];
        }

        $html = $this->buildClassPdfHtml($import, $classInfo, $periods, $days, $scheduleData, $teacherColors);

        $mpdf = new \Mpdf\Mpdf([
            'orientation' => 'L',
            'margin_top'  => 10,
            'margin_bottom' => 10,
            'margin_left' => 8,
            'margin_right' => 8,
            'default_font_size' => 9,
            'default_font' => 'dejavusans',
        ]);

        $mpdf->WriteHTML($html);

        $filename = 'jadwal_kelas_' . ($classInfo['name'] ?? 'x') . '_' . date('Ymd') . '.pdf';
        $mpdf->Output($filename, 'D');
        exit;
    }

    

    // ── Generate Excel per guru ────────────────────────────────────────────

    private function generateTeacherExcel($import, $teacherInfo, $periods, $days, $scheduleData, $allTeachers, $showTime = true)
    {
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Jadwal Guru');

        $Coord   = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::class;
        $bgColor = ltrim($teacherInfo['color'] ?? '#CCCCCC', '#');
        $fgColor = $this->getExcelTextColor($bgColor);

        $colPeriods = count($periods);
        $lastDataCol = $colPeriods + 1;
        $lastColStr  = $Coord::stringFromColumnIndex($lastDataCol);

        // ── Baris 1: Judul ───────────────────────────────────────────────
        $sheet->mergeCells("A1:{$lastColStr}1");
        $sheet->setCellValue('A1', 'JADWAL MENGAJAR');
        $sheet->getStyle('A1')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 14],
            'alignment' => ['horizontal' => 'center'],
        ]);
        $sheet->getRowDimension(1)->setRowHeight(24);

        // ── Baris 2: Nama guru (dengan warna guru) ───────────────────────
        $sheet->mergeCells("A2:{$lastColStr}2");
        $sheet->setCellValue('A2', $teacherInfo['name'] ?? '');
        $sheet->getStyle('A2')->applyFromArray([
            'font'      => ['bold' => true, 'size' => 12, 'color' => ['rgb' => $fgColor]],
            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bgColor]],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
        ]);
        $sheet->getRowDimension(2)->setRowHeight(22);

        // ── Baris 3: Tahun ajaran ────────────────────────────────────────
        $sheet->mergeCells("A3:{$lastColStr}3");
        $sheet->setCellValue('A3', $import['academic_year'] . ' — Semester ' . $import['semester']);
        $sheet->getStyle('A3')->applyFromArray([
            'font'      => ['size' => 10],
            'alignment' => ['horizontal' => 'center'],
        ]);

        // ── Baris 5: Header (Hari + per jam) ────────────────────────────
        $headerStyle = [
            'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
            'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
            'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
        ];

        $sheet->setCellValue('A5', 'Hari');
        $sheet->getStyle('A5')->applyFromArray($headerStyle);
        $sheet->getColumnDimension('A')->setWidth(9);

        foreach ($periods as $idx => $period) {
            $col = $Coord::stringFromColumnIndex($idx + 2);
            $sheet->setCellValue($col . '5', $showTime ? ($period['period_number'] . "\n" . substr($period['start_time'], 0, 5) . '-' . substr($period['end_time'], 0, 5)) : ('Jam ' . $period['period_number']));
            $sheet->getStyle($col . '5')->applyFromArray($headerStyle);
            $sheet->getColumnDimension($col)->setWidth(13);
        }
        $sheet->getRowDimension(5)->setRowHeight(28);

        // ── Baris data ───────────────────────────────────────────────────
        $dataRow    = 6;
        $totalHours = 0;
        $classSummary = [];

        foreach ($days as $day) {
            $dayNum = $day['day_number'];
            $sheet->setCellValue('A' . $dataRow, strtoupper(substr($day['day_name'], 0, 3)));
            $sheet->getStyle('A' . $dataRow)->applyFromArray([
                'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
                'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
                'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
            ]);

            foreach ($periods as $idx => $period) {
                $pNum = $period['period_number'];
                $col  = $Coord::stringFromColumnIndex($idx + 2);
                $addr = $col . $dataRow;
                $slot = $scheduleData[$dayNum][$pNum] ?? null;

                if ($slot) {
                    $displayCode = $slot['display_code'] ?? $slot['subject_code'];
                    $sheet->setCellValue($addr, $slot['class_name'] . "\n" . $displayCode);
                    $sheet->getStyle($addr)->applyFromArray([
                        'font'      => ['bold' => true, 'size' => 9, 'color' => ['rgb' => $fgColor]],
                        'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bgColor]],
                        'alignment' => ['horizontal' => 'center', 'vertical' => 'center', 'wrapText' => true],
                        'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'AAAAAA']]],
                    ]);
                    $totalHours++;
                    $key = $slot['class_name'];
                    if (!isset($classSummary[$key])) $classSummary[$key] = ['hours' => 0, 'subjects' => []];
                    $classSummary[$key]['hours']++;
                    $classSummary[$key]['subjects'][$slot['subject_code']] = true;
                } else {
                    $sheet->getStyle($addr)->applyFromArray([
                        'fill'    => ['fillType' => 'solid', 'startColor' => ['rgb' => 'F5F5F5']],
                        'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'DDDDDD']]],
                    ]);
                }
            }

            $sheet->getRowDimension($dataRow)->setRowHeight(30);
            $dataRow++;

            // Garis pemisah antar hari
            $sheet->getRowDimension($dataRow)->setRowHeight(4);
            $sheet->mergeCells("A{$dataRow}:{$lastColStr}{$dataRow}");
            $sheet->getStyle("A{$dataRow}:{$lastColStr}{$dataRow}")->applyFromArray([
                'fill' => ['fillType' => 'solid', 'startColor' => ['rgb' => '1e3a5f']],
            ]);
            $dataRow++;
        }

        // ── Ringkasan mengajar per kelas ─────────────────────────────────
        $dataRow++;
        $sheet->mergeCells("A{$dataRow}:{$lastColStr}{$dataRow}");
        $sheet->setCellValue('A' . $dataRow, 'RINGKASAN MENGAJAR — Total: ' . $totalHours . ' jam/minggu');
        $sheet->getStyle('A' . $dataRow)->applyFromArray([
            'font'      => ['bold' => true, 'color' => ['rgb' => $fgColor], 'size' => 10],
            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bgColor]],
            'alignment' => ['horizontal' => 'center'],
        ]);
        $sheet->getRowDimension($dataRow)->setRowHeight(18);
        $dataRow++;

        // Sub-header
        $sheet->setCellValue('A' . $dataRow, 'Kelas');
        $sheet->setCellValue('B' . $dataRow, 'Mata Pelajaran');
        $sheet->setCellValue('C' . $dataRow, 'Jam');
        $sheet->getStyle('A' . $dataRow . ':C' . $dataRow)->applyFromArray([
            'font'      => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 9],
            'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => '2d4f7c']],
            'alignment' => ['horizontal' => 'center'],
            'borders'   => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => '555555']]],
        ]);
        $sheet->getColumnDimension('C')->setWidth(8);
        $dataRow++;

        ksort($classSummary);
        foreach ($classSummary as $className => $summary) {
            $sheet->setCellValue('A' . $dataRow, $className);
            $sheet->setCellValue('B' . $dataRow, implode(', ', array_keys($summary['subjects'])));
            $sheet->setCellValue('C' . $dataRow, $summary['hours']);
            $sheet->getStyle('A' . $dataRow . ':C' . $dataRow)->applyFromArray([
                'font'    => ['size' => 9],
                'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['rgb' => 'CCCCCC']]],
                'alignment' => ['vertical' => 'center'],
            ]);
            $sheet->getStyle('A' . $dataRow)->applyFromArray([
                'font'      => ['bold' => true, 'color' => ['rgb' => $fgColor], 'size' => 9],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['rgb' => $bgColor]],
                'alignment' => ['horizontal' => 'center'],
            ]);
            $sheet->getStyle('C' . $dataRow)->getAlignment()->setHorizontal('center');
            $dataRow++;
        }

        $sheet->freezePane('B6');

        $filename = 'jadwal_guru_' . ($teacherInfo['short_code'] ?? 'x') . '_' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    // ── Helper: warna teks berdasarkan background ──────────────────────────

    private function getExcelTextColor($hexBg)
    {
        $hexBg = ltrim($hexBg, '#');
        if (strlen($hexBg) !== 6) return '000000';

        $r = hexdec(substr($hexBg, 0, 2));
        $g = hexdec(substr($hexBg, 2, 2));
        $b = hexdec(substr($hexBg, 4, 2));
        $luminance = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;

        return $luminance > 0.5 ? '000000' : 'FFFFFF';
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT PDF — SEMUA KELAS (1 halaman per kelas)
    // ══════════════════════════════════════════════════════════════════════

    public function exportAllClassPdf()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId = $this->resolveImportId();
        if (!$importId) {
            return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        }

        $import   = $this->importModel->find($importId);
        $classes  = $this->classModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);

        // Lookup warna guru
        $teacherColors = [];
        foreach ($teachers as $t) {
            $teacherColors[$t['short_code']] = $t['color'];
        }

        $mpdf = new \Mpdf\Mpdf([
            'orientation' => 'L',
            'margin_top'  => 8,
            'margin_bottom' => 8,
            'margin_left' => 8,
            'margin_right' => 8,
            'default_font_size' => 8,
            'default_font' => 'dejavusans',
        ]);

        foreach ($classes as $idx => $class) {
            $scheduleData = $this->scheduleModel->getByClass($importId, $class['asc_id']);
            $html = $this->buildClassPdfHtml($import, $class, $periods, $days, $scheduleData, $teacherColors);

            if ($idx > 0) {
                $mpdf->AddPage('L');
            }
            $mpdf->WriteHTML($html);
        }

        $filename = 'jadwal_semua_kelas_' . date('Ymd') . '.pdf';
        $mpdf->Output($filename, 'D');
        exit;
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT PDF — SEMUA GURU (1 halaman per guru)
    // ══════════════════════════════════════════════════════════════════════

    public function exportAllTeacherPdf()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId = $this->resolveImportId();
        if (!$importId) {
            return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        }

        $import   = $this->importModel->find($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);

        $mpdf = new \Mpdf\Mpdf([
            'orientation' => 'L',  // LANDSCAPE
            'margin_top'  => 10,
            'margin_bottom' => 10,
            'margin_left' => 8,
            'margin_right' => 8,
            'default_font_size' => 9,
            'default_font' => 'dejavusans',
        ]);

        foreach ($teachers as $idx => $teacher) {
            $scheduleData = $this->scheduleModel->getByTeacher($importId, $teacher['asc_id']);

            // Hitung total jam
            $totalHours = 0;
            foreach ($scheduleData as $day) {
                $totalHours += count($day);
            }

            $html = $this->buildTeacherPdfHtml($import, $teacher, $periods, $days, $scheduleData, $totalHours);

            if ($idx > 0) {
                $mpdf->AddPage('L');  // PORTRAIT
            }
            $mpdf->WriteHTML($html);
        }

        $filename = 'jadwal_semua_guru_' . date('Ymd') . '.pdf';
        $mpdf->Output($filename, 'D');
        exit;
    }

    // ══════════════════════════════════════════════════════════════════════
    // PRIVATE — BUILD HTML: JADWAL SATU KELAS
    // ══════════════════════════════════════════════════════════════════════

    private function buildClassPdfHtml($import, $classInfo, $periods, $days, $scheduleData, $teacherColors, $showTime = true)
    {
        // Ambil nama sekolah
        $schoolSettingModel = new \App\Models\SchoolSettingModel();
        $schoolSettings = $schoolSettingModel->getSettings();
        $schoolName = $schoolSettings['school_name'] ?? 'Sekolah';

        $html = '
        <style>
            body { 
                font-family: dejavusans, sans-serif; 
                font-size: 9pt; 
                margin: 0; 
                padding: 0;
            }
            h1 { 
                font-size: 14pt; 
                margin: 0 0 2px; 
                text-align: center; 
            }
            h2 { 
                font-size: 12pt; 
                margin: 0 0 2px; 
                text-align: center; 
            }
            h4 { 
                font-size: 9pt; 
                margin: 0 0 8px; 
                text-align: center; 
                color: #555; 
                font-weight: normal;
            }
            .schedule-table { 
                width: 100%; 
                border-collapse: collapse; 
                margin-bottom: 15px;
            }
            .schedule-table th {
                background: #1e3a5f; 
                color: #fff; 
                font-size: 9pt;
                padding: 6px 4px; 
                text-align: center; 
                border: 1px solid #555;
            }
            .schedule-table td {
                padding: 6px 4px; 
                text-align: center;
                border: 1px solid #ccc; 
                font-size: 9pt;
                vertical-align: middle;
            }
            .td-jam {
                background: #2d4f7c; 
                color: #fff;
                font-weight: bold;
                font-size: 9pt;
            }
            .td-empty { 
                background: #f9f9f9; 
            }
            
            /* Legenda - list 2 kolom, jarak ideal */
            .legend-container {
                margin-top: 12px;
                width: 100%;
            }

            .legend-title {
                background: #1e3a5f;
                color: #fff;
                font-weight: bold;
                text-align: center;
                padding: 5px;
                font-size: 10pt;
                margin-bottom: 8px;
            }

            .legend-list {
                width: 100%;
                overflow: hidden;
            }

            .legend-col {
                width: 48%;
                float: left;
            }

            .legend-col-right {
                width: 48%;
                float: right;
            }

            .legend-item {
                margin-bottom: 2px;
                font-size: 10pt;
                line-height: 1.6;
            }

            .legend-item .code {
                display: inline-block;
                width: 50px;
                font-weight: bold;
            }

            .legend-item .separator {
                display: inline-block;
                width: 15px;
                text-align: center;
            }

            .legend-item .name {
                display: inline-block;
            }

            .clearfix {
                clear: both;
            }
        </style>';

        // Header
        $html .= '<div>';
        $html .= '<h1>' . strtoupper(htmlspecialchars($schoolName)) . '</h1>';
        $html .= '<h2>JADWAL PELAJARAN — KELAS ' . strtoupper(htmlspecialchars($classInfo['name'])) . '</h2>';
        $html .= '<h4>' . htmlspecialchars($import['academic_year']) . ' — Semester ' . htmlspecialchars($import['semester']) . '</h4>';

        // Tabel jadwal
        if (!empty($periods) && !empty($days)) {
            $colWidth = round(70 / count($days), 1);
            
            $html .= '<table class="schedule-table">';
            $html .= '<thead>';
            $html .= '<tr>';
            $html .= '<th style="width:15%">Jam</th>';
            foreach ($days as $day) {
                $html .= '<th style="width:' . $colWidth . '%">' . strtoupper($day['day_name']) . '</th>';
            }
            $html .= '</tr>';
            $html .= '</thead>';
            $html .= '<tbody>';

            foreach ($periods as $period) {
                $pNum = $period['period_number'];
                $html .= '<tr>';
                $html .= '<td class="td-jam">';
                $html .= 'Jam ' . $pNum;
                if ($showTime) {
                    $html .= '<br><span style="font-size:7pt">' . substr($period['start_time'], 0, 5) . '-' . substr($period['end_time'], 0, 5) . '</span>';
                }
                $html .= '</td>';

                foreach ($days as $day) {
                    $slot = $scheduleData[$day['day_number']][$pNum] ?? null;

                    if ($slot) {
                        $displayTeacherCode = $slot['display_teacher_code'] ?? $slot['teacher_code'];
                        $bg = $teacherColors[$displayTeacherCode] ?? '#CCCCCC';
                        $fg = $this->getExcelTextColor(ltrim($bg, '#'));
                        $displayCode = $slot['display_code'] ?? $slot['subject_code'];
                        $html .= '<td style="background:' . $bg . ';color:#' . $fg . ';font-weight:bold">'
                            . htmlspecialchars($displayCode)
                            . '<br><span style="font-size:7pt;opacity:0.8">[' . htmlspecialchars($displayTeacherCode) . ']</span>'
                            . '</td>';
                    } else {
                        $html .= '<td class="td-empty">-</td>';
                    }
                }
                $html .= '</tr>';
            }

            $html .= '</tbody>';
            $html .= '</table>';
        } else {
            $html .= '<p style="text-align:center;color:red">Tidak ada data jadwal</p>';
        }

        // ── LEGENDA GURU (URUT KODE, JARAK IDEAL) ─────────────────────────────
        $usedTeachers = [];
        if (!empty($scheduleData)) {
            foreach ($scheduleData as $daySlots) {
                if (!empty($daySlots)) {
                    foreach ($daySlots as $slot) {
                        $displayTeacherCode = $slot['display_teacher_code'] ?? $slot['teacher_code'];
                        if (!isset($usedTeachers[$displayTeacherCode])) {
                            $usedTeachers[$displayTeacherCode] = [
                                'code' => $displayTeacherCode,
                                'name' => $slot['display_teacher_name'] ?? $slot['teacher_name']
                            ];
                        }
                    }
                }
            }
        }

        if (!empty($usedTeachers)) {
            // Urutkan berdasarkan kode (ascending)
            ksort($usedTeachers);
            $teacherList = array_values($usedTeachers);
            $totalTeachers = count($teacherList);
            $halfCount = ceil($totalTeachers / 2);
            
            $html .= '<div class="legend-container">';
            $html .= '<div class="legend-title">KETERANGAN KODE GURU</div>';
            $html .= '<div class="legend-list">';
            
            // Kolom kiri
            $html .= '<div class="legend-col">';

            for ($i = 0; $i < $halfCount; $i++) {
                if (isset($teacherList[$i])) {
                    $html .= '<div class="legend-item">';
                    $html .= '<span class="code">'
                        . htmlspecialchars($teacherList[$i]['code'])
                        . '</span>';
                    $html .= '<span class="separator">-</span>';
                    $html .= '<span class="name">'
                        . htmlspecialchars($teacherList[$i]['name'])
                        . '</span>';
                    $html .= '</div>';
                }
            }

            $html .= '</div>';
            
            // Kolom kanan
            $html .= '<div class="legend-col-right">';

            for ($i = $halfCount; $i < $totalTeachers; $i++) {
                if (isset($teacherList[$i])) {
                    $html .= '<div class="legend-item">';
                    $html .= '<span class="code">'
                        . htmlspecialchars($teacherList[$i]['code'])
                        . '</span>';
                    $html .= '<span class="separator">-</span>';
                    $html .= '<span class="name">'
                        . htmlspecialchars($teacherList[$i]['name'])
                        . '</span>';
                    $html .= '</div>';
                }
            }

            $html .= '</div>';
            
            $html .= '<div class="clearfix"></div>';
            $html .= '</div>'; // .legend-list
            $html .= '</div>'; // .legend-container
        }
        
        $html .= '</div>';

        return $html;
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT PDF — PER GURU (SINGLE)
    // ══════════════════════════════════════════════════════════════════════

    public function exportTeacherPdf()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $importId     = $this->resolveImportId();
        $teacherAscId = $this->request->getGet('teacher_id');

        if (!$importId || !$teacherAscId) {
            return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        }

        $import   = $this->importModel->find($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $scheduleData = $this->scheduleModel->getByTeacher($importId, $teacherAscId);

        // Ambil info guru
        $teacherInfo = null;
        foreach ($teachers as $t) {
            if ($t['asc_id'] === $teacherAscId) {
                $teacherInfo = $t;
                break;
            }
        }

        // Hitung total jam
        $totalHours = 0;
        foreach ($scheduleData as $day) {
            $totalHours += count($day);
        }

        $html = $this->buildTeacherPdfHtml($import, $teacherInfo, $periods, $days, $scheduleData, $totalHours);

        $mpdf = new \Mpdf\Mpdf([
            'orientation' => 'L',  // LANDSCAPE
            'margin_top'  => 10,
            'margin_bottom' => 10,
            'margin_left' => 8,
            'margin_right' => 8,
            'default_font_size' => 9,
            'default_font' => 'dejavusans',
        ]);

        $mpdf->WriteHTML($html);

        $filename = 'jadwal_guru_' . ($teacherInfo['short_code'] ?? 'x') . '_' . date('Ymd') . '.pdf';
        $mpdf->Output($filename, 'D');
        exit;
    }


    // ── BUILD HTML PDF UNTUK SATU GURU (LANDSCAPE + RINGKASAN MENGAJAR 2 KOLOM) ─

    // ── BUILD HTML PDF UNTUK SATU GURU (LANDSCAPE + RINGKASAN MENGAJAR 2 KOLOM) ─

private function buildTeacherPdfHtml($import, $teacherInfo, $periods, $days, $scheduleData, $totalHours, $showTime = true)
{
    // Ambil nama sekolah
    $schoolSettingModel = new \App\Models\SchoolSettingModel();
    $schoolSettings = $schoolSettingModel->getSettings();
    $schoolName = $schoolSettings['school_name'] ?? 'Sekolah';

    // Hitung ringkasan mengajar per kelas (pakai nama lengkap mapel)
    $classSummary = [];
    foreach ($scheduleData as $daySlots) {
        foreach ($daySlots as $slot) {
            $key = $slot['class_name'];
            if (!isset($classSummary[$key])) {
                $classSummary[$key] = [
                    'class' => $slot['class_name'],
                    'subjects' => [],
                    'subjects_full' => [], // pakai nama lengkap
                    'hours' => 0
                ];
            }
            $classSummary[$key]['hours']++;
            // Gunakan nama lengkap mapel, bukan kode
            $classSummary[$key]['subjects_full'][$slot['subject_name']] = true;
        }
    }
    ksort($classSummary);

    $html = '
    <style>
        body { 
            font-family: dejavusans, sans-serif; 
            font-size: 9pt; 
            margin: 0; 
            padding: 0;
        }
        h1 { 
            font-size: 14pt; 
            margin: 0 0 2px; 
            text-align: center; 
        }
        h2 { 
            font-size: 12pt; 
            margin: 0 0 2px; 
            text-align: center; 
        }
        .teacher-name {
            font-size: 11pt;
            font-weight: bold;
            text-align: center;
            margin: 5px 0 2px;
            padding: 4px;
            background: #f0f4f8;
        }
        h4 { 
            font-size: 9pt; 
            margin: 0 0 8px; 
            text-align: center; 
            color: #555; 
            font-weight: normal;
        }
        .schedule-table { 
            width: 100%; 
            border-collapse: collapse; 
            margin-bottom: 15px;
        }
        .schedule-table th {
            background: #1e3a5f; 
            color: #fff; 
            font-size: 8pt;
            padding: 5px 3px; 
            text-align: center; 
            border: 1px solid #555;
        }
        .schedule-table td {
            padding: 5px 3px; 
            text-align: center;
            border: 1px solid #ccc; 
            font-size: 8pt;
            vertical-align: middle;
        }
        .td-jam {
            background: #2d4f7c; 
            color: #fff;
            font-weight: bold;
            font-size: 8pt;
        }
        .td-empty { 
            background: #f9f9f9; 
        }
        
        /* Ringkasan Mengajar - 2 kolom */
        .summary-container {
            margin-top: 15px;
            width: 100%;
        }
        .summary-title {
            background: #1e3a5f;
            color: #fff;
            font-weight: bold;
            text-align: center;
            padding: 5px;
            font-size: 10pt;
            margin-bottom: 8px;
        }
        .summary-wrapper {
            width: 100%;
            overflow: hidden;
        }
        .summary-col {
            width: 48%;
            float: left;
        }
        .summary-col-right {
            width: 48%;
            float: right;
        }
        .summary-table {
            width: 100%;
            border-collapse: collapse;
        }
        .summary-table th {
            background: #2d4f7c;
            color: #fff;
            font-size: 8pt;
            padding: 4px;
            text-align: center;
            border: 1px solid #555;
        }
        .summary-table td {
            padding: 4px;
            font-size: 7pt;
            border: 1px solid #ccc;
            vertical-align: top;
        }
        .summary-table .class-cell {
            font-weight: bold;
            width: 25%;
        }
        .summary-table .subjects-cell {
            width: 55%;
        }
        .summary-table .hours-cell {
            text-align: center;
            width: 20%;
        }
        .clearfix {
            clear: both;
        }
    </style>';

    // Header
    $html .= '<div>';
    $html .= '<h1>' . strtoupper(htmlspecialchars($schoolName)) . '</h1>';
    $html .= '<h2>JADWAL MENGAJAR</h2>';
    $html .= '<div class="teacher-name">' . htmlspecialchars($teacherInfo['name']) . ' [' . htmlspecialchars($teacherInfo['short_code']) . '] — Total: ' . $totalHours . ' jam/minggu</div>';
    $html .= '<h4>' . htmlspecialchars($import['academic_year']) . ' — Semester ' . htmlspecialchars($import['semester']) . '</h4>';

    // Tabel jadwal (Jam sebagai baris, Hari sebagai kolom) - tampilkan jam awal & akhir
    if (!empty($periods) && !empty($days)) {
        $colWidth = round(70 / count($days), 1);
        
        $html .= '<table class="schedule-table">';
        $html .= '<thead>';
        $html .= '<tr>';
        $html .= '<th style="width:15%">Jam</th>';
        foreach ($days as $day) {
            $html .= '<th style="width:' . $colWidth . '%">' . strtoupper($day['day_name']) . '</th>';
        }
        $html .= '</tr>';
        $html .= '</thead>';
        $html .= '<tbody>';

        foreach ($periods as $period) {
            $pNum = $period['period_number'];
            $start = substr($period['start_time'], 0, 5);
            $end = substr($period['end_time'], 0, 5);
            $html .= '<tr>';
            $html .= '<td class="td-jam">';
            $html .= 'Jam ' . $pNum;
            if ($showTime) {
                $html .= '<br><span style="font-size:6pt">' . $start . '-' . $end . '</span>';
            }
            $html .= '</td>';

            foreach ($days as $day) {
                $slot = $scheduleData[$day['day_number']][$pNum] ?? null;

                if ($slot) {
                    $displayCode = $slot['display_code'] ?? $slot['subject_code'];
                    $html .= '<td style="font-weight:bold;font-size:8pt">'
                        . htmlspecialchars($slot['class_name'])
                        . '<br><span style="font-size:6pt;opacity:0.7">' . htmlspecialchars($displayCode) . '</span>'
                        . '</td>';
                } else {
                    $html .= '<td class="td-empty">-</td>';
                }
            }
            $html .= '</tr>';
        }

        $html .= '</tbody>';
        $html .= '</table>';
    } else {
        $html .= '<p style="text-align:center;color:red">Tidak ada data jadwal</p>';
    }

    // ── RINGKASAN MENGAJAR (2 KOLOM, semua kelas, nama lengkap mapel) ─────
    if (!empty($classSummary)) {
        $summaryList = array_values($classSummary);
        $totalSummary = count($summaryList);
        $halfCount = ceil($totalSummary / 2);
        
        $html .= '<div class="summary-container">';
        $html .= '<div class="summary-title">RINGKASAN MENGAJAR</div>';
        $html .= '<div class="summary-wrapper">';
        
        // Kolom kiri
        $html .= '<div class="summary-col">';
        $html .= '<table class="summary-table">';
        $html .= '<thead><tr><th>Kelas</th><th>Mata Pelajaran</th><th>Jam</th></tr></thead>';
        $html .= '<tbody>';
        for ($i = 0; $i < $halfCount; $i++) {
            if (isset($summaryList[$i])) {
                $item = $summaryList[$i];
                // Ambil nama lengkap mapel, gabung dengan koma
                $subjectsFull = array_keys($item['subjects_full']);
                $subjectsText = implode(', ', $subjectsFull);
                $html .= '<tr>';
                $html .= '<td class="class-cell">' . htmlspecialchars($item['class']) . '</td>';
                $html .= '<td class="subjects-cell">' . htmlspecialchars($subjectsText) . '</td>';
                $html .= '<td class="hours-cell">' . $item['hours'] . '</td>';
                $html .= '</tr>';
            }
        }
        $html .= '</tbody>';
        $html .= '</table>';
        $html .= '</div>';
        
        // Kolom kanan
        $html .= '<div class="summary-col-right">';
        $html .= '<table class="summary-table">';
        $html .= '<thead><tr><th>Kelas</th><th>Mata Pelajaran</th><th>Jam</th></tr></thead>';
        $html .= '<tbody>';
        for ($i = $halfCount; $i < $totalSummary; $i++) {
            if (isset($summaryList[$i])) {
                $item = $summaryList[$i];
                // Ambil nama lengkap mapel, gabung dengan koma
                $subjectsFull = array_keys($item['subjects_full']);
                $subjectsText = implode(', ', $subjectsFull);
                $html .= '<tr>';
                $html .= '<td class="class-cell">' . htmlspecialchars($item['class']) . '</td>';
                $html .= '<td class="subjects-cell">' . htmlspecialchars($subjectsText) . '</td>';
                $html .= '<td class="hours-cell">' . $item['hours'] . '</td>';
                $html .= '</tr>';
            }
        }
        $html .= '</tbody>';
        $html .= '</table>';
        $html .= '</div>';
        
        $html .= '<div class="clearfix"></div>';
        $html .= '</div>'; // .summary-wrapper
        $html .= '</div>'; // .summary-container
    }
    
    $html .= '</div>';

    return $html;
}

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT TANPA WAKTU — KESELURUHAN
    // ══════════════════════════════════════════════════════════════════════

    public function exportExcelNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId   = $this->resolveImportId();
        $gradeLevel = $this->request->getGet('grade') ? (int) $this->request->getGet('grade') : null;
        if (!$importId) return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        $import   = $this->importModel->find($importId);
        $classes  = $gradeLevel ? $this->classModel->getByGrade($importId, $gradeLevel) : $this->classModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $gridData = $this->scheduleModel->getGridData($importId, $gradeLevel);
        $this->generateExcel($import, $classes, $periods, $days, $teachers, $gridData, $gradeLevel, false);
    }

    public function exportPdfNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId   = $this->resolveImportId();
        $gradeLevel = $this->request->getGet('grade') ? (int) $this->request->getGet('grade') : null;
        if (!$importId) return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        $import   = $this->importModel->find($importId);
        $classes  = $gradeLevel ? $this->classModel->getByGrade($importId, $gradeLevel) : $this->classModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $gridData = $this->scheduleModel->getGridData($importId, $gradeLevel);
        $html = $this->buildSchedulePdfHtml($import, $classes, $periods, $days, $teachers, $gridData, $gradeLevel, false);
        $mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'margin_top' => 10, 'margin_bottom' => 10, 'margin_left' => 8, 'margin_right' => 8, 'default_font_size' => 9, 'default_font' => 'dejavusans']);
        $mpdf->WriteHTML($html);
        $gradeSuffix = $gradeLevel ? "_kelas{$gradeLevel}" : '_semua';
        $mpdf->Output('jadwal' . $gradeSuffix . '_notimes_' . date('Ymd') . '.pdf', 'D');
        exit;
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT TANPA WAKTU — PER KELAS
    // ══════════════════════════════════════════════════════════════════════

    public function exportClassExcelNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId   = $this->resolveImportId();
        $classAscId = $this->request->getGet('class_id');
        if (!$importId || !$classAscId) return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        $import       = $this->importModel->find($importId);
        $periods      = $this->periodModel->getByImport($importId);
        $days         = $this->scheduleModel->getDayList($importId);
        $teachers     = $this->teacherModel->getByImport($importId);
        $scheduleData = $this->scheduleModel->getByClass($importId, $classAscId);
        $classes = $this->classModel->getByImport($importId);
        $classInfo = null;
        foreach ($classes as $c) { if ($c['asc_id'] === $classAscId) { $classInfo = $c; break; } }
        $this->generateClassExcel($import, $classInfo, $periods, $days, $teachers, $scheduleData, false);
    }

    public function exportClassPdfNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId   = $this->resolveImportId();
        $classAscId = $this->request->getGet('class_id');
        if (!$importId || !$classAscId) return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        $import       = $this->importModel->find($importId);
        $periods      = $this->periodModel->getByImport($importId);
        $days         = $this->scheduleModel->getDayList($importId);
        $teachers     = $this->teacherModel->getByImport($importId);
        $scheduleData = $this->scheduleModel->getByClass($importId, $classAscId);
        $teacherColors = [];
        foreach ($teachers as $t) { $teacherColors[$t['short_code']] = $t['color']; }
        $classes = $this->classModel->getByImport($importId);
        $classInfo = null;
        foreach ($classes as $c) { if ($c['asc_id'] === $classAscId) { $classInfo = $c; break; } }
        $html = $this->buildClassPdfHtml($import, $classInfo, $periods, $days, $scheduleData, $teacherColors, false);
        $mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'margin_top' => 10, 'margin_bottom' => 10, 'margin_left' => 8, 'margin_right' => 8, 'default_font_size' => 9, 'default_font' => 'dejavusans']);
        $mpdf->WriteHTML($html);
        $mpdf->Output('jadwal_kelas_' . ($classInfo['name'] ?? 'x') . '_notimes_' . date('Ymd') . '.pdf', 'D');
        exit;
    }

    public function exportAllClassPdfNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId = $this->resolveImportId();
        if (!$importId) return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        $import   = $this->importModel->find($importId);
        $classes  = $this->classModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $teacherColors = [];
        foreach ($teachers as $t) { $teacherColors[$t['short_code']] = $t['color']; }
        $mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'margin_top' => 8, 'margin_bottom' => 8, 'margin_left' => 8, 'margin_right' => 8, 'default_font_size' => 8, 'default_font' => 'dejavusans']);
        foreach ($classes as $idx => $class) {
            $scheduleData = $this->scheduleModel->getByClass($importId, $class['asc_id']);
            $html = $this->buildClassPdfHtml($import, $class, $periods, $days, $scheduleData, $teacherColors, false);
            if ($idx > 0) $mpdf->AddPage('L');
            $mpdf->WriteHTML($html);
        }
        $mpdf->Output('jadwal_semua_kelas_notimes_' . date('Ymd') . '.pdf', 'D');
        exit;
    }

    // ══════════════════════════════════════════════════════════════════════
    // EXPORT TANPA WAKTU — PER GURU
    // ══════════════════════════════════════════════════════════════════════

    public function exportTeacherExcelNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId     = $this->resolveImportId();
        $teacherAscId = $this->request->getGet('teacher_id');
        if (!$importId || !$teacherAscId) return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        $import       = $this->importModel->find($importId);
        $periods      = $this->periodModel->getByImport($importId);
        $days         = $this->scheduleModel->getDayList($importId);
        $scheduleData = $this->scheduleModel->getByTeacher($importId, $teacherAscId);
        $teachers = $this->teacherModel->getByImport($importId);
        $teacherInfo = null;
        foreach ($teachers as $t) { if ($t['asc_id'] === $teacherAscId) { $teacherInfo = $t; break; } }
        $this->generateTeacherExcel($import, $teacherInfo, $periods, $days, $scheduleData, $teachers, false);
    }

    public function exportTeacherPdfNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId     = $this->resolveImportId();
        $teacherAscId = $this->request->getGet('teacher_id');
        if (!$importId || !$teacherAscId) return redirect()->back()->with('error', 'Parameter tidak lengkap.');
        $import   = $this->importModel->find($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $scheduleData = $this->scheduleModel->getByTeacher($importId, $teacherAscId);
        $teacherInfo = null;
        foreach ($teachers as $t) { if ($t['asc_id'] === $teacherAscId) { $teacherInfo = $t; break; } }
        $totalHours = 0;
        foreach ($scheduleData as $day) { $totalHours += count($day); }
        $html = $this->buildTeacherPdfHtml($import, $teacherInfo, $periods, $days, $scheduleData, $totalHours, false);
        $mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'margin_top' => 10, 'margin_bottom' => 10, 'margin_left' => 8, 'margin_right' => 8, 'default_font_size' => 9, 'default_font' => 'dejavusans']);
        $mpdf->WriteHTML($html);
        $mpdf->Output('jadwal_guru_' . ($teacherInfo['short_code'] ?? 'x') . '_notimes_' . date('Ymd') . '.pdf', 'D');
        exit;
    }

    public function exportAllTeacherPdfNoTimes()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $importId = $this->resolveImportId();
        if (!$importId) return redirect()->to('/asc-import')->with('error', 'Belum ada jadwal aktif.');
        $import   = $this->importModel->find($importId);
        $teachers = $this->teacherModel->getByImport($importId);
        $periods  = $this->periodModel->getByImport($importId);
        $days     = $this->scheduleModel->getDayList($importId);
        $mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'margin_top' => 10, 'margin_bottom' => 10, 'margin_left' => 8, 'margin_right' => 8, 'default_font_size' => 9, 'default_font' => 'dejavusans']);
        foreach ($teachers as $idx => $teacher) {
            $scheduleData = $this->scheduleModel->getByTeacher($importId, $teacher['asc_id']);
            $totalHours = 0;
            foreach ($scheduleData as $day) { $totalHours += count($day); }
            $html = $this->buildTeacherPdfHtml($import, $teacher, $periods, $days, $scheduleData, $totalHours, false);
            if ($idx > 0) $mpdf->AddPage('L');
            $mpdf->WriteHTML($html);
        }
        $mpdf->Output('jadwal_semua_guru_notimes_' . date('Ymd') . '.pdf', 'D');
        exit;
    }

}