<?php

declare(strict_types=1);

namespace ROITheme\Admin\CustomCSSManager\Infrastructure\Bootstrap;

use ROITheme\Admin\CustomCSSManager\Infrastructure\Persistence\WordPressSnippetRepository;
use ROITheme\Admin\CustomCSSManager\Application\UseCases\SaveSnippetUseCase;
use ROITheme\Admin\CustomCSSManager\Application\UseCases\DeleteSnippetUseCase;
use ROITheme\Admin\CustomCSSManager\Application\DTOs\SaveSnippetRequest;
use ROITheme\Admin\CustomCSSManager\Domain\ValueObjects\SnippetId;
use ROITheme\Shared\Domain\Exceptions\ValidationException;

/**
 * Bootstrap para CustomCSSManager
 *
 * Registra el handler de formulario POST en admin_init
 * ANTES de que se envíen headers HTTP
 */
final class CustomCSSManagerBootstrap
{
    private const NONCE_ACTION = 'roi_custom_css_manager';

    public static function init(): void
    {
        add_action('admin_init', [self::class, 'handleFormSubmission']);
    }

    public static function handleFormSubmission(): void
    {
        if (!isset($_POST['roi_css_action'])) {
            return;
        }

        // Verificar que estamos en la página correcta
        $page = $_GET['page'] ?? '';
        $component = $_GET['component'] ?? '';
        if ($page !== 'roi-theme-admin' || $component !== 'custom-css-manager') {
            return;
        }

        // Verificar nonce
        if (!wp_verify_nonce($_POST['_wpnonce'] ?? '', self::NONCE_ACTION)) {
            wp_die('Nonce verification failed');
        }

        // Verificar permisos
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }

        global $wpdb;
        $repository = new WordPressSnippetRepository($wpdb);
        $saveUseCase = new SaveSnippetUseCase($repository);
        $deleteUseCase = new DeleteSnippetUseCase($repository);

        $action = sanitize_text_field($_POST['roi_css_action']);

        try {
            match ($action) {
                'save' => self::processSave($_POST, $saveUseCase),
                'delete' => self::processDelete($_POST, $deleteUseCase),
                default => null,
            };

            // Redirect con mensaje de éxito
            $redirect_url = admin_url('admin.php?page=roi-theme-admin&component=custom-css-manager&roi_message=success');
            wp_redirect($redirect_url);
            exit;

        } catch (ValidationException $e) {
            $redirect_url = admin_url('admin.php?page=roi-theme-admin&component=custom-css-manager&roi_message=error&roi_error=' . urlencode($e->getMessage()));
            wp_redirect($redirect_url);
            exit;
        }
    }

    private static function processSave(array $data, SaveSnippetUseCase $useCase): void
    {
        $id = sanitize_text_field($data['snippet_id'] ?? '');
        if (empty($id)) {
            $id = SnippetId::generate()->value();
        }

        $request = SaveSnippetRequest::fromArray([
            'id' => $id,
            'name' => sanitize_text_field($data['snippet_name'] ?? ''),
            'description' => sanitize_textarea_field($data['snippet_description'] ?? ''),
            'css' => wp_strip_all_tags($data['snippet_css'] ?? ''),
            'type' => sanitize_text_field($data['snippet_type'] ?? 'deferred'),
            'pages' => array_map('sanitize_text_field', $data['snippet_pages'] ?? ['all']),
            'enabled' => isset($data['snippet_enabled']),
            'order' => absint($data['snippet_order'] ?? 100),
        ]);

        $useCase->execute($request);
    }

    private static function processDelete(array $data, DeleteSnippetUseCase $useCase): void
    {
        $id = sanitize_text_field($data['snippet_id'] ?? '');
        if (empty($id)) {
            throw new ValidationException('ID de snippet requerido para eliminar');
        }
        $useCase->execute($id);
    }
}
