<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;

class Account extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'business_id',
        'contact_owner_id',
        'primary_contact_id',
        'parent_account_id',
        'account_name',
        'account_number',
        'billing_address_1',
        'billing_address_2',
        'billing_city',
        'billing_province',
        'billing_zip_code',
        'billing_country_id',
        'website',
        'fax',
        'industry_id',
        'sic_code',
        'contact_method',
        'total_revenue',
        'account_type',
        'ownership',
        'originating_lead_id',
        'credit_limit',
        'payment_terms',
        'rating',
        'status',
    ];

    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 billingCountry() { return $this->belongsTo(Country::class, 'billing_country_id'); }

    public function primaryContact()
    {
        return $this->belongsTo(Contact::class, 'primary_contact_id');
    }

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

    public function parentAccount()
    {
        return $this->belongsTo(Account::class, 'parent_account_id');
    }

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

    public function deals()
    {
        return $this->belongsToMany(Deal::class, 'deal_account')->withTimestamps();
    }

    public function activities() { return $this->hasMany(Activity::class); }
    public function cases() { return $this->hasMany(CrmCase::class); }
    public function surveys() { return $this->belongsToMany(Survey::class, 'account_survey')->withTimestamps(); }
    public function campaignTargets() { return $this->morphMany(CampaignTarget::class, 'target'); }
    public function projects() { return $this->hasMany(Project::class); }

    protected $casts = [
        'contact_method' => 'array',
    ];
}
