<?php

namespace App\Models;

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

class KitchenIssuance extends Model
{
    use HasFactory;

    protected $fillable = [
        'issuance_number',
        'restaurant_id',
        'branch_id',
        'issued_by',
        'received_by',
        'status',
        'notes',
        'issued_at',
        'received_at',
    ];

    protected $casts = [
        'issued_at' => 'datetime',
        'received_at' => 'datetime',
    ];

    protected $appends = ['total_cost', 'total_items'];

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

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

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

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

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

    public function getTotalCostAttribute(): float
    {
        return $this->items->sum('total_cost');
    }

    public function getTotalItemsAttribute(): int
    {
        return $this->items->count();
    }

    public function getStatusDisplayAttribute(): string
    {
        return match($this->status) {
            'pending' => 'Pending',
            'received' => 'Received',
            'cancelled' => 'Cancelled',
            default => ucfirst($this->status),
        };
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($issuance) {
            if (!$issuance->issuance_number) {
                $issuance->issuance_number = static::generateIssuanceNumber();
            }
            if (!$issuance->issued_at) {
                $issuance->issued_at = now();
            }
        });
    }

    public static function generateIssuanceNumber(): string
    {
        $prefix = 'KI';
        $date = now()->format('Ymd');
        $sequence = static::whereDate('created_at', today())->count() + 1;
        
        return $prefix . $date . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeReceived($query)
    {
        return $query->where('status', 'received');
    }

    public function scopeCancelled($query)
    {
        return $query->where('status', 'cancelled');
    }

    public function scopeToday($query)
    {
        return $query->whereDate('issued_at', today());
    }

    public function scopeThisWeek($query)
    {
        return $query->whereBetween('issued_at', [now()->startOfWeek(), now()->endOfWeek()]);
    }

    public function scopeThisMonth($query)
    {
        return $query->whereMonth('issued_at', now()->month)
            ->whereYear('issued_at', now()->year);
    }
}
