<?php

namespace App\Http\Controllers;

use App\Models\SopStep;
use App\Repositories\SopStepRepository;
use App\Http\Requests\SopStepRequest;
use App\Support\IdFormatter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SopStepController extends Controller
{
    public function __construct(
        protected SopStepRepository $repository
    ) {}

    public function data(): JsonResponse
    {
        $this->authorize('viewAny', SopStep::class);

        $orgHex = $this->getOrgHex();
        $phases = $this->repository->getAllPhasesWithSteps($orgHex);

        $result = $phases->map(function ($phase) {
            return [
                'id' => $phase->id,
                'num' => $phase->num,
                'name' => $phase->name,
                'desc' => $phase->desc,
                'steps' => $phase->steps->map(function ($step) {
                    $tpls = array_map(fn($tpl, $i) => [
                        'id' => $i,
                        'tab_label' => $tpl['tab_label'] ?? '',
                        'purpose' => $tpl['purpose'] ?? '',
                        'content' => $tpl['content'] ?? '',
                        'shortcut' => $tpl['shortcut'] ?? '',
                    ], $step->templates ?? [], array_keys($step->templates ?? []));

                    $items = array_map(fn($c, $i) => [
                        'id' => $i,
                        'content' => $c,
                    ], $step->checklist ?? [], array_keys($step->checklist ?? []));

                    return [
                        'id' => $step->id,
                        'num' => $step->num,
                        'icon' => $step->icon,
                        'sublabel' => $step->sublabel,
                        'name' => $step->name,
                        'desc' => $step->desc,
                        'note' => $step->note,
                        'tip' => $step->tip,
                        'tags' => $step->tags,
                        'sources' => $step->sources,
                        'kpis' => $step->kpis,
                        'templates' => $tpls,
                        'checklist_items' => $items,
                    ];
                }),
            ];
        });

        return response()->json(['phases' => $result]);
    }

    public function update(SopStepRequest $request, int $id): JsonResponse
    {
        $step = $this->repository->getStepWithPhase($id);
        if (!$step) {
            return response()->json(['success' => false, 'message' => 'Không tìm thấy bước'], 404);
        }
        $this->authorize('update', $step);

        // Verify organization ownership
        $orgHex = $this->getOrgHex();
        if ($orgHex) {
            $orgBin = IdFormatter::hexToBinary($orgHex);
            if ($orgBin && $step->phase->organization_id !== $orgBin) {
                return response()->json(['success' => false, 'message' => 'Không có quyền chỉnh sửa bước này'], 403);
            }
        }

        $data = $request->validated();

        $updateData = [
            'name' => $data['name'],
            'desc' => $data['desc'] ?? '',
            'note' => $data['note'] ?? '',
            'tip' => $data['tip'] ?? '',
        ];

        if (isset($data['templates'])) {
            $updateData['templates'] = array_map(fn($tpl) => [
                'tab_label' => $tpl['tab_label'] ?? '',
                'purpose' => $tpl['purpose'] ?? '',
                'content' => $tpl['content'] ?? '',
                'shortcut' => $tpl['shortcut'] ?? '',
            ], $data['templates']);
        }

        if (isset($data['checklist_items'])) {
            $updateData['checklist'] = array_map(fn($item) => $item['content'] ?? '', $data['checklist_items']);
        }

        $this->repository->updateStep($id, $updateData);

        return response()->json(['success' => true, 'message' => 'Cập nhật bước thành công']);
    }
}
