<?php

namespace App\Models;

use App\Classes\General\Interfaces\Documentable;
use App\Classes\General\Interfaces\Transactionable;
use App\Classes\General\Traits\LogData;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Scopes\CustomerBookingsScope;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Staudenmeir\EloquentHasManyDeep\HasManyDeep;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;

/**
 * Class Booking
 * @package App\Models
 *
 * @property \App\Models\Company company_id
 * @property \App\Models\Bank transferable_bank_id
 * @property string marking
 * @property string reference
 * @property float fix_amount
 * @property int convertible_currency_id
 * @property int conversion_currency_id
 */
class Booking extends AbstractModel implements Documentable, Transactionable
{
    use HasRelationships;
    use SoftDeletes;
    use LogData;

    protected $table = 'bookings';

    protected $dates = ['deleted_at'];

    /**
     * @return BelongsTo
     */
    public function company(): BelongsTo
    {
        return $this->BelongsTo(Company::class, 'company_id')->withTrashed();
    }

    /**
     * @return BelongsTo
     */
    public function service(): BelongsTo
    {
        return $this->BelongsTo(ServiceType::class, 'service_id');
    }

    /**
     * @return BelongsTo
     */
    public function bank(): BelongsTo
    {
        return $this->BelongsTo(Bank::class, 'bank_id')->withTrashed();
    }

    /**
     * @return BelongsTo
     */
    public function fixedCurrency(): BelongsTo
    {
        return $this->BelongsTo(Currency::class, 'fix_currency_id');
    }

    /**
     * @return BelongsTo
     */
    public function convertibleCurrency(): BelongsTo
    {
        return $this->BelongsTo(Currency::class, 'convertible_currency_id');
    }

    /**
     * @return BelongsTo
     */
    public function conversionCurrency(): BelongsTo
    {
        return $this->BelongsTo(Currency::class, 'conversion_currency_id');
    }

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

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

    /**
     * @return hasManyDeep
     */
    public function bills(): hasManyDeep
    {
        return $this->hasManyDeep(Transaction::class, [Transaction::class.' as alias'], [['owner_type', 'owner_id'], ['owner_type', 'owner_id']], [null, null]);
    }

    protected static function booted()
    {
        if (auth()->user()) {
            if (auth()->user()->type === RoleTypes::USER) {
                static::addGlobalScope(new CustomerBookingsScope);
            }
        }
    }


}
