<?php

namespace App\Models;

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

class KitchenTicket extends Model
{
    use HasFactory;

    protected $fillable = [
        'ticket_number',
        'order_id',
        'branch_id',
        'station',
        'priority',
        'status',
        'items',
        'special_instructions',
        'estimated_time',
        'completed_at',
        'prepared_by',
    ];

    protected $casts = [
        'items' => 'array',
        'completed_at' => 'datetime',
    ];

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

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

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

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

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

        static::creating(function ($ticket) {
            if (!$ticket->ticket_number) {
                $ticket->ticket_number = static::generateTicketNumber();
            }
        });
    }

    public static function generateTicketNumber(): string
    {
        $prefix = 'KOT';
        $timestamp = now()->format('YmdHis');
        $sequence = static::whereDate('created_at', today())->count() + 1;
        
        return $prefix . $timestamp . str_pad($sequence, 3, '0', STR_PAD_LEFT);
    }

    public function getElapsedTimeAttribute(): int
    {
        return $this->created_at->diffInMinutes(now());
    }

    public function getPreparationTimeAttribute(): ?int
    {
        if (!$this->created_at || !$this->completed_at) {
            return null;
        }

        return $this->created_at->diffInMinutes($this->completed_at);
    }

    public function getPriorityColorAttribute(): string
    {
        return match($this->priority) {
            'low' => '#10B981',      // green
            'normal' => '#3B82F6',   // blue
            'high' => '#F59E0B',     // amber
            'urgent' => '#EF4444',   // red
            default => '#6B7280',    // gray
        };
    }

    public function getStatusColorAttribute(): string
    {
        return match($this->status) {
            'pending' => '#F59E0B',      // amber/yellow
            'completed' => '#10B981',    // green
            default => '#6B7280',        // gray
        };
    }

    public function canBeCompleted(): bool
    {
        return $this->status === 'pending';
    }
}