<?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 Customer extends Model
{
    use HasFactory;

    protected $fillable = [
        'restaurant_id',
        'name',
        'phone',
        'email',
        'address',
        'total_orders',
        'total_spent',
        'last_order_at',
        'preferences',
        'is_active',
    ];

    protected $casts = [
        'total_spent' => 'decimal:2',
        'last_order_at' => 'datetime',
        'preferences' => 'array',
        'is_active' => 'boolean',
    ];

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

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

    public function getFormattedPhoneAttribute(): string
    {
        // Format Kenyan phone numbers
        $phone = preg_replace('/[^0-9]/', '', $this->phone);
        
        if (str_starts_with($phone, '254')) {
            return '+' . $phone;
        } elseif (str_starts_with($phone, '0')) {
            return '+254' . substr($phone, 1);
        } else {
            return '+254' . $phone;
        }
    }

    public function getAverageOrderValueAttribute(): float
    {
        if ($this->total_orders === 0) {
            return 0;
        }

        return $this->total_spent / $this->total_orders;
    }

    public function getCustomerTypeAttribute(): string
    {
        if ($this->total_orders >= 50) {
            return 'VIP';
        } elseif ($this->total_orders >= 20) {
            return 'Loyal';
        } elseif ($this->total_orders >= 5) {
            return 'Regular';
        } else {
            return 'New';
        }
    }

    public function updateStats(): void
    {
        $orders = $this->orders()->where('status', 'completed');
        
        $this->update([
            'total_orders' => $orders->count(),
            'total_spent' => $orders->sum('total_amount'),
            'last_order_at' => $orders->latest()->first()?->created_at,
        ]);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeVip($query)
    {
        return $query->where('total_orders', '>=', 50);
    }

    public function scopeLoyal($query)
    {
        return $query->where('total_orders', '>=', 20);
    }

    public function scopeRegular($query)
    {
        return $query->where('total_orders', '>=', 5);
    }

    public function scopeNew($query)
    {
        return $query->where('total_orders', '<', 5);
    }
}