<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Shop extends Model
{
    use LogsActivity;

    protected $table = 'shops';

    protected $fillable = [
        'contact_id',
        'name',
        'phone',
        'email',
        'address',
        'city',
        'manager_contact_id',
        'shop_account_id',
    ];

    protected $casts = [
        'contact_id' => 'integer',
        'manager_contact_id' => 'integer',
        'shop_account_id' => 'integer',
    ];

    // Relationships
    public function contact(): BelongsTo
    {
        return $this->belongsTo(Contact::class);
    }

    public function manager(): BelongsTo
    {
        return $this->belongsTo(Contact::class, 'manager_contact_id');
    }

    public function shopAccount(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'shop_account_id');
    }

    public function employees(): HasMany
    {
        return $this->hasMany(Contact::class, 'shop_id')->where('type', 'shop_employee');
    }

    // Scopes
    public function scopeByCity($query, $city)
    {
        return $query->where('city', $city);
    }

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

    // Helper methods
    public function getFullAddressAttribute()
    {
        $parts = array_filter([$this->address, $this->city]);
        return implode(', ', $parts) ?: 'No address provided';
    }

    public function getContactNameAttribute()
    {
        return $this->contact ? $this->contact->name : 'Unknown Contact';
    }

    public function getIsActiveAttribute()
    {
        return $this->contact ? $this->contact->is_active : false;
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('shop')
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
