<?php

namespace Modules\MultiPOS\Entities;

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

class PosMachine extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'restaurant_id',
        'branch_id',
        'device_id',
        'alias',
        'status',
        'registered_by',
        'approved_by',
        'approved_at',
        'declined_by',
        'declined_at',
        'declined_reason',
        'last_seen_at',
        'registered_at',
    ];

    protected $casts = [
        'approved_at' => 'datetime',
        'declined_at' => 'datetime',
        'last_seen_at' => 'datetime',
        'registered_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    protected $attributes = [
        'status' => 'pending',
    ];

    /**
     * Generate a unique device ID
     */
    public static function generateDeviceId(): string
    {
        return (string) Str::ulid();
    }

    /**
     * Boot the model
     */
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->registered_at)) {
                $model->registered_at = now();
            }
            if (empty($model->device_id)) {
                $model->device_id = self::generateDeviceId();
            }
        });
    }

    /**
     * Relationships
     */
    public function restaurant(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Restaurant::class);
    }

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

    public function registeredBy(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'registered_by');
    }

    public function approvedBy(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'approved_by');
    }

    public function declinedBy(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'declined_by');
    }

    public function orders(): HasMany
    {
        return $this->hasMany(\App\Models\Order::class, 'pos_machine_id');
    }

    /**
     * Scopes
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

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

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

    public function scopeForBranch($query, int $branchId)
    {
        return $query->where('branch_id', $branchId);
    }

    public function scopeForRestaurant($query, int $restaurantId)
    {
        return $query->where('restaurant_id', $restaurantId);
    }

    /**
     * Check if machine is active
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    /**
     * Check if machine is pending
     */
    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    /**
     * Check if machine is declined
     */
    public function isDeclined(): bool
    {
        return $this->status === 'declined';
    }

    /**
     * Update last seen timestamp
     */
    public function updateLastSeen(): void
    {
        $this->update(['last_seen_at' => now()]);
    }

    /**
     * Get status badge color
     */
    public function getStatusColorAttribute(): string
    {
        return match($this->status) {
            'active' => 'success',
            'pending' => 'warning',
            'declined' => 'danger',
            default => 'secondary',
        };
    }
}

