<?php

namespace ISPManager\Clients\Models;

use Botble\Base\Casts\SafeContent;
use ISPManager\Clients\Enums\ClientStatusEnum;
use Botble\Base\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use ISPManager\Clients\Models\Client;

class Contact extends BaseModel
{
    protected $table = 'contacts';
    protected $appends = [
    ];

    protected $fillable = [
        'client_id',
        'firstname',
        'middlename',
        'lastname',
        'secondlastname',
        'nid',
        'email',
        'username',
        'password',
        'phone1',
        'phone2',
        'photo',
        'notify_sms',
        'notify_whatsapp',
        'is_primary',
        'status',
        //'avatar_id',
    ];

    protected $hidden = [
        'password',
    ];

    protected $casts = [
        'status' => ClientStatusEnum::class,
        'firstname' => SafeContent::class,
        'middlename' => SafeContent::class,
        'lastname' => SafeContent::class,
        'secondlastname' => SafeContent::class,
        'nid' => SafeContent::class,
        'email' => SafeContent::class,
        'username' => SafeContent::class,
        'phone1' => SafeContent::class,
        'phone2' => SafeContent::class,
        'photo' => SafeContent::class,
        'notify_sms' => 'boolean',
        'notify_whatsapp' => 'boolean',
        'is_primary' => 'boolean',
        'password' => 'hashed',
    ];

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

        static::saving(function ($contact) {
            if ($contact->is_primary) {
                // Desactivar otros contactos primarios del mismo cliente
                static::where('client_id', $contact->client_id)
                    ->where('id', '!=', $contact->id)
                    ->where('is_primary', true)
                    ->update(['is_primary' => false]);
            }
        });
    }

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class, 'client_id');
    }
}
