<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Contact extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'name',
        'email',
        'phone',
        'type',
        'notes',
        'birthday',
    ];

    protected $casts = [
        'birthday' => 'date:Y-m-d',
    ];

    const TYPES = ['privat', 'arbeit', 'kunde', 'sonstiges'];

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

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

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

    // ── Scopes ────────────────────────────────────────────────────────────

    public function scopeForUser(Builder $query, string $userId): Builder
    {
        return $query->where('user_id', $userId);
    }

    public function scopeSearch(Builder $query, string $term): Builder
    {
        return $query->where(function ($q) use ($term) {
            $q->where('name',  'like', "%{$term}%")
              ->orWhere('email', 'like', "%{$term}%")
              ->orWhere('phone', 'like', "%{$term}%");
        });
    }

    // ── Helpers ───────────────────────────────────────────────────────────

    public function initials(): string
    {
        $parts = explode(' ', trim($this->name));
        if (count($parts) >= 2) {
            return strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1));
        }
        return strtoupper(substr($this->name, 0, 2));
    }

    public function typeLabel(): string
    {
        return match ($this->type) {
            'privat'    => 'Privat',
            'arbeit'    => 'Arbeit',
            'kunde'     => 'Kunde',
            'sonstiges' => 'Sonstiges',
            default     => 'Kontakt',
        };
    }

    public function typeClasses(): array
    {
        return match ($this->type) {
            'privat'    => ['bg' => 'bg-blue-50',   'text' => 'text-blue-700',   'avatar' => 'bg-blue-100 text-blue-700'],
            'arbeit'    => ['bg' => 'bg-indigo-50',  'text' => 'text-indigo-700', 'avatar' => 'bg-indigo-100 text-indigo-700'],
            'kunde'     => ['bg' => 'bg-green-50',   'text' => 'text-green-700',  'avatar' => 'bg-green-100 text-green-700'],
            'sonstiges' => ['bg' => 'bg-gray-50',    'text' => 'text-gray-600',   'avatar' => 'bg-gray-100 text-gray-600'],
            default     => ['bg' => 'bg-purple-50',  'text' => 'text-purple-700', 'avatar' => 'bg-purple-100 text-purple-700'],
        };
    }
}
