<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Attendance\AttendanceDetail;
use App\Models\Attendance\AttendancePunchDetail;
use Carbon\Carbon;

class AttendancePunchDetailSeeder extends Seeder
{
    public function run(): void
    {
        $details = AttendanceDetail::where('attendance_status', 'P')->get();

        foreach ($details as $detail) {

            $date = Carbon::parse($detail->attendance->attendance_date);

            // Clear existing punches (safe re-run)
            AttendancePunchDetail::where('attendance_detail_id', $detail->id)->delete();

            $punches = [
                // Morning IN
                [
                    'sequence_no' => 1,
                    'punch_type' => 'IN',
                    'punch_time' => $date->copy()->setTime(8, 0),
                ],
                // Lunch OUT
                [
                    'sequence_no' => 2,
                    'punch_type' => 'OUT',
                    'punch_time' => $date->copy()->setTime(12, 0),
                ],
                // Lunch IN
                [
                    'sequence_no' => 3,
                    'punch_type' => 'IN',
                    'punch_time' => $date->copy()->setTime(13, 0),
                ],
                // Evening OUT
                [
                    'sequence_no' => 4,
                    'punch_type' => 'OUT',
                    'punch_time' => $date->copy()->setTime(17, 0),
                ],
            ];

            // Random gate pass (afternoon)
            if (rand(0, 1)) {
                $punches[] = [
                    'sequence_no' => 5,
                    'punch_type' => 'IN',
                    'punch_time' => $date->copy()->setTime(15, 30),
                ];
            }

            foreach ($punches as $punch) {
                AttendancePunchDetail::create([
                    'attendance_detail_id' => $detail->id,
                    'sequence_no' => $punch['sequence_no'],
                    'punch_type' => $punch['punch_type'],
                    'punch_time' => $punch['punch_time'],
                    'source' => 'BIOMETRIC',
                ]);
            }
        }
    }
}
