<?php

// app/Models/Merchant.php

namespace App\Models;

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

class Merchant extends Model
{
    use HasFactory;

    protected $table = 'merchants';

    protected $fillable = [
        'business_type_id',
        'full_name',
        'birth_date',
        'identity_number',
        'identity_type',
        'tax_number',
        'phone',
        'alternate_phone',
        'email',
        'address',
        'photo_url',
        'status',
        'approved_by',
        'approved_at',
        'metadata',
    ];

    protected $casts = [
        'birth_date' => 'date',
        'approved_at' => 'datetime',
        'metadata' => 'array',
    ];

    const STATUS = ['pending' => 'Pendente', 'approved' => 'Aprovado', 'active' => 'Ativo', 'suspended' => 'Suspenso'];

    /**
     * Relacionamento com BusinessType
     */
    public function businessType()
    {
        return $this->belongsTo(BusinessType::class);
    }

    /**
     * Quem aprovou este merchant
     */
    public function approvedBy()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * Bancadas do merchant
     */
    public function stalls()
    {
        return $this->hasMany(Stall::class);
    }

    /**
     * Histórico de ocupação de bancadas
     */
    public function stallHistories()
    {
        return $this->hasMany(StallHistory::class);
    }

    /**
     * CORREÇÃO: Cartões RFID do merchant (relacionamento correto)
     */
    public function rfidCards()
    {
        return $this->hasMany(RfidCard::class);
    }

    /**
     * Alias para o cartão RFID ativo (mais comum)
     */
    public function rfidCard()
    {
        return $this->hasOne(RfidCard::class)->where('status', 'active')->latest();
    }

    /**
     * Conta digital do merchant
     */
    public function digitalAccount()
    {
        return $this->hasOne(DigitalAccount::class);
    }

    /**
     * Dependentes do merchant
     */
    public function dependents()
    {
        return $this->hasMany(MerchantDependent::class);
    }

    /**
     * Documentos do merchant
     */
    public function documents()
    {
        return $this->hasMany(MerchantDocument::class);
    }

    /**
     * Pagamentos do merchant
     */
    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    /**
     * Isenções de taxas do merchant
     */
    public function taxExemptions()
    {
        return $this->hasMany(TaxExemption::class);
    }

    /**
     * Ocorrências envolvendo este merchant
     */
    public function occurrences()
    {
        return $this->hasMany(Occurrence::class);
    }

    /**
     * Verifica se o merchant está ativo
     */
    public function isActive(): bool
    {
        return $this->status === 'active' && $this->user && $this->user->status === 1;
    }

    /**
     * Verifica se está pendente
     */
    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    /**
     * Verifica se está bloqueado
     */
    public function isBlocked(): bool
    {
        return $this->status === 'blocked';
    }

    /**
     * Aprova o merchant
     */
    public function approve(int $approverId): self
    {
        $this->update([
            'status' => 'active',
            'approved_by' => $approverId,
            'approved_at' => now(),
        ]);

        // Atualiza status do user
        if ($this->user) {
            $this->user->update(['status' => 1]);
        }

        return $this;
    }

    /**
     * Bloqueia o merchant
     */
    public function block(?string $reason = null): self
    {
        $metadata = $this->metadata ?? [];
        $metadata['blocked_at'] = now();
        $metadata['block_reason'] = $reason;

        $this->update([
            'status' => 'blocked',
            'metadata' => $metadata,
        ]);

        // Bloqueia user
        if ($this->user) {
            $this->user->update(['status' => 0]);
        }

        return $this;
    }

    /**
     * Desbloqueia o merchant
     */
    public function unblock(): self
    {
        $metadata = $this->metadata ?? [];
        unset($metadata['blocked_at']);
        unset($metadata['block_reason']);
        $metadata['unblocked_at'] = now();

        $this->update([
            'status' => 'active',
            'metadata' => $metadata,
        ]);

        // Reativa user
        if ($this->user) {
            $this->user->update(['status' => 1]);
        }

        return $this;
    }

    /**
     * Scope para merchants ativos
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope para merchants pendentes
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    /**
     * Scope para merchants bloqueados
     */
    public function scopeBlocked($query)
    {
        return $query->where('status', 'blocked');
    }

    /**
     * Scope para busca
     */
    public function scopeSearch($query, string $term)
    {
        return $query->where(function ($q) use ($term) {
            $q->where('full_name', 'like', "%{$term}%")
                ->orWhere('identity_number', 'like', "%{$term}%")
                ->orWhere('phone', 'like', "%{$term}%")
                ->orWhere('email', 'like', "%{$term}%");
        });
    }
}
