<?php

namespace App\Repositories;

use App\Models\SopPhase;
use App\Models\SopStep;
use App\Support\IdFormatter;
use Illuminate\Support\Collection;

class SopStepRepository
{
    public function getAllPhasesWithSteps(?string $orgHex = null): Collection
    {
        $query = SopPhase::with('steps')
            ->orderBy('sort_order');

        if ($orgHex) {
            $bin = IdFormatter::hexToBinary($orgHex);
            if ($bin) {
                $query->where('organization_id', $bin);
            }
        }

        return $query->get();
    }

    public function getStepById(int $id): ?SopStep
    {
        return SopStep::find($id);
    }

    public function updateStep(int $id, array $data): SopStep
    {
        $step = SopStep::findOrFail($id);
        $step->update($data);
        return $step->fresh();
    }

    public function getStepWithPhase(int $id): ?SopStep
    {
        return SopStep::with('phase')->find($id);
    }
}
