<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Supplier extends Model
{
    use \Illuminate\Database\Eloquent\SoftDeletes;

    const STATUS_INACTIVE = false;

    const STATUS_ACTIVE = true;

    protected $guarded = [];

    protected $casts = [
        'status' => 'boolean',
    ];

    public function contact(): BelongsTo
    {
        return $this->belongsTo(Contact::class);
    }

    public function address(): BelongsTo
    {
        return $this->belongsTo(Address::class);
    }

    /**
     * Get supplier address
     */
    public function getFullAddressAttribute()
    {
        $address = $this->address;
        if (! $address) {
            return null;
        }
        $province = $address->province ? $address->province->name : "";
        $city = $address->city ? $address->city->name : "";
        return $province . ', ' . $city . ', ' . $address->commune . ', ' . $address->quarter . ', ' . $address->description;
    }


    public function purchaseOrders(): HasMany
    {
        return $this->hasMany(PurchaseOrder::class);
    }

    public function stockEntries(): HasMany
    {
        return $this->hasMany(StockEntry::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public static function generateSlug()
    {
        $slug = Str::orderedUuid();

        while (self::where('slug', $slug)->exists()) {
            $slug = Str::orderedUuid();
        }

        return $slug;
    }

    public function getStatusLabel()
    {
        return match ($this->status) {
            self::STATUS_ACTIVE => 'Actif',
            self::STATUS_INACTIVE => 'Inactif',
            default => 'Inconnu',
        };
    }

    public function getStatusBadge()
    {
        if ($this->status == self::STATUS_ACTIVE) {
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 border border-green-500 min-w-30 justify-center">
                <i class="ph ph-check-circle mr-1"></i>
                Actif
            </span>';
        } else {
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800 border border-red-500 min-w-30 justify-center">
                <i class="ph ph-x-circle mr-1"></i>
                Inactif
            </span>';
        }
    }

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

    public function scopeByCountry($query, $country)
    {
        return $query->where('country', $country);
    }

    // Accessor for last order date
    public function getLastOrderAtAttribute()
    {
        return $this->purchaseOrders()
            ->orderBy('created_at', 'desc')
            ->value('created_at');
    }

    public function hasAllRequiredFields(): array
    {
        $requiredFields = [
            ['name', 'nom'],
            ['contact_person', 'personne de contact'],
        ];

        $missing = [];

        foreach ($requiredFields as $field) {
            [$key, $label] = $field;
            $value = $this->{$key};

            // Treat null/empty string as missing; allow 0/0.00 for numeric fields if desired
            $isMissing = is_null($value) || (is_string($value) && trim($value) === '');

            if ($isMissing) {
                $missing[] = $label;
            }
        }

        if (! empty($missing)) {
            return ['success' => false, 'message' => 'Champs requis manquants: ' . implode(', ', $missing)];
        }

        return ['success' => true, 'message' => 'Tous les champs requis sont remplis'];
    }
}
