<?php

namespace App\Filament\Resources\AttendanceResource\Pages;

use App\Filament\Resources\AttendanceResource;
use App\Models\ActivityRecord;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditAttendance extends EditRecord
{
    protected static string $resource = AttendanceResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make()
                ->before(function () {
                    // Log delete action
                    ActivityRecord::log(
                        userId: auth()->id(),
                        action: 'delete',
                        entityType: 'attendance',
                        entityId: $this->record->id,
                        targetDate: $this->record->date->format('Y-m-d'),
                        oldValues: $this->record->toArray(),
                        attendanceId: $this->record->id,
                        notes: 'Dihapus oleh admin via panel'
                    );
                }),
        ];
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // Store old values for comparison
        $this->oldValues = $this->record->only([
            'type', 'status', 'check_in_time', 'check_out_time',
            'check_in_address', 'check_out_address', 'work_duration'
        ]);

        return $data;
    }

    protected array $oldValues = [];

    protected function afterSave(): void
    {
        // Log update action
        ActivityRecord::log(
            userId: auth()->id(),
            action: 'update',
            entityType: 'attendance',
            entityId: $this->record->id,
            targetDate: $this->record->date->format('Y-m-d'),
            oldValues: $this->oldValues,
            newValues: $this->record->only([
                'type', 'status', 'check_in_time', 'check_out_time',
                'check_in_address', 'check_out_address', 'work_duration'
            ]),
            attendanceId: $this->record->id,
            notes: 'Diperbarui oleh admin via panel'
        );
    }
}
