<?php

namespace App\Models;

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

class PurchaseOrder extends Model
{
    const STATUS_DRAFT = 0;
    const STATUS_ACTIVE = 1;
    const STATUS_RECEIVED = 2;
    const STATUS_CANCELLED = 3;

    protected $guarded = [];

    public const PURCHASE_ORDER_STATUSES = [
        ['id' => self::STATUS_DRAFT, 'name' => 'Brouillon', 'slug' => 'brouillon'],
        ['id' => self::STATUS_ACTIVE, 'name' => 'En attente', 'slug' => 'en_attente'],
        ['id' => self::STATUS_RECEIVED, 'name' => 'Reçu', 'slug' => 'reçu'],
        ['id' => self::STATUS_CANCELLED, 'name' => 'Annulé', 'slug' => 'annulé'],
    ];

    protected $casts = [
        'order_date' => 'date',
        'expected_delivery_date' => 'date',
        'status' => 'integer',
    ];

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

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

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

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

    /**
     * Get all products in this purchase order
     */
    public function getProducts()
    {
        return $this->items()->with('product')->get()->pluck('product');
    }

    /**
     * Get products relationship (alternative approach)
     */
    public function products()
    {
        return $this->belongsToMany(Product::class, 'purchase_order_items', 'purchase_order_id', 'product_id');
    }

    public static function generateUniqueReference()
    {
        $reference = 'PO-'.date('Ymd').'-'.str_pad(self::count() + 1, 3, '0', STR_PAD_LEFT);

        return $reference;
    }

    public function getStatusLabel()
    {
        return match ($this->status) {
            self::STATUS_DRAFT => 'Brouillon',
            self::STATUS_ACTIVE => 'En attente',
            self::STATUS_RECEIVED => 'Reçu',
            self::STATUS_CANCELLED => 'Annulé',
            default => 'Inconnu',
        };
    }

    public function getStatusBadge()
    {
        if ($this->status == self::STATUS_DRAFT) {
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800 border border-gray-500 min-w-30 justify-center">
                <i class="ph ph-x-circle mr-1"></i>
                Brouillon
            </span>';
        } elseif ($this->status == self::STATUS_ACTIVE) {
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 border border-blue-500 min-w-30 justify-center">
                <i class="ph ph-check-circle mr-1"></i>
                En attente
            </span>';
        } elseif ($this->status == self::STATUS_RECEIVED) {
            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>
                Reçu
            </span>';
        } elseif ($this->status == self::STATUS_CANCELLED) {
            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>
                Annulé
            </span>';
        } else {
            return '<span class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800 border border-gray-500 min-w-30 justify-center">
                <i class="ph ph-x-circle mr-1"></i>
                Inconnu
            </span>';
        }
    }


    public function getTotalAmount()
    {
        return $this->items->sum('total_price');
    }

    public function isFullyReceived()
    {
        return $this->items->every(function ($item) {
            return $item->received_quantity >= $item->quantity;
        });
    }

    public function getReceivedPercentage()
    {
        if ($this->items->count() === 0) {
            return 0;
        }

        $totalOrdered = $this->items->sum('quantity');
        $totalReceived = $this->items->sum('received_quantity');

        return $totalOrdered > 0 ? round(($totalReceived / $totalOrdered) * 100, 1) : 0;
    }
}
