<?php

namespace App\Controllers;

use App\Models\DeliveryNoteTemplateModel;
use CodeIgniter\HTTP\RedirectResponse;

class DeliveryNoteTemplateController extends BaseController
{
    public function index(): string
    {
        $templates = (new DeliveryNoteTemplateModel())
            ->orderBy('code')
            ->findAll();

        return view('delivery_note_templates/index', [
            'title' => 'Plantillas de acta',
            'templates' => $templates,
        ]);
    }

    public function create(): string
    {
        return view('delivery_note_templates/form', [
            'title' => 'Nueva plantilla de acta',
            'template' => null,
            'fields' => [],
            'action' => site_url('delivery-note-templates'),
        ]);
    }

    public function store(): RedirectResponse
    {
        $model = new DeliveryNoteTemplateModel();
        $id = $model->insert($this->payload(), true);

        return redirect()
            ->to(site_url('delivery-note-templates/' . $id . '/edit'))
            ->with('success', 'Plantilla de acta creada.');
    }

    public function edit(int $id): string
    {
        $model = new DeliveryNoteTemplateModel();
        $template = $model->find($id);
        if ($template === null) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('delivery_note_templates/form', [
            'title' => 'Editar plantilla de acta',
            'template' => $template,
            'fields' => $model->fields($template),
            'action' => site_url('delivery-note-templates/' . $id . '/update'),
        ]);
    }

    public function update(int $id): RedirectResponse
    {
        $model = new DeliveryNoteTemplateModel();
        if ($model->find($id) === null) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $model->update($id, $this->payload());

        return redirect()
            ->to(site_url('delivery-note-templates/' . $id . '/edit'))
            ->with('success', 'Plantilla de acta actualizada.');
    }

    public function delete(int $id): RedirectResponse
    {
        (new DeliveryNoteTemplateModel())->update($id, ['is_active' => 0]);
        return redirect()->to(site_url('delivery-note-templates'))->with('success', 'Plantilla desactivada.');
    }

    private function payload(): array
    {
        $fields = $this->normalizeFields((string) $this->request->getPost('fields_json'));

        return [
            'code' => strtoupper(trim((string) $this->request->getPost('code'))),
            'name' => trim((string) $this->request->getPost('name')),
            'body_html' => $this->cleanBodyHtml((string) $this->request->getPost('body_html')),
            'fields_json' => json_encode($fields, JSON_UNESCAPED_UNICODE),
            'is_active' => $this->request->getPost('is_active') === '1' ? 1 : 0,
        ];
    }

    private function normalizeFields(string $json): array
    {
        $raw = json_decode($json, true);
        if (! is_array($raw)) {
            return [];
        }

        $validTypes = ['text', 'textarea', 'date', 'signature'];
        $fields = [];
        foreach ($raw as $field) {
            if (! is_array($field)) {
                continue;
            }
            $key = preg_replace('/[^a-z0-9_]/', '_', strtolower(trim((string) ($field['key'] ?? ''))));
            $label = trim((string) ($field['label'] ?? ''));
            $type = (string) ($field['type'] ?? 'text');
            if ($key === '' || $label === '' || ! in_array($type, $validTypes, true)) {
                continue;
            }
            $fields[] = [
                'key' => $key,
                'label' => $label,
                'type' => $type,
                'required' => ! empty($field['required']),
            ];
        }

        return $fields;
    }

    private function cleanBodyHtml(string $html): string
    {
        return trim(strip_tags($html, '<p><br><strong><em><b><i><u><ul><ol><li><h3><h4>'));
    }
}
