<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Contact extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'user_id', 'hash', 'contact_owner', 'company_id',
        'prefix', 'first_name', 'last_name', 'email',
        'timezone', 'address_line_1', 'address_line_2',
        'postal_code', 'city', 'state', 'country',
        'ip', 'latitude', 'longitude',
        'total_points', 'life_time_value',
        'phone', 'status', 'contact_type', 'source',
        'avatar', 'date_of_birth', 'last_activity',
    ];

    protected $casts = [
        'date_of_birth' => 'date',
        'last_activity' => 'datetime',
    ];

    public function getFullNameAttribute(): string
    {
        return trim(implode(' ', array_filter([$this->prefix, $this->first_name, $this->last_name])));
    }

    public function getInitialsAttribute(): string
    {
        $first = strtoupper(substr($this->first_name ?? '', 0, 1));
        $last  = strtoupper(substr($this->last_name  ?? '', 0, 1));
        return $first . $last ?: strtoupper(substr($this->email, 0, 2));
    }

    public function lists(): BelongsToMany
    {
        return $this->belongsToMany(ContactList::class, 'contact_list', 'contact_id', 'list_id');
    }

    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(Tag::class, 'contact_tag');
    }

    public function notes(): HasMany
    {
        return $this->hasMany(ContactNote::class)->latest();
    }

    public function activities(): HasMany
    {
        return $this->hasMany(ContactActivity::class, 'contact_id')->orderByDesc('occurred_at');
    }

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

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

    public function logActivity(string $type, string $description): void
    {
        // Set occurred_at explicitly - the DB default uses the MySQL server
        // clock, which may differ from the app timezone and break ordering
        $this->activities()->create(['type' => $type, 'description' => $description, 'occurred_at' => now()]);
        $this->update(['last_activity' => now()]);
    }
}
