<?php

namespace Modules\SpecialAttendance\Database\Seeders;

use App\Models\Hrm\Attendance\Holiday;
use App\Models\Hrm\Attendance\Weekend;
use App\Models\User;
use DateTime;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Modules\SpecialAttendance\Http\Repositories\DutyCalendarRepository;

class SpecialDutyScheduleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        $users = User::get();
        foreach ($users as $user) {
            $weekends = Weekend::where('is_weekend', 1)->get()->pluck('name')->toArray();
            $weekendsCapitalized = array_map(function ($item) {
                return ucfirst(strtolower($item));
            }, $weekends);

            $holidays = Holiday::where('status_id', 1)->get(['id', 'start_date', 'end_date']);
            $expandedHolidays = [];
            foreach ($holidays as $holiday) {
                $startDate = new DateTime($holiday->start_date);
                $endDate = new DateTime($holiday->end_date);
                while ($startDate <= $endDate) {
                    $expandedHolidays[$startDate->format('Y-m-d')] = $holiday->id;
                    $startDate->modify('+1 day');
                }
            }
            $user->duty_schedule_id = $user->shift->dutySchedule->id ?? 1;
            $user->weekends = json_encode($weekendsCapitalized);
            $user->holidays = json_encode($expandedHolidays);
            $user->save();

            $months = [];
            $currentYear = date('Y');

            for ($month = 1; $month <= 12; $month++) {
                $months[] = $currentYear.'-'.str_pad($month, 2, '0', STR_PAD_LEFT);
            }

            foreach ($months ?? [] as $month) {
                (new DutyCalendarRepository)->store($user, $month);
            }
        }
    }
}
