<?php

declare(strict_types=1);

namespace App\Modules\Administration\Controllers;

use App\Controllers\Controller;
use App\Modules\Administration\Services\AuthenticationService;
use App\Modules\Administration\Services\AuthorizationService;
use App\Modules\Administration\Services\DynamicFormService;
use App\Modules\Administration\Services\DynamicFormSectionService;
use System\Http\Request;
use System\View\View;
use App\Modules\Administration\Services\DynamicFormFieldService;
use App\Modules\Administration\Services\DynamicFormSubmissionService;

final class DynamicFormController extends Controller
{
public function __construct(
    private AuthenticationService $authentication,
    private AuthorizationService $authorization,
    private DynamicFormService $formService,
    private DynamicFormSectionService $sectionService,
    private DynamicFormFieldService $fieldService,
    private Request $request,
    private DynamicFormSubmissionService $submissionService,
    
    View $view
) {
    parent::__construct($view);
}

    private function protect(): void
    {
        if (!$this->authentication->check()) {
            header(
                'Location: /public/login'
            );

            exit;
        }
    }

    private function requireAdministrator(): void
    {
        if (
            !$this->authorization
                ->isAdministrator()
        ) {
            header(
                'Location: /public/403'
            );

            exit;
        }
    }

    public function index(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $this->render(
            'dynamic-forms/index',
            [
                'title' =>
                    'Dynamic Form Management',

                'forms' =>
                    $this->formService->all(),

                'created' =>
                    $this->request->input(
                        'created'
                    ),

                'updated' =>
                    $this->request->input(
                        'updated'
                    ),

                'statusUpdated' =>
                    $this->request->input(
                        'status_updated'
                    ),
                'deleted' =>
                    $this->request->input(
                        'deleted'
                    ),
                'error' =>
                    $this->request->input(
                        'error'
                    )

            ]
        );
    }

