<?php

// app/Models/Fiscal.php

namespace App\Models;

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

class Fiscal extends Model
{
    use HasFactory;

    protected $table = 'fiscals';

    protected $fillable = [
        'user_id',
        'full_name',
        'badge_number',
        'phone',
        'status',
        'metadata',
    ];

    protected $casts = [
        'metadata' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function markets()
    {
        return $this->belongsToMany(Market::class, 'fiscal_market_assignments')
            ->withPivot('assigned_zones', 'primary_fiscal', 'start_date', 'end_date', 'status')
            ->withTimestamps();
    }

    public function activeAssignments()
    {
        return $this->belongsToMany(Market::class, 'fiscal_market_assignments')
            ->wherePivot('status', 'active')
            ->wherePivot('start_date', '<=', now())
            ->where(function ($q) {
                $q->whereNull('fiscal_market_assignments.end_date')
                    ->orWhere('fiscal_market_assignments.end_date', '>=', now());
            })
            ->withPivot('assigned_zones', 'primary_fiscal');
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    public function occurrences()
    {
        return $this->hasMany(Occurrence::class);
    }

    public function devices()
    {
        return $this->hasMany(FiscalDevice::class);
    }

    public function locations()
    {
        return $this->hasMany(FiscalLocation::class);
    }

    public function journeys()
    {
        return $this->hasMany(FiscalJourney::class);
    }
}
