<?php

namespace App\DTO;

use Carbon\Carbon;

class AttendanceEventData
{
    public function __construct(
        public int $deviceId,
        public string $deviceIdentifier,
        public string $employeePin,
        public string $attendanceTime,
        public string $verificationMethod = 'fingerprint',
        public string $attendanceStatus = 'scan',
        public string $source = 'local_fingerspot',
        public ?array $rawData = null
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            deviceId: (int) ($data['device_id'] ?? 0),
            deviceIdentifier: (string) ($data['device_identifier'] ?? 'machine'),
            employeePin: (string) ($data['employee_pin'] ?? $data['raw_user_id'] ?? ''),
            attendanceTime: (string) ($data['attendance_time'] ?? $data['timestamp'] ?? Carbon::now()->toDateTimeString()),
            verificationMethod: (string) ($data['verification_method'] ?? 'fingerprint'),
            attendanceStatus: (string) ($data['attendance_status'] ?? 'scan'),
            source: (string) ($data['source'] ?? 'local_fingerspot'),
            rawData: isset($data['raw_data']) && is_array($data['raw_data']) ? $data['raw_data'] : $data
        );
    }

    public function toArray(): array
    {
        return [
            'device_id' => $this->deviceId,
            'device_identifier' => $this->deviceIdentifier,
            'employee_pin' => $this->employeePin,
            'attendance_time' => $this->attendanceTime,
            'verification_method' => $this->verificationMethod,
            'attendance_status' => $this->attendanceStatus,
            'source' => $this->source,
            'raw_data' => $this->rawData,
        ];
    }
}
