<?php

namespace App\Services;

use App\Models\SopPhase;
use App\Models\SopStep;
use Illuminate\Support\Facades\DB;

class SopTemplateService
{
    protected string $templatePath;

    public function __construct()
    {
        $this->templatePath = database_path('templates/sop-default.json');
    }

    public function seedForOrganization($orgInfo): void
    {
        if (!file_exists($this->templatePath)) {
            return;
        }

        $orgBin = is_string($orgInfo) ? $orgInfo : ($orgInfo->getAttributes()['id'] ?? null);
        if (!$orgBin) return;

        $exists = SopPhase::where('organization_id', $orgBin)->exists();
        if ($exists) return;

        $phases = json_decode(file_get_contents($this->templatePath), true);
        if (empty($phases)) return;

        DB::transaction(function () use ($phases, $orgBin) {
            foreach ($phases as $phaseData) {
                $steps = $phaseData['steps'] ?? [];
                unset($phaseData['steps']);

                $phaseData['organization_id'] = $orgBin;
                $phase = SopPhase::create($phaseData);

                foreach ($steps as $stepData) {
                    $stepData['sop_phase_id'] = $phase->id;
                    SopStep::create($stepData);
                }
            }
        });
    }
}
