<?php

namespace kernel\app_modules\user_stage\models;

class User extends \kernel\modules\user\models\User
{

    public function stageProgress(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(UserStageProgress::class);
    }

    public function stages()
    {
        return $this->belongsToMany(UserStage::class, 'user_stage_progress')
            ->withPivot(['is_completed', 'completed_at', 'is_closed', 'status'])
            ->withTimestamps();
    }

    // Метод для отметки этапа как завершенного
    public function completeStage(UserStage $stage): void
    {
        $this->stages()->updateExistingPivot($stage->id, [
            'is_completed' => true,
            'status' => 3,
            'completed_at' => date('Y-m-d H:i')
        ]);
    }

    public function openStage(UserStage $stage): void
    {
        $this->stages()->updateExistingPivot($stage->id, [
            'status' => 2,
            'is_closed' => 0,
        ]);
    }

    public function closeStage(UserStage $stage): void
    {
        $this->stages()->updateExistingPivot($stage->id, [
            'status' => 1,
            'is_closed' => 1,
        ]);
    }

    // Проверка, завершен ли этап
    public function hasCompletedStage(UserStage $stage)
    {
        return $this->stages()
            ->where('stage_id', $stage->id)
            ->where('is_completed', true)
            ->exists();
    }

    public function isClosed(UserStage $stage)
    {
        return $this->stages()
            ->where('user_stage_id', $stage->id)
            ->where('is_closed', true)
            ->exists();
    }

    public function hasStages(): bool
    {
        if ($this->stages()) {
            return true;
        }

        return false;
    }

    // Получение текущего этапа (первый незавершенный)
    public function currentStage()
    {
        return $this->stages()
            ->where('is_completed', false)
            ->orderBy('stage_id')
            ->first();
    }

}