<?php

namespace Hilco\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Support\Facades\DB;

/**
 * Hilco\Models\BusinessChain
 * @property-read integer $id
 * @property-read string $chain_identifier
 * @property-read string $chain_level_1
 * @property-read string $chain_level_2
 * @property-read string $chain_level_3
 * @property-read string $chain_level_4
 * @property-read string $chain_level_5
 * @property-read string $chain_level_6
 * @property-read string $chain_level_7
 * @property-read string $chain_level_8
 * @property-read string $chain_level_9
 * @property-read Collection|BusinessChain_Customer[] $businessChainCustomers
 * @property-read Collection|Customer[] $customers
 */
class BusinessChain extends WebModel {
    protected $table = "BusinessChains";

    /**
     * @return HasMany
     */
    public function businessChainCustomers(): HasMany {
        return $this->hasMany(BusinessChain_Customer::class, "businesschain_id", "id");
    }

    /**
     * @return HasManyThrough
     */
    public function customers(): HasManyThrough {
        return $this->hasManyThrough(Customer::class, BusinessChain_Customer::class, "businesschain_id", "id", "id", "customer_id")
            ->where("BusinessChain_Customer.deleted_at", "=", DB::raw("0"));
    }

    /**
     * @return mixed|string
     */
    public function getLowestPopulatedChainLink() {
        $lowestLink = $this->chain_level_1;
        for ($level = 2; $level <= 9; $level++) {
            $chain_level = "chain_level_" . $level;
            $nextLink = $this->$chain_level;
            if (empty($nextLink)) {
                return $lowestLink;
            } else {
                $lowestLink = $nextLink;
            }
        }
        return $lowestLink;
    }
}