<?php

// app/Models/FiscalDevice.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class FiscalDevice extends Model
{
    use HasFactory;

    protected $fillable = [
        'fiscal_id', 'device_id', 'device_model', 'device_os',
        'app_version', 'last_sync_at', 'last_location_lat',
        'last_location_lng', 'battery_level', 'status',
    ];

    protected $casts = [
        'last_sync_at' => 'datetime',
        'last_location_lat' => 'decimal:8',
        'last_location_lng' => 'decimal:8',
        'battery_level' => 'integer',
    ];

    public function fiscal()
    {
        return $this->belongsTo(Fiscal::class);
    }

    public function updateLocation($latitude, $longitude, $batteryLevel = null)
    {
        $this->update([
            'last_location_lat' => $latitude,
            'last_location_lng' => $longitude,
            'battery_level' => $batteryLevel ?? $this->battery_level,
            'last_sync_at' => now(),
        ]);

        $this->fiscal->locations()->create([
            'latitude' => $latitude,
            'longitude' => $longitude,
            'recorded_at' => now(),
        ]);
    }
}
