<?php

namespace App\Models;

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

class Sale extends Model
{
    // Status constants
    const STATUS_PENDING = 0;
    const STATUS_COMPLETED = 1;
    const STATUS_CANCELLED = 2;

    const PAYMENT_METHOD_CASH = 1;
    const PAYMENT_METHOD_DEBT = 2;

    const PAYMENT_METHOD_MOBILE_MONEY = 3;
    const PAYMENT_METHOD_CARD = 4;
    const PAYMENT_METHOD_TRANSFER = 5;

    const PAYMENT_METHODS = [
        ['id' => 1, 'name' => 'Espèces', 'code' => 'cash', 'icon' => 'ph-money', 'color' => '#10B981'],
        ['id' => 2, 'name' => 'Dette', 'code' => 'debt', 'icon' => 'ph-credit-card', 'color' => '#F59E0B'],
        ['id' => 3, 'name' => 'Mobile Money', 'code' => 'mobile_money', 'icon' => 'ph-device-mobile', 'color' => '#8B5CF6'],
        ['id' => 4, 'name' => 'Carte', 'code' => 'card', 'icon' => 'ph-credit-card', 'color' => '#3B82F6'],
        ['id' => 5, 'name' => 'Virement', 'code' => 'transfer', 'icon' => 'ph-bank', 'color' => '#F59E0B'],
    ];

    const SALE_TYPE_PRESCRIPTION = 1;
    const SALE_TYPE_OTC = 2;
    const SALE_TYPE_WHOLESALE = 3;

    const SALE_TYPES = [
        [
            'id' => 1,
            'name' => 'Vente avec ordonnance',
            'code' => 'prescription_sale',
        ],
        [
            'id' => 2,
            'name' => 'Vente sans ordonnance',
            'code' => 'otc_sale',
        ],
        [
            'id' => 3,
            'name' => 'Vente en gros',
            'code' => 'wholesale',
        ]
    ];

    const SALE_STATUS = [
        ['id' => 0, 'name' => 'En attente', 'slug' => 'pending'],
        ['id' => 1, 'name' => 'Complétée', 'slug' => 'completed'],
        ['id' => 2, 'name' => 'Annulée', 'slug' => 'cancelled'],
    ];

    protected $guarded = [];

    protected $casts = [
        'subtotal' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'paid_amount' => 'decimal:2',
        'change_amount' => 'decimal:2',
    ];

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

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

    public function soldBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

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

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

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

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

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

    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('created_at', [$startDate, $endDate]);
    }

    public function scopeByPaymentMethod($query, $paymentMethodId)
    {
        return $query->where('payment_method_id', $paymentMethodId);
    }

    // Accessors
    public function getProfitAttribute()
    {
        return $this->items->sum('profit');
    }

    // Helper methods
    public function getStatusLabel()
    {
        return match ($this->status) {
            self::STATUS_PENDING => 'En attente',
            self::STATUS_COMPLETED => 'Complétée',
            self::STATUS_CANCELLED => 'Annulée',
            default => 'Inconnu'
        };
    }

    public function getStatusBadge()
    {
        return match ($this->status) {
            self::STATUS_COMPLETED => '<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>Complété</span>',
            self::STATUS_CANCELLED => '<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>',
            default => '<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">En attente</span>'
        };
    }

    public function getTotalAmount()
    {
        return $this->total_amount ?? 0;
    }

    public function isCompleted()
    {
        return $this->status === self::STATUS_COMPLETED;
    }

    public function isPending()
    {
        return $this->status === self::STATUS_PENDING;
    }

    public static function generateUniqueSaleNumber()
    {
        // Prefix: SL + YYYYMMDD
        $prefix = 'SL'.date('Ymd');

        // Find the last sale for today (sequence resets daily)
        $lastSaleToday = Sale::where('sale_number', 'like', $prefix.'%')
            ->orderBy('sale_number', 'desc')
            ->first();

        $lastSequence = $lastSaleToday
            ? (int) substr($lastSaleToday->sale_number, strlen($prefix))
            : 0;

        return $prefix.str_pad((string) ($lastSequence + 1), 5, '0', STR_PAD_LEFT);
    }

    public function getPaymentMethodBadge(): string
    {
        if (! $this->paymentMethod) {
            return '';
        }
        return '<span class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium text-gray-800 border border-gray-500 min-w-30 justify-center"> <i class="ph ph-tag mr-1"></i>'.$this->getPaymentMethodLabel().'</span>';
    }

    public function getPaymentMethodLabel()
    {
        return match ($this->payment_method_id) {
            self::PAYMENT_METHOD_CASH => 'Espèces',
            self::PAYMENT_METHOD_DEBT => 'Dette',
            self::PAYMENT_METHOD_MOBILE_MONEY => 'Mobile Money',
            self::PAYMENT_METHOD_CARD => 'Carte',
            self::PAYMENT_METHOD_TRANSFER => 'Virement',
            default => 'Inconnu',
        };
    }

    public function getSaleTypeBadge(): string
    {
        if (! $this->saleType) {
            return '';
        }
        return '<span class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium text-gray-800 border border-gray-500 min-w-30 justify-center"> <i class="ph ph-tag mr-1"></i>'.$this->getSaleTypeLabel().'</span>';
    }

    public function getSaleTypeLabel()
    {
        return match ($this->sale_type_id) {
            self::SALE_TYPE_PRESCRIPTION => 'Vente avec ordonnance',
            self::SALE_TYPE_OTC => 'Vente sans ordonnance',
            self::SALE_TYPE_WHOLESALE => 'Vente en gros',
            default => 'Inconnu',
        };
    }
}