    public function store(): void
    {
        $this->protect();
        $this->requireAdministrator();

        try {
            $this->formService->create(
                $this->request->all(),
                null
            );

            header(
                'Location: /public/dynamic-forms?created=1'
            );

            exit;

        } catch (\Throwable $exception) {

            header(
                'Location: /public/dynamic-forms?error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }

    public function update(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $id = (int) $this->request->input(
            'id',
            0
        );

        try {
            $this->formService->update(
                $id,
                $this->request->all()
            );

            header(
                'Location: /public/dynamic-forms?updated=1'
            );

            exit;

        } catch (\Throwable $exception) {

            header(
                'Location: /public/dynamic-forms?error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }

    public function publish(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $id = (int) $this->request->input(
            'id',
            0
        );

        try {
            $this->formService->publish($id);

            header(
                'Location: /public/dynamic-forms?status_updated=1'
            );

            exit;

        } catch (\Throwable $exception) {

            header(
                'Location: /public/dynamic-forms?error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }

    public function archive(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $id = (int) $this->request->input(
            'id',
            0
        );

        try {
            $this->formService->archive($id);

            header(
                'Location: /public/dynamic-forms?status_updated=1'
            );

            exit;

        } catch (\Throwable $exception) {

            header(
                'Location: /public/dynamic-forms?error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }

public function designer(): void
{
    $this->protect();
    $this->requireAdministrator();

    $id = (int) $this->request->input(
        'id',
        0
    );

    $form = $this->formService->find($id);

    if ($form === null) {
        http_response_code(404);

        exit(
            'Dynamic form not found.'
        );
    }

    $sections = $this->sectionService
        ->byForm($id);

    $fields = $this->fieldService
        ->byForm($id);
$fieldOptions = [];

foreach ($fields as $field) {
    $fieldId = (int) (
        $field['id']
        ?? 0
    );

    if ($fieldId <= 0) {
        continue;
    }

    $fieldOptions[$fieldId] =
        $this->fieldService
            ->optionsByField(
                $fieldId
            );
}
    $this->render(
        'dynamic-forms/designer',
        [
            'title' =>
                'Form Designer',

            'form' =>
                $form,

            'sections' =>
                $sections,

            'fields' =>
                $fields,
                
            'fieldOptions' =>
                $fieldOptions,
            'sectionCreated' =>
                $this->request->input(
                    'section_created'
                ),

            'sectionUpdated' =>
                $this->request->input(
                    'section_updated'
                ),

            'fieldCreated' =>
                $this->request->input(
                    'field_created'
                ),

            'fieldUpdated' =>
                $this->request->input(
                    'field_updated'
                ),

            'error' =>
                $this->request->input(
                    'error'
                )
        ]
    );
}

    public function storeSection(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $formId = (int) $this->request->input(
            'form_id',
            0
        );

        try {
            $this->sectionService->create(
                $formId,
                $this->request->all()
            );

            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&section_created=1'
            );

            exit;

        } catch (\Throwable $exception) {

            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }

    public function updateSection(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $id = (int) $this->request->input(
            'id',
            0
        );

        $formId = (int) $this->request->input(
            'form_id',
            0
        );

        try {
            $this->sectionService->update(
                $id,
                $this->request->all()
            );

            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&section_updated=1'
            );

            exit;

        } catch (\Throwable $exception) {

            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }
        public function storeField(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $formId = (int) $this->request->input(
            'form_id',
            0
        );

        try {
            $this->fieldService->create(
                $formId,
                $this->request->all()
            );

            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&field_created=1'
            );

            exit;
        } catch (\Throwable $exception) {
            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }


    public function updateField(): void
    {
        $this->protect();
        $this->requireAdministrator();

        $id = (int) $this->request->input(
            'id',
            0
        );

        $formId = (int) $this->request->input(
            'form_id',
            0
        );

        try {
            $this->fieldService->update(
                $id,
                $this->request->all()
            );

            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&field_updated=1'
            );

            exit;
        } catch (\Throwable $exception) {
            header(
                'Location: /public/dynamic-forms/designer?id='
                . $formId
                . '&error='
                . urlencode(
                    $exception->getMessage()
                )
            );

            exit;
        }
    }
public function preview(): void
{
    $this->protect();
    $this->requireAdministrator();

    $id = (int) $this->request->input(
        'id',
        0
    );

    if ($id <= 0) {
        http_response_code(400);

        exit('Invalid dynamic form ID.');
    }

    $form = $this->formService->find($id);

    if ($form === null) {
        http_response_code(404);

        exit('Dynamic form not found.');
    }

    $sections = $this->sectionService
        ->byForm($id);

    $fields = $this->fieldService
        ->byForm($id);

    $fieldOptions = [];

    foreach ($fields as $field) {
        $fieldId = (int) (
            $field['id']
            ?? 0
        );

        if ($fieldId <= 0) {
            continue;
        }

        $fieldOptions[$fieldId] =
            $this->fieldService
                ->optionsByField(
                    $fieldId
                );
    }

    $this->render(
        'dynamic-forms/preview',
        [
            'title' =>
                'Form Preview',

            'form' =>
                $form,

            'sections' =>
                $sections,

            'fields' =>
                $fields,

            'fieldOptions' =>
                $fieldOptions
        ]
    );
}
public function submit(): void
{
    $this->protect();
    $this->requireAdministrator();

    $formId = (int) $this->request->input(
        'form_id',
        0
    );

    if ($formId <= 0) {
        header(
            'Location: /public/dynamic-forms?error='
            . urlencode(
                'Invalid dynamic form ID.'
            )
        );

        exit;
    }

    try {
        $submissionId =
            $this->submissionService->submit(
                $formId,
                $this->request->all(),
                null,
                null
            );

        header(
            'Location: /public/dynamic-forms/preview?id='
            . $formId
            . '&submitted=1'
            . '&submission_id='
            . $submissionId
        );

        exit;

    } catch (\Throwable $exception) {

        header(
            'Location: /public/dynamic-forms/preview?id='
            . $formId
            . '&error='
            . urlencode(
                $exception->getMessage()
            )
        );

        exit;
    }
}
public function delete(): void
{
    $this->protect();
    $this->requireAdministrator();

    $id = (int) $this->request->input(
        'id',
        0
    );

    try {

        $this->formService
            ->delete($id);

        header(
            'Location: /public/dynamic-forms?deleted=1'
        );

        exit;

    } catch (\Throwable $exception) {

        header(
            'Location: /public/dynamic-forms?error='
            . urlencode(
                $exception->getMessage()
            )
        );

        exit;
    }
}
public function deactivateField(): void
{
    $this->protect();
    $this->requireAdministrator();

    $id = (int) $this->request->input(
        'id',
        0
    );

    $formId = (int) $this->request->input(
        'form_id',
        0
    );

    try {
        $this->fieldService
            ->deactivate($id);

        header(
            'Location: /public/dynamic-forms/designer?id='
            . $formId
            . '&field_removed=1'
        );

        exit;

    } catch (\Throwable $exception) {

        header(
            'Location: /public/dynamic-forms/designer?id='
            . $formId
            . '&error='
            . urlencode(
                $exception->getMessage()
            )
        );

        exit;
    }
}
public function deactivateSection(): void
{
    $this->protect();
    $this->requireAdministrator();

    $id = (int) $this->request->input('id', 0);
    $formId = (int) $this->request->input('form_id', 0);

    try {

        $this->sectionService->deactivate($id);

        header(
            'Location: /public/dynamic-forms/designer?id='
            . $formId
            . '&section_removed=1'
        );

        exit;

    } catch (\Throwable $exception) {

        header(
            'Location: /public/dynamic-forms/designer?id='
            . $formId
            . '&error='
            . urlencode($exception->getMessage())
        );

        exit;
    }
}
public function reorderFields(): void
{

    
    $fieldIds = $_POST['field_id'] ?? [];
    $sectionIds = $_POST['section_id'] ?? [];
    $sortOrders = $_POST['sort_order'] ?? [];

    $this->fieldService->reorder(
        $fieldIds,
        $sectionIds,
        $sortOrders
    );

    header('Content-Type: application/json');

    echo json_encode([
        'success' => true
    ]);

    exit;
}
/* public function deactivateSection(): void 
{
    $this->protect();
    $this->requireAdministrator();

    $id = (int) $this->request->input(
        'id',
        0
    );

    $formId = (int) $this->request->input(
        'form_id',
        0
    );

    try {
        $this->sectionService
            ->deactivate($id);

        header(
            'Location: /public/dynamic-forms/designer?id='
            . $formId
            . '&section_removed=1'
        );

        exit;

    } catch (\Throwable $exception) {
        header(
            'Location: /public/dynamic-forms/designer?id='
            . $formId
            . '&error='
            . urlencode(
                $exception->getMessage()
            )
        );

        exit;
    }
} **/

} // final class closing brace
