<?php

namespace Database\Seeders;

use App\Models\Attendance;
use App\Models\Customer;
use Carbon\Carbon;
use Illuminate\Database\Seeder;

class AttendanceSeeder extends Seeder
{
    public function run(): void
    {
        $customers = Customer::whereHas('subscriptions', function ($q) {
            $q->where('status', 'active');
        })->get();

        foreach ($customers as $customer) {
            $subscription = $customer->activeSubscription;

            if (!$subscription) {
                continue;
            }

            // إنشاء حضور عشوائي للأيام السابقة
            $days = random_int(5, 20);

            for ($i = 0; $i < $days; $i++) {
                $date = Carbon::today()->subDays(random_int(1, 30));

                // تجنب تكرار نفس اليوم
                if (Attendance::where('customer_id', $customer->id)
                    ->whereDate('check_in', $date)
                    ->exists()) {
                    continue;
                }

                $checkIn = $date->copy()->setTime(random_int(8, 11), random_int(0, 59));
                $checkOut = $checkIn->copy()->addHours(random_int(1, 3));

                Attendance::create([
                    'customer_id' => $customer->id,
                    'subscription_id' => $subscription->id,
                    'check_in' => $checkIn,
                    'check_out' => $checkOut,
                    'status' => 'checked_out',
                    'verified_by' => 1,
                    'created_at' => $checkIn,
                    'updated_at' => $checkOut
                ]);
            }
        }
    }
}
