<?php

namespace App\Helpers;

use App\Models\JadwalPattern;
use Illuminate\Support\Facades\Cache;

class ScheduleHelper
{
    public static function getDefaultDayPatterns()
    {
        return [
            'senin' => ['1-2', '3-6', '7-10'],
            'selasa' => ['2-5', '6-10'],
            'rabu' => ['1-5', '6', '7-8', '9-10'],
            'kamis' => ['1-5', '6', '7-10'],
            'jumat' => ['1-4', '5-9']
        ];
    }

    public static function getDayPatterns()
    {
        return Cache::remember('jadwal_day_patterns', now()->addDay(), function() {
            $patternsFromDB = JadwalPattern::all()->pluck('pattern', 'hari')->toArray();
            
            if (!empty($patternsFromDB)) {
                $result = [];
                foreach ($patternsFromDB as $day => $patternStr) {
                    $result[$day] = explode(',', $patternStr);
                }
                return $result;
            }
            
            return self::getDefaultDayPatterns();
        });
    }

    public static function processSchedules($schedules, $dayPatterns = null)
    {
        $dayPatterns = $dayPatterns ?? self::getDayPatterns();
        $dayOrder = ['senin', 'selasa', 'rabu', 'kamis', 'jumat'];
        
        $groupedByDay = [];
        foreach ($schedules as $jadwal) {
            $day = strtolower($jadwal->hari);
            if (!isset($groupedByDay[$day])) {
                $groupedByDay[$day] = [];
            }
            $groupedByDay[$day][] = $jadwal;
        }
        
        foreach ($groupedByDay as $day => $daySchedules) {
            usort($groupedByDay[$day], function($a, $b) {
                return $a->jam_ke <=> $b->jam_ke;
            });
        }
        
        $finalData = [];
        $counter = 1;
        
        foreach ($dayOrder as $day) {
            if (!isset($groupedByDay[$day])) continue;
            
            $jadwalsInDay = $groupedByDay[$day];
            $pattern = $dayPatterns[$day] ?? [];
            $firstBlockInDay = true;
            
            foreach ($pattern as $block) {
                list($startBlock, $endBlock) = array_pad(explode('-', $block), 2, null);
                $endBlock = $endBlock ?? $startBlock;
                
                $blockJadwals = array_filter($jadwalsInDay, function($j) use ($startBlock, $endBlock) {
                    return $j->jam_ke >= $startBlock && $j->jam_ke <= $endBlock;
                });

                if (!empty($blockJadwals)) {
                    $currentBlock = null;
                    $subBlocks = [];
                    
                    foreach ($blockJadwals as $jadwal) {
                        if ($currentBlock === null) {
                            $currentBlock = self::createBlockFromJadwal($jadwal);
                        } else {
                            if ($jadwal->jam_ke == $currentBlock['end_ke'] + 1 &&
                                $jadwal->guru_id == $jadwal->guru_id &&
                                $jadwal->mapel_id == $jadwal->mapel_id &&
                                $jadwal->kelas_id == $jadwal->kelas_id) {
                                $currentBlock['end_ke'] = $jadwal->jam_ke;
                                $currentBlock['waktu_selesai'] = $jadwal->waktu_selesai;
                            } else {
                                $subBlocks[] = $currentBlock;
                                $currentBlock = self::createBlockFromJadwal($jadwal);
                            }
                        }
                    }
                    
                    if ($currentBlock !== null) {
                        $subBlocks[] = $currentBlock;
                    }

                    foreach ($subBlocks as $i => $subBlock) {
                        $finalData[] = [
                            'no' => $counter,
                            'hari' => ucfirst($day),
                            'jam_ke' => self::formatJamKe($subBlock['start_ke'], $subBlock['end_ke']),
                            'kelas' => $subBlock['kelas'],
                            'waktu_mulai' => $subBlock['waktu_mulai']->format('H:i'),
                            'waktu_selesai' => $subBlock['waktu_selesai']->format('H:i'),
                            'instruktur' => $subBlock['instruktur'],
                            'mapel' => $subBlock['mapel'],
                            'is_first' => $firstBlockInDay && $i === 0,
                        ];
                    }
                    
                    $firstBlockInDay = false;
                }
            }
            $counter++;
        }
        
        return $finalData;
    }

    private static function createBlockFromJadwal($jadwal)
    {
        return [
            'start_ke' => $jadwal->jam_ke,
            'end_ke' => $jadwal->jam_ke,
            'waktu_mulai' => $jadwal->waktu_mulai,
            'waktu_selesai' => $jadwal->waktu_selesai,
            'instruktur' => $jadwal->guru->nama ?? 'Unknown',
            'mapel' => $jadwal->mapel->nama_mapel ?? 'Unknown',
            'kelas' => $jadwal->kelas->nama_kelas ?? 'Unknown'
        ];
    }
    private static function formatJamKe($start, $end)
    {
        return $start == $end ? $start : $start . '-' . $end;
    }
}