<?php

namespace App\Actions\Leave;

use App\Contracts\LeaveRepositoryInterface;
use App\Models\AttendanceRecord;
use App\Models\LeaveApplication;
use Carbon\Carbon;
use Carbon\CarbonPeriod;

class ApproveLeaveAction
{
    public function __construct(
        protected LeaveRepositoryInterface $leaveRepository
    ) {}

    public function execute(LeaveApplication $application, int $approverId, ?string $notes = null): bool
    {
        if ($application->status !== 'pending') {
            return false;
        }

        $updated = $this->leaveRepository->updateStatus($application, 'approved', $approverId, null);

        if ($updated) {
            $this->leaveRepository->addHistory($application->id, $approverId, 'approve', $notes ?? 'Pengajuan izin disetujui');
            \App\Events\LeaveStatusUpdatedEvent::dispatch($application, 'approved', $notes);

            // Format tanggal awal dan akhir
            $startDate = Carbon::parse($application->start_date)->toDateString();
            $endDate = Carbon::parse($application->end_date)->toDateString();

            $period = CarbonPeriod::create($startDate, $endDate);
            $statusLabel = ucfirst($application->type); // 'Izin' / 'Sakit'

            foreach ($period as $date) {
                AttendanceRecord::updateOrCreate(
                    [
                        'user_id' => $application->user_id,
                        'date' => $date->toDateString(),
                    ],
                    [
                        'status' => $statusLabel,
                    ]
                );
            }
        }

        return $updated;
    }
}
