<?php

namespace App\Models;

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

class ShippingZone extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'cities',
        'districts',
        'base_price',
        'price_per_kg',
        'free_shipping_min',
        'delivery_days',
        'description',
        'active',
    ];

    protected $casts = [
        'cities' => 'array',
        'districts' => 'array',
        'base_price' => 'decimal:2',
        'price_per_kg' => 'decimal:2',
        'free_shipping_min' => 'decimal:2',
        'delivery_days' => 'integer',
        'active' => 'boolean',
    ];

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    public function scopeForCity($query, $city)
    {
        return $query->whereJsonContains('cities', $city)
            ->orWhereJsonContains('cities', strtolower($city))
            ->orWhereJsonContains('cities', strtoupper($city));
    }

    // Accessors
    public function getFormattedBasePriceAttribute()
    {
        return 'MT ' . number_format($this->base_price, 2, ',', '.');
    }

    public function getFormattedPricePerKgAttribute()
    {
        if (!$this->price_per_kg) {
            return 'N/A';
        }
        return 'MT ' . number_format($this->price_per_kg, 2, ',', '.') . '/kg';
    }

    public function getFormattedFreeShippingMinAttribute()
    {
        if (!$this->free_shipping_min) {
            return 'Não disponível';
        }
        return 'MT ' . number_format($this->free_shipping_min, 2, ',', '.');
    }

    public function getDeliveryEstimateAttribute()
    {
        if ($this->delivery_days === 1) {
            return '1 dia útil';
        }
        return $this->delivery_days . ' dias úteis';
    }

    // Methods
    public function calculateShipping($weight, $orderTotal)
    {
        // Verificar frete grátis
        if ($this->free_shipping_min && $orderTotal >= $this->free_shipping_min) {
            return 0;
        }

        $price = $this->base_price;

        // Adicionar custo por peso
        if ($this->price_per_kg && $weight > 0) {
            $price += $weight * $this->price_per_kg;
        }

        return round($price, 2);
    }

    public function coversCity($city)
    {
        if (!$this->cities) {
            return false;
        }

        $cityLower = strtolower($city);
        
        foreach ($this->cities as $zoneCity) {
            if (strtolower($zoneCity) === $cityLower) {
                return true;
            }
        }

        return false;
    }

    public function coversDistrict($district)
    {
        if (!$this->districts) {
            return true; // Se não tem distritos específicos, cobre todos
        }

        $districtLower = strtolower($district);
        
        foreach ($this->districts as $zoneDistrict) {
            if (strtolower($zoneDistrict) === $districtLower) {
                return true;
            }
        }

        return false;
    }
}
