<?php

namespace App\Models\Applications;

use App\Events\Applications\ApplicationStatusChanged;
use App\Models\Companies\CompanyMember;
use App\Models\Objects\Field;
use App\Models\Products\Product;
use App\Models\User;
use App\Support\HasObjectsTrait;
use App\Support\RelationValuesTrait;
use App\Support\UuidScopeTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Application extends Model {
    use UuidScopeTrait, SoftDeletes, HasObjectsTrait, RelationValuesTrait;

    protected $dates = [
    ];

    protected $fillable = [
        'submitter_id',
        'product_id',
        'status',
        'number',
        'applicant'
    ];

    protected $hidden = [
        'id'
    ];



    public function submitter(): BelongsTo {
        return $this->belongsTo(User::class);
    }

    public function product(): BelongsTo {
        return $this->belongsTo(Product::class);
    }

    public function conclusions(): HasMany {
        return $this->hasMany(Conclusion::class);
    }



    public function getTitleAttribute(): string {
        return "Заявка №{$this->number} от " . $this->created_at->format('d.m.Y');
    }

    public function getParsedStatusAttribute(): array {
        return ['name' => $this->status, 'title' => ApplicationStatus::TITLES[$this->status] ?? null];
    }

    public function getPropertiesAttribute(): ?Model {
        return $this->getObject('application-properties', 'properties');
    }

    public function getAddresseesAttribute() {
        return CompanyMember::query()->mainCompany()->whereHas('objects', function($query) {
            Field::applyFilters($query, collect(['types' => 'company-member-properties', 'moderate-permissions' => 'applications']));
        })->get();
    }


    public function submit(): bool {
        $res = $this->update(['status' => ApplicationStatus::PROCESSING]);
        event(new ApplicationStatusChanged($this));
        return $res;
    }
    public function complete(): bool {
        $res = $this->update(['status' => ApplicationStatus::COMPLETED]);
        event(new ApplicationStatusChanged($this));
        return $res;
    }


    public function setNumber() {
        if (!$this->number) $this->update(['number' => self::generateNumber()]);
    }

    public static function generateNumber($start = 100, $digits = 5): string {
        $res = intval(static::query()->max('number') ?? $start) + 1;
        while (strlen($res) < $digits) {
            $res = "0{$res}";
        }
        return trim($res);
    }


}
