<?php

namespace App\Models;

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

class Fisherman extends Model
{
    use HasFactory;

    protected $table = 'fishermen';

    protected $fillable = [
        'merchant_id',
        'registration_number',
        'fishing_license_number',
        'license_expiry_date',
        'professional_category',
        'fishing_zone',
        'vessel_owner',
        'dependent_fishermen',
        'next_of_kin_name',
        'next_of_kin_phone',
        'next_of_kin_relationship',
        'blood_type',
        'emergency_contact_phone',
        'health_insurance_number',
        'health_insurance_expiry',
        'training_certificate',
        'training_certificate_expiry',
        'medical_certificate',
        'medical_certificate_expiry',
        'status',
        'deactivated_at',
        'deactivated_reason',
        'approved_at',
        'approved_by',
        'suspended_reason',
        'suspended_at',
        'suspended_by',
        'suspended_until',
        'metadata',
    ];

    protected $casts = [
        'license_expiry_date' => 'date',
        'health_insurance_expiry' => 'date',
        'training_certificate_expiry' => 'date',
        'medical_certificate_expiry' => 'date',
        'deactivated_at' => 'datetime',
        'approved_at' => 'datetime',
        'suspended_at' => 'datetime',
        'suspended_until' => 'date',
        'vessel_owner' => 'boolean',
        'dependent_fishermen' => 'integer',
        'metadata' => 'array',
    ];

    // Status constants
    const STATUS_PENDING = 'pending';
    const STATUS_APPROVED = 'approved';
    const STATUS_ACTIVE = 'active';
    const STATUS_SUSPENDED = 'suspended';
    const STATUS_EXPIRED = 'expired';
    const STATUS_DECEASED = 'deceased';
    const STATUS_INACTIVE = 'inactive';

    const STATUS_LIST = [
        self::STATUS_PENDING => 'Pendente',
        self::STATUS_APPROVED => 'Aprovado',
        self::STATUS_ACTIVE => 'Ativo',
        self::STATUS_SUSPENDED => 'Suspenso',
        self::STATUS_EXPIRED => 'Expirado',
        self::STATUS_DECEASED => 'Falecido',
        self::STATUS_INACTIVE => 'Inativo',
    ];

    // Professional categories
    const CATEGORY_ARTISANAL = 'artisanal';
    const CATEGORY_SEMI_INDUSTRIAL = 'semi_industrial';
    const CATEGORY_INDUSTRIAL = 'industrial';
    const CATEGORY_RECREATIONAL = 'recreational';

    const CATEGORY_LIST = [
        self::CATEGORY_ARTISANAL => 'Artesanal',
        self::CATEGORY_SEMI_INDUSTRIAL => 'Semi-industrial',
        self::CATEGORY_INDUSTRIAL => 'Industrial',
        self::CATEGORY_RECREATIONAL => 'Recreativo',
    ];

    // Relationships
    public function merchant()
    {
        return $this->belongsTo(Merchant::class);
    }

    public function approvedBy()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function suspendedBy()
    {
        return $this->belongsTo(User::class, 'suspended_by');
    }

    public function vessels()
    {
        return $this->hasMany(Vessel::class, 'owner_fisherman_id');
    }

    public function licenses()
    {
        return $this->hasMany(FishingLicense::class);
    }

    public function boardings()
    {
        return $this->hasMany(Boarding::class, 'captain_id');
    }

    public function crews()
    {
        return $this->hasMany(VesselCrew::class);
    }

    public function infractions()
    {
        return $this->hasMany(FishingInfraction::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', self::STATUS_ACTIVE);
    }

    public function scopeApproved($query)
    {
        return $query->where('status', self::STATUS_APPROVED);
    }

    public function scopePending($query)
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    public function scopeSuspended($query)
    {
        return $query->where('status', self::STATUS_SUSPENDED);
    }

    // Accessors
    public function getStatusTextAttribute()
    {
        return self::STATUS_LIST[$this->status] ?? $this->status;
    }

    public function getProfessionalCategoryTextAttribute()
    {
        return self::CATEGORY_LIST[$this->professional_category] ?? $this->professional_category;
    }

    public function getLicenseExpiryDateFormattedAttribute()
    {
        return $this->license_expiry_date ? $this->license_expiry_date->format('d/m/Y') : '-';
    }

    public function getIsLicenseExpiredAttribute()
    {
        return $this->license_expiry_date && $this->license_expiry_date->isPast();
    }

    // Methods
    public function approve(int $approvedBy)
    {
        $this->update([
            'status' => self::STATUS_APPROVED,
            'approved_at' => now(),
            'approved_by' => $approvedBy,
        ]);
    }

    public function activate()
    {
        $this->update(['status' => self::STATUS_ACTIVE]);
    }

    public function suspend(string $reason = null, $until = null)
    {
        $this->update([
            'status' => self::STATUS_SUSPENDED,
            'suspended_reason' => $reason,
            'suspended_at' => now(),
            'suspended_by' => auth()->id(),
            'suspended_until' => $until,
        ]);
    }

    public function reactivate()
    {
        $this->update([
            'status' => self::STATUS_ACTIVE,
            'suspended_reason' => null,
            'suspended_at' => null,
            'suspended_by' => null,
            'suspended_until' => null,
        ]);
    }

    public function isActive()
    {
        return in_array($this->status, [self::STATUS_ACTIVE, self::STATUS_APPROVED]);
    }
}
