<?php

namespace Database\Seeders;

use App\Models\Attendance;
use App\Models\User;
use Illuminate\Support\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Http;

class AttendanceSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Ambil user aktif agar tidak hard-coded id
        $userIds = User::query()
            ->where('status', 'aktif')
            ->limit(3)
            ->pluck('id')
            ->all();

        if (empty($userIds)) {
            return;
        }

        // Waktu
        $startDate = Carbon::now()->subMonths(2)->startOfMonth();
        $endDate = Carbon::now();

        // Ambil tanggal libur nasional
        $holidays = $this->getIndonesianHolidays($startDate, $endDate);

        foreach ($userIds as $userId) {
            $statuses = ['hadir', 'izin', 'alpha'];

            // Seed data per user
            for ($date = $startDate->copy(); $date->lte($endDate); $date->addDay()) {

                // Lewati Sabtu, Minggu dan hari libur nasional
                if ($date->isWeekend() || in_array($date->toDateString(), $holidays)) {
                    continue;
                }

                // Buat variasi berdasarkan user_id (acak + offset)
                $randomSeed = crc32($userId . $date->toDateString());
                srand($randomSeed);
                $status = $statuses[array_rand($statuses)];

                $checkIn = $status === 'hadir'
                    ? $date->copy()->setTime(rand(7, 8), rand(0, 59), rand(0, 59))
                    : null;

                $checkOut = $status === 'hadir'
                    ? $date->copy()->setTime(rand(16, 17), rand(0, 59), rand(0, 59))
                    : null;

                $notes = match ($status) {
                    'izin' => 'Izin keperluan mendadak',
                    'alpha' => 'Tidak hadir tanpa keterangan',
                    default => null,
                };

                Attendance::create([
                    'user_id'     => $userId,
                    'date'        => $date->toDateString(),
                    'check_in'    => $checkIn,
                    'check_out'   => $checkOut,
                    'status'      => $status,
                    'notes'       => $notes,
                    'device_info' => $status === 'hadir' ? 'Android Pixel 7' : null,
                    'location'    => null,
                ]);
            }
        }
    }

    /**
     * Ambil daftar hari libur nasional Indonesia dari API
     */
    private function getIndonesianHolidays(Carbon $startDate, Carbon $endDate): array
    {
        $years = range($startDate->year, $endDate->year);
        $holidays = [];

        foreach ($years as $year) {
            try {
                $response = Http::get("https://api-harilibur.vercel.app/api?year=$year");

                if ($response->successful()) {
                    $data = $response->json();
                    foreach ($data as $item) {
                        if (isset($item['holiday_date'])) {
                            $holidayDate = Carbon::parse($item['holiday_date']);
                            if ($holidayDate->between($startDate, $endDate)) {
                                $holidays[] = $holidayDate->toDateString();
                            }
                        }
                    }
                }
            } catch (\Exception $e) {
                // Lewatkan jika gagal ambil API
                continue;
            }
        }

        return $holidays;
    }
}
