<?php

namespace App\Filament\Resources\AttendanceResource\Pages;

use App\Filament\Resources\AttendanceResource;
use App\Models\ActivityRecord;
use App\Models\UserDevice;
use Filament\Resources\Pages\CreateRecord;

class CreateAttendance extends CreateRecord
{
    protected static string $resource = AttendanceResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // Get device info from user's registered device
        $userId = $data['user_id'] ?? null;
        if ($userId) {
            $deviceInfo = UserDevice::getDeviceInfoForBackdate($userId);

            // Only add device info if not already present
            if (empty($data['check_in_device_model'])) {
                $data['check_in_device_model'] = $deviceInfo['device_model'];
                $data['check_in_device_brand'] = $deviceInfo['device_brand'];
                $data['check_in_os_version'] = $deviceInfo['os_version'];
                $data['check_in_app_version'] = $deviceInfo['app_version'];
            }

            // Add checkout device info if checkout time is set
            if (!empty($data['check_out_time']) && empty($data['check_out_device_model'])) {
                $data['check_out_device_model'] = $deviceInfo['device_model'];
                $data['check_out_device_brand'] = $deviceInfo['device_brand'];
                $data['check_out_os_version'] = $deviceInfo['os_version'];
                $data['check_out_app_version'] = $deviceInfo['app_version'];
            }
        }

        return $data;
    }

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