<?php

namespace App\Models;

use App\Classes\General\Interfaces\Documentable;
use App\Classes\General\Interfaces\Contactable;
use App\Classes\ValueObjects\Constants\BusinessType;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Staudenmeir\EloquentHasManyDeep\HasManyDeep;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;

/**
 * Class Company
 * @package App\Models
 *
 * @property \App\Models\Country country_id
 * @property \App\Models\State state_id
 * @property \App\Models\District district_id
 * @property string postcode
 * @property string street_one
 * @property string street_two
 * @property integer billing_type
 */
class Company extends AbstractModel implements Documentable, Contactable
{
    use HasRelationships;
    use SoftDeletes;

    protected $table = 'companies';

    protected $dates = ['deleted_at'];

    /**
     * @return MorphMany
     */
    public function addresses(): morphMany
    {
        return $this->morphMany(Address::class, 'owner');
    }

    /**
     * @return HasMany
     */
    public function companyModules(): hasMany
    {
        return $this->hasMany(CompanyModule::class);
    }

    /**
     * @return hasManyThrough
     */
    public function employees(): hasManyThrough
    {
        return $this->hasManyThrough(User::class, CompanyModule::class, 'company_id', 'company_module_id');
    }

    public function orders()
    {
        return $this->companyModules()->where('type', '=', BusinessType::IMPORTER)->first()->orders->sortByDesc('id');
        $orders = [];

        $this->CompanyModules->each(function ($companyModule) {
                $orders[] = $companyModule->orders->sortByDesc('id');
            });

        return collect($orders);
    }


    /**
     * @return MorphMany
     */
    public function documents(): morphMany
    {
        return $this->morphMany(Document::class, 'owner');
    }

    /**
     * @return MorphMany
     */
    public function contacts(): morphMany
    {
        return $this->morphMany(Contact::class, 'owner');
    }

    /**
     * @return HasMany
     */
    public function banks(): HasMany
    {
        return $this->HasMany(BankAccount::class, 'company_id');
    }

    /**
     * @return hasManyDeep
     */
    public function parcels(): hasManyDeep
    {
        return $this->hasManyDeep(Package::class, [CompanyModule::class, Order::class, PackingList::class], ['company_id', 'company_module_id', ['owner_type', 'owner_id'], 'packing_list_id'], ['id', 'id', null, 'id']);
    }

}
