<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Schedule;
use App\Models\User;
use App\Models\Kelas;
use App\Models\Subject;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class ScheduleController extends Controller
{
    public function index()
{
    $user = Auth::user();
    
    // 1. Ambil Jadwal
    $query = Schedule::with(['guru', 'subject'])->orderBy('tanggal', 'asc');
    if (!in_array($user->role, ['super_admin', 'admin_mapel'])) {
        $query->where('user_id', $user->id);
    }
    $rawSchedules = $query->get();

    // 2. AMBIL DATA PEKAN TIDAK EFEKTIF (WAJIB ADA)
    $pekanTidakEfektif = \App\Models\EffectiveWeek::orderBy('start_date', 'asc')->get();

    // 3. Data Pelengkap Admin
    if (in_array($user->role, ['super_admin', 'admin_mapel'])) {
        $teachers = User::where('role', 'guru_mapel')->orWhere('role', 'koordinator')->get();
        $classes = \App\Models\Kelas::all();
    } else {
        $teachers = collect([]); 
        $classes = collect([]);
    }

    $groupedSchedules = $rawSchedules->groupBy(function($item) {
        return $item->user_id . '-' . $item->subject_id . '-' . $item->class . '-' . $item->hari . '-' . $item->tipe_jadwal;
    });
    // Pastikan mengirim seluruh objek agar 'notes' terbawa ke JS
    $pekanTidakEfektif = \App\Models\EffectiveWeek::orderBy('start_date', 'asc')->get();
    // Kirim semua variabel ke view
    return view('pages.pembelajaran.jadwal.index', compact(
        'teachers', 
        'classes', 
        'groupedSchedules', 
        'pekanTidakEfektif' // Pastikan variabel ini terkirim
    ));
}

    public function getTeacherSubjects($teacherId)
    {
        try {
            $teacher = User::with('subjects')->find($teacherId);
            if ($teacher && $teacher->subjects && $teacher->subjects->count() > 0) {
                return response()->json($teacher->subjects);
            }
            return response()->json(Subject::all());
        } catch (\Exception $e) {
            return response()->json(Subject::all());
        }
    }

public function getEvents(Request $request)
{
    $user = Auth::user();
    $query = Schedule::with(['guru', 'subject']);

    if (!in_array($user->role, ['super_admin', 'admin_mapel'])) {
        $query->where('user_id', $user->id);
    }

    $schedules = $query->get();
    $events = [];

    // Daftar palet warna yang menarik
    $colors = [
        '#4e73df', // Blue
        '#1cc88a', // Green
        '#36b9cc', // Cyan
        '#f6c23e', // Yellow
        '#e74a3b', // Red
        '#6f42c1', // Purple
        '#fd7e14', // Orange
        '#20c997', // Teal
    ];

    foreach ($schedules as $schedule) {
        $subjectId = $schedule->subject_id ?? 0;
        // Pilih warna berdasarkan ID mata pelajaran
        $colorIndex = $subjectId % count($colors);
        $eventColor = $colors[$colorIndex];

        $events[] = [
            'id' => $schedule->id,
            'title' => $schedule->subject->name ?? 'Mapel',
            'start' => $schedule->tanggal,
            'backgroundColor' => $eventColor,
            'borderColor' => $eventColor,
            'allDay' => true,
            'extendedProps' => [
                'guru' => $schedule->guru->name ?? '-',
                'kelas' => $schedule->class,
                'mapel' => $schedule->subject->name ?? '-',
                'tipe' => ucfirst($schedule->tipe_jadwal),
                'pekan' => $schedule->pekan_ke,
            ]
        ];
    }
    return response()->json($events);
}

public function store(Request $request)
{
    $request->validate([
        'teacher_id' => 'required',
        'class'      => 'required',
        'subject_id' => 'required',
        'type'       => 'required',
    ]);

    // Ambil semua pekan tidak efektif
    $offWeeks = \App\Models\EffectiveWeek::pluck('start_date')
                ->map(fn($d) => \Carbon\Carbon::parse($d)->format('Y-m-d'))
                ->toArray();

    if ($request->type === 'block') {
    $startSemesterDate = Carbon::parse($request->start_date_block); 
    
    // Sortir pilihan pekan agar diproses berurutan
    $selectedWeeks = collect($request->selected_weeks)->sort();

    foreach ($selectedWeeks as $actualWeekIndex) {
        $weekStartDate = $startSemesterDate->copy()->addWeeks($actualWeekIndex - 1)->startOfWeek(Carbon::MONDAY);
        
        // Hitung manual nomor pekan efektif ke berapa minggu ini berada
        $effectiveWeekNumber = 1;
        for ($j = 1; $j < $actualWeekIndex; $j++) {
            $checkDate = $startSemesterDate->copy()->addWeeks($j - 1)->startOfWeek(Carbon::MONDAY)->format('Y-m-d');
            if (!in_array($checkDate, $offWeeks)) {
                $effectiveWeekNumber++;
            }
        }

        foreach ($request->days as $dayNumber) {
            $dayIndex = (int)$dayNumber; 
            $realDate = $weekStartDate->copy()->addDays($dayIndex - 1);
            
            // Simpan menggunakan $effectiveWeekNumber, bukan index loop
            $this->saveSchedule($request, $realDate, $dayIndex, $effectiveWeekNumber, 'blok');
        }
    }
}
    else {
        // --- LOGIKA REGULAR (OTOMATIS SKIP LIBUR) ---
        $targetDurasi = (int) ($request->duration_weeks ?? 16);
        $semesterStart = Carbon::parse($request->start_date_regular);
        $baseDate = $semesterStart->copy()->startOfWeek(Carbon::MONDAY); 

        $savedMeetings = 0;
        $weekOffset = 0;

        while ($savedMeetings < $targetDurasi) {
            $currentWeekStart = $baseDate->copy()->addWeeks($weekOffset);
            
            // Jika pekan libur, lompat ke minggu depan tanpa menambah hitungan savedMeetings
            if (in_array($currentWeekStart->format('Y-m-d'), $offWeeks)) {
                $weekOffset++;
                continue;
            }

            $mapHari = ['Senin'=>1, 'Selasa'=>2, 'Rabu'=>3, 'Kamis'=>4, 'Jumat'=>5, 'Sabtu'=>6];
            $targetHari = $mapHari[$request->day] ?? 1;
            
            $realDate = $currentWeekStart->copy()->addDays($targetHari - 1);
            $this->saveSchedule($request, $realDate, $targetHari, ($savedMeetings + 1), 'regular');
            
            $savedMeetings++;
            $weekOffset++;
            
            if ($weekOffset > 30) break; // Keamanan agar tidak infinite loop
        }
    }

    return back()->with('success', 'Jadwal berhasil disimpan!');
}


    private function saveSchedule($request, $date, $dayIndex, $week, $type) {
        Schedule::create([
            'user_id'       => $request->teacher_id,
            'subject_id'    => $request->subject_id,
            'class'         => $request->class,
            'tanggal'       => $date->format('Y-m-d'),
            'pekan_ke'      => $week,
            'hari'          => $dayIndex,
            'tipe_jadwal'   => $type,
            'data'          => [],
        ]);
    }

    // Hapus SATU jadwal (Dipanggil dari modal rincian)
    public function destroy($id)
    {
        $schedule = Schedule::find($id);
        if ($schedule) {
            $schedule->delete();
            return back()->with('success', 'Satu jadwal pertemuan dihapus');
        }
        return back()->with('error', 'Data tidak ditemukan');
    }

    // [BARU] Hapus SATU GRUP jadwal (Hapus Batch)
    public function destroyGroup(Request $request)
    {
        // Hapus berdasarkan kriteria yang sama (Guru, Kelas, Mapel, Hari, Tipe)
        $deleted = Schedule::where('user_id', $request->user_id)
            ->where('subject_id', $request->subject_id)
            ->where('class', $request->class)
            ->where('hari', $request->hari)
            ->where('tipe_jadwal', $request->tipe_jadwal)
            ->delete();

        return back()->with('success', $deleted . ' Jadwal berhasil dihapus sekaligus.');
    }
public function storePekanTidakEfektif(Request $request)
{
    $request->validate([
        'start_date_off' => 'required|date',
        'notes' => 'nullable|string' // Pastikan input notes divalidasi
    ]);

    try {
        DB::beginTransaction();

        $inputDate = \Carbon\Carbon::parse($request->start_date_off);
        $startDate = $inputDate->startOfWeek(\Carbon\Carbon::MONDAY)->format('Y-m-d');

        // --- BAGIAN YANG SERING TERLUPAKAN ---
        // Simpan data ke tabel effective_weeks agar muncul di daftar
        \App\Models\EffectiveWeek::create([
            'start_date' => $startDate,
            'notes' => $request->notes
        ]);

        // Geser jadwal yang sudah ada
        Schedule::where('tanggal', '>=', $startDate)
            ->update([
                'tanggal'  => DB::raw("DATE_ADD(tanggal, INTERVAL 7 DAY)"),
                'pekan_ke' => DB::raw("pekan_ke + 1") 
            ]);

        DB::commit();
        return back()->with('success', 'Pekan tidak efektif berhasil disimpan dan jadwal digeser.');

    } catch (\Exception $e) {
        DB::rollBack();
        return back()->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
    }
}
public function destroyPekanTidakEfektif($id)
{
    try {
        DB::beginTransaction();

        $pekan = \App\Models\EffectiveWeek::findOrFail($id);
        $startDate = $pekan->start_date->format('Y-m-d');

        // Tarik kembali jadwal masa depan: Tanggal -7 hari, Pekan_ke -1
        \App\Models\Schedule::where('tanggal', '>', $startDate)
            ->update([
                'tanggal'  => DB::raw("DATE_SUB(tanggal, INTERVAL 7 DAY)"),
                'pekan_ke' => DB::raw("pekan_ke - 1") 
            ]);

        $pekan->delete();

        DB::commit();
        return back()->with('success', 'Pekan dihapus. Jadwal ditarik kembali ke pekan ini.');
    } catch (\Exception $e) {
        DB::rollBack();
        return back()->with('error', 'Gagal: ' . $e->getMessage());
    }
}
// --- FUNGSI CETAK JADWAL GURU ---
    public function print()
    {
        $user = Auth::user();
        
        $query = Schedule::with(['subject', 'guru'])->orderBy('tanggal', 'asc');
        
        // Jika yang login bukan admin, hanya ambil jadwal miliknya
        if (!in_array($user->role, ['super_admin', 'admin_mapel'])) {
            $query->where('user_id', $user->id);
        }
        
        $schedules = $query->get();

        if ($schedules->isEmpty()) {
            return back()->with('error', 'Tidak ada jadwal yang dapat dicetak.');
        }

        // 1. Data untuk Tabel (Group by Pekan)
        $groupedByPekan = $schedules->groupBy('pekan_ke')->sortKeys();

        // 2. Data untuk Kalender (Group by Tanggal)
		$schedulesByDate = $schedules->groupBy(function($item) {
   		// Memaksa format tanggal menjadi YYYY-MM-DD saja tanpa jam
	    return \Carbon\Carbon::parse($item->tanggal)->format('Y-m-d');
		});        
        // Cari rentang bulan (Min - Max) untuk menggambar kotak kalender
        $minDate = \Carbon\Carbon::parse($schedules->min('tanggal'))->startOfMonth();
        $maxDate = \Carbon\Carbon::parse($schedules->max('tanggal'))->endOfMonth();
        
        $months = [];
        $current = $minDate->copy();
        while($current <= $maxDate) {
            $months[] = $current->copy();
            $current->addMonth();
        }

        return view('pages.pembelajaran.jadwal.print', compact('groupedByPekan', 'schedulesByDate', 'months', 'user'));
    }

}