<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Contact extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'business_id',
        'lead_id',
        'first_name',
        'last_name',
        'job_title',
        'type',
        'priority',
        'contact_owner_id',
        'marketing_source_id',
        'department',
        'company_id',
        'gender',
        'date_of_birth',
        'address_1',
        'address_2',
        'city',
        'province',
        'zip_code',
        'country_id',
        'contact_owner_id',
        'marketing_source_id',
        'industry_id',
        'description',
        'skype_id',
        'stage_id',
        'status',
        // Add other fields if needed
    ];


    public function contactPhones()
    {
        return $this->hasMany(ContactPhoneNum::class);
    }

    public function contactEmails()
    {
        return $this->hasMany(ContactEmail::class);
    }

    public function contactSocialMedia()
    {
        return $this->hasMany(ContactSocialMedia::class);
    }

    public function contactLanguages()
    {
        return $this->hasMany(ContactLanguage::class);
    }

    public function assignedUser() { return $this->belongsTo(User::class, 'contact_owner_id'); }
    public function company() { return $this->belongsTo(Company::class); }
    public function country() { return $this->belongsTo(Country::class); }
    public function stage() { return $this->belongsTo(Stage::class); }

    public function phones() {
        return $this->hasMany(ContactPhoneNum::class);
    }

    public function emails() {
        return $this->hasMany(ContactEmail::class);
    }

    public function socialMedias() {
        return $this->hasMany(ContactSocialMedia::class);
    }

    public function accounts()
    {
        return $this->belongsToMany(Account::class, 'account_contact')
            ->withPivot(['is_primary', 'role'])->withTimestamps();
    }

    public function primaryForAccounts() { return $this->hasMany(Account::class, 'primary_contact_id'); }

    public function deals()
    {
        return $this->hasMany(Deal::class, 'contact_id');
    }

    public function linkedDeals()
    {
        return $this->belongsToMany(Deal::class, 'deal_contact')
            ->withPivot('is_primary')->withTimestamps();
    }

    public function leads()
    {
        return $this->hasMany(Lead::class, 'primary_contact_id');
    }

    public function activities()
    {
        return $this->hasMany(Activity::class, 'contact_id');
    }

    public function notes()
    {
        return $this->hasMany(Note::class, 'contact_id');
    }

    public function latestActivity()
    {
        return $this->hasOne(Activity::class, 'contact_id')->latestOfMany();
    }

    public function projects() { return $this->belongsToMany(Project::class, 'contact_project')->withTimestamps(); }
    public function products() { return $this->belongsToMany(Product::class, 'contact_product')->withTimestamps(); }
    public function surveys() { return $this->belongsToMany(Survey::class, 'contact_survey')->withTimestamps(); }
    public function cases() { return $this->hasMany(CrmCase::class); }
    public function files() { return $this->morphMany(CrmFile::class, 'fileable'); }
    public function moveHistories() { return $this->hasMany(ContactMoveHistory::class); }

    public function recordMove(string $destinationType, Model $destination, ?string $reason = null): void
    {
        DB::transaction(function () use ($destinationType, $destination, $reason) {
            $this->loadMissing(['accounts', 'deals', 'activities', 'projects', 'products', 'surveys', 'files']);
            $this->moveHistories()->create([
                'business_id' => $this->business_id,
                'destination_type' => $destinationType,
                'destination_id' => $destination->getKey(),
                'moved_by' => auth()->id(),
                'reason' => $reason,
                'relationship_snapshot' => [
                    'account_ids' => $this->accounts->pluck('id')->values(),
                    'deal_ids' => $this->deals->pluck('id')->values(),
                    'activity_ids' => $this->activities->pluck('id')->values(),
                    'project_ids' => $this->projects->pluck('id')->values(),
                    'product_ids' => $this->products->pluck('id')->values(),
                    'survey_ids' => $this->surveys->pluck('id')->values(),
                    'file_ids' => $this->files->pluck('id')->values(),
                ],
            ]);
        });
    }

}
