<?php

namespace App\Http\Controllers\Admin;

/*
 * WebFormController — управление конструктором веб-форм в административной панели.
 * Маршруты: resource admin/forms (index, create, store, edit, update, destroy)
 * Поля формы хранятся в JSON-колонке fields модели WebForm.
 * Поле fields приходит в POST как JSON-строка из конструктора на JS.
 */

use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Models\WebForm;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class WebFormController extends Controller
{
    public function index(): View
    {
        $forms = WebForm::withCount('leads')->latest()->get();

        return view('admin.forms.index', compact('forms'));
    }

    public function create(): View
    {
        $form = new WebForm;
        $services = $this->servicesList();

        return view('admin.forms.edit', compact('form', 'services'));
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validated($request);
        WebForm::create($data);

        return redirect()->route('admin.forms.index')->with('success', 'Форма создана.');
    }

    public function edit(WebForm $form): View
    {
        $services = $this->servicesList();

        return view('admin.forms.edit', compact('form', 'services'));
    }

    public function update(Request $request, WebForm $form): RedirectResponse
    {
        $data = $this->validated($request, $form);
        $form->update($data);

        return redirect()->route('admin.forms.index')->with('success', 'Форма сохранена.');
    }

    public function destroy(WebForm $form): RedirectResponse
    {
        $form->delete();

        return redirect()->route('admin.forms.index')->with('success', 'Форма удалена.');
    }

    // Активные услуги в порядке sort_order для подстановки в select-поля форм
    private function servicesList(): array
    {
        return Service::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('title')
            ->pluck('title')
            ->toArray();
    }

    // Парсим и валидируем входящие данные формы
    private function validated(Request $request, ?WebForm $form = null): array
    {
        $slugRule = 'required|string|max:80|regex:/^[a-z0-9\-_]+$/|unique:web_forms,slug';
        if ($form && $form->exists) {
            $slugRule .= ','.$form->id;
        }

        $request->validate([
            'title' => 'required|string|max:150',
            'slug' => $slugRule,
            'notify_email' => 'nullable|email|max:150',
            'is_active' => 'nullable|boolean',
            'fields_json' => 'nullable|string',
        ]);

        // Декодируем поля из JSON-строки
        $fields = [];
        if ($request->filled('fields_json')) {
            $decoded = json_decode($request->input('fields_json'), true);
            if (is_array($decoded)) {
                $fields = $decoded;
            }
        }

        return [
            'title' => $request->input('title'),
            'slug' => $request->input('slug'),
            'notify_email' => $request->input('notify_email'),
            'is_active' => $request->boolean('is_active'),
            'fields' => $fields,
        ];
    }
}
