<?php
declare(strict_types=1);

namespace App\Modules\Forms\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Forms\Models\FormSchema;

class FormBuilderController extends Controller
{
    public function index(Request $request): Response
    {
        $schemas = FormSchema::allActive();
        return $this->view('Forms.Views.builder', ['schemas' => $schemas, 'schema' => null]);
    }

    public function edit(Request $request, string $id): Response
    {
        $schema = FormSchema::find((int) $id);
        if (!$schema) {
            return $this->redirect('/forms/builder')->withError('النموذج غير موجود');
        }
        $schemas = FormSchema::allActive();
        return $this->view('Forms.Views.builder', ['schemas' => $schemas, 'schema' => $schema]);
    }

    public function update(Request $request, string $id): Response
    {
        $schema = FormSchema::find((int) $id);
        if (!$schema) {
            return $this->redirect('/forms/builder')->withError('النموذج غير موجود');
        }

        $schemaJson = trim((string) $request->post('schema_json', ''));
        $decoded = json_decode($schemaJson, true);
        if ($decoded === null && $schemaJson !== 'null') {
            return $this->redirect("/forms/builder/{$id}")->withError('JSON غير صالح');
        }

        $newVersion = (int) $schema->version + 1;

        $schema->update([
            'schema_json' => $schemaJson,
            'name_ar'     => trim((string) $request->post('name_ar', $schema->name_ar)),
            'form_fee'    => $request->post('form_fee', $schema->form_fee),
            'version'     => $newVersion,
        ]);

        return $this->redirect('/forms/builder')->withSuccess('تم تحديث النموذج — الإصدار ' . $newVersion);
    }
}