<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class QrAttendanceLog extends Model
{
    use HasFactory, HasUuids;

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'scanned_user_id',
        'scanner_user_id',
        'company_id',
        'attendance_id',
        'scan_type',
        'latitude',
        'longitude',
        'scan_status',
        'failure_reason',
        'device_info',
        'scanned_at',
    ];

    protected function casts(): array
    {
        return [
            'latitude' => 'decimal:8',
            'longitude' => 'decimal:8',
            'device_info' => 'array',
            'scanned_at' => 'datetime',
        ];
    }

    /**
     * Get the user that was scanned.
     */
    public function scannedUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'scanned_user_id');
    }

    /**
     * Get the admin user who performed the scan.
     */
    public function scannerUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'scanner_user_id');
    }

    /**
     * Get the company.
     */
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Get the related attendance record.
     */
    public function attendance(): BelongsTo
    {
        return $this->belongsTo(Attendance::class);
    }

    /**
     * Scope a query to only include successful scans.
     */
    public function scopeSuccessful($query)
    {
        return $query->where('scan_status', 'success');
    }

    /**
     * Scope a query to only include failed scans.
     */
    public function scopeFailed($query)
    {
        return $query->where('scan_status', 'failed');
    }

    /**
     * Scope a query to only include check-in scans.
     */
    public function scopeCheckIn($query)
    {
        return $query->where('scan_type', 'check_in');
    }

    /**
     * Scope a query to only include check-out scans.
     */
    public function scopeCheckOut($query)
    {
        return $query->where('scan_type', 'check_out');
    }

    /**
     * Scope a query for a specific date.
     */
    public function scopeForDate($query, $date)
    {
        return $query->whereDate('scanned_at', $date);
    }

    /**
     * Check if the scan was successful.
     */
    public function isSuccessful(): bool
    {
        return $this->scan_status === 'success';
    }
}
