<?php

namespace App\Services;

use App\Models\WorkCalendar;
use App\Models\HolidaySchedule;
use Carbon\Carbon;

class AttendanceService
{
    /**
     * Menghitung total hari kerja efektif dalam satu bulan
     * @param int $year
     * @param int $month
     * @param int|null $branchId
     * @return int
     */
    public function getWorkingDays($year, $month, $branchId = null)
    {
        // 1. Ambil konfigurasi kalender kerja
        $calendar = WorkCalendar::where('year', $year)->first();
        $workingDays = $calendar ? $calendar->working_days : ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

        // 2. Tentukan range tanggal dalam bulan tersebut
        $start = Carbon::create($year, $month, 1);
        $end = $start->copy()->endOfMonth();
        
        $totalDays = 0;

        // 3. Loop setiap hari dalam bulan tersebut
        for ($date = $start->copy(); $date->lte($end); $date->addDay()) {
            $dayName = $date->format('l'); // Senin, Selasa, dst.

            // Cek apakah ini hari kerja (sesuai config)
            if (in_array($dayName, $workingDays)) {
                // Cek apakah hari ini ada di tabel libur (nasional atau cabang)
                $isHoliday = HolidaySchedule::where('holiday_date', $date->format('Y-m-d'))
                    ->where(function ($query) use ($branchId) {
                        $query->where('is_national_holiday', true)
                              ->orWhere('branch_id', $branchId);
                    })
                    ->exists();

                if (!$isHoliday) {
                    $totalDays++;
                }
            }
        }

        return $totalDays;
    }
}