<?php

namespace App\Http\Controllers;

use App\Models\Jadwal;
use App\Models\JadwalPerawatan;
use App\Models\JenisPerawatan;
use App\Models\Kelas;
use App\Models\Mapel;
use App\Models\User;
use Carbon\Carbon;
use App\Helpers\ScheduleHelper;

class LandingController extends Controller
{
    public function index()
    {
        $hariIndo = [
            'Sunday' => 'minggu',
            'Monday' => 'senin',
            'Tuesday' => 'selasa',
            'Wednesday' => 'rabu',
            'Thursday' => 'kamis',
            'Friday' => 'jumat',
            'Saturday' => 'sabtu'
        ];
        
        $now = Carbon::now('Asia/Jakarta');
        $hariIni = $hariIndo[$now->format('l')];
        $waktuSekarang = $now->format('H:i:s');
        
        $jadwalBerjalan = Jadwal::with(['guru', 'mapel', 'kelas'])
            ->where('hari', $hariIni)
            ->whereColumn('waktu_mulai', '<', 'waktu_selesai')
            ->where('waktu_mulai', '<=', $waktuSekarang)
            ->where('waktu_selesai', '>=', $waktuSekarang)
            ->orderBy('jam_ke')
            ->get();
        
        $jadwalAkuntansi = Jadwal::with(['guru', 'mapel', 'kelas'])
            ->whereHas('kelas', function($query) {
                $query->where('jurusan', 'akuntansi');
            })
            ->orderBy('hari')
            ->orderBy('jam_ke')
            ->get();
            
        $jadwalManajemen = Jadwal::with(['guru', 'mapel', 'kelas'])
            ->whereHas('kelas', function($query) {
                $query->where('jurusan', 'manajemen_perkantoran');
            })
            ->orderBy('hari')
            ->orderBy('jam_ke')
            ->get();

        $processedAkuntansi = ScheduleHelper::processSchedules($jadwalAkuntansi);
        $processedManajemen = ScheduleHelper::processSchedules($jadwalManajemen);

        $tahun = now()->year;
    
        $jadwalPerawatan = JadwalPerawatan::with(['jenisPerawatan' => function($query) {
            $query->select('id', 'nama', 'kategori');
        }])
        ->where('tahun', $tahun)
        ->get();
        
        $jenisPerawatan = JenisPerawatan::all();

        $totalPengguna = User::count();
        $totalJadwal = Jadwal::count();
        $totalMapel = Mapel::count();
        $totalKelas = Kelas::count();
        
        return view('index', [
            'jadwalBerjalan' => $jadwalBerjalan,
            'tanggalHariIni' => $now->isoFormat('D MMMM Y'),
            'jadwalAkuntansi' => $processedAkuntansi,
            'jadwalManajemen' => $processedManajemen,
            'jadwalPerawatan' => $jadwalPerawatan,
            'jenisPerawatan' => $jenisPerawatan,
            'tahun' => $tahun,
            'totalPengguna' => $totalPengguna,
            'totalJadwal' => $totalJadwal,
            'totalMapel' => $totalMapel,
            'totalKelas' => $totalKelas
        ]);
    }
}