<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

use APD\Repositories\ProductConfigRepository;
use APD\Support\RequestData;

defined('ABSPATH') || exit;

class ConfigStructurePage
{
    private array $fields = [
        '_apd_mode' => ['label' => 'Mode', 'type' => 'select', 'options' => ['standalone', 'customer', 'admin']],
        '_apd_theme' => ['label' => 'Theme JSON', 'type' => 'json', 'rows' => 10],
        '_apd_layout' => ['label' => 'Layout JSON', 'type' => 'json', 'rows' => 10],
        '_apd_modules' => ['label' => 'Modules JSON', 'type' => 'json', 'rows' => 12],
        '_apd_permissions' => ['label' => 'Permissions JSON', 'type' => 'json', 'rows' => 10],
        '_apd_views' => ['label' => 'Views JSON', 'type' => 'json', 'rows' => 12],
        '_apd_drawing_zones' => ['label' => 'Drawing zones JSON', 'type' => 'json', 'rows' => 12],
        '_apd_fonts' => ['label' => 'Fonts JSON', 'type' => 'json', 'rows' => 8],
        '_apd_upload' => ['label' => 'Upload JSON', 'type' => 'json', 'rows' => 8],
        '_apd_colors' => ['label' => 'Colors JSON', 'type' => 'json', 'rows' => 8],
        '_apd_pricing_rules' => ['label' => 'Pricing rules JSON', 'type' => 'json', 'rows' => 10],
        '_apd_selection_menu' => ['label' => 'Selection menu JSON', 'type' => 'json', 'rows' => 8],
        '_apd_ui' => ['label' => 'UI JSON', 'type' => 'json', 'rows' => 8],
        '_apd_front_behavior' => ['label' => 'Front behavior JSON', 'type' => 'json', 'rows' => 8],
        '_apd_mobile_behavior' => ['label' => 'Mobile behavior JSON', 'type' => 'json', 'rows' => 8],
        '_apd_initial_document' => ['label' => 'Initial document JSON', 'type' => 'json', 'rows' => 16],
    ];

    public function render() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'asuka-product-designer'));
        }

        $query = RequestData::query();
        $configId = absint($query['config_id'] ?? 0);
        $repository = new ProductConfigRepository();
        $config = $repository->find($configId);
        if (! $configId || ! $config) {
            wp_die(esc_html__('The requested config could not be found.', 'asuka-product-designer'));
        }

        $editUrl = admin_url('post.php?post=' . $configId . '&action=edit');
        ?>
        <div class="wrap apd-admin-shell apd-structure-page">
            <div class="apd-page-heading apd-page-heading-tight">
                <div>
                    <h1><?php esc_html_e('Config structure', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('This standalone screen holds the structural and advanced JSON parts of the config. The main edit screen stays focused on the canvas builder.', 'asuka-product-designer'); ?></p>
                </div>
                <div class="apd-inline-actions apd-inline-actions-wrap">
                    <a class="button button-secondary" href="<?php echo esc_url($editUrl); ?>"><?php esc_html_e('Back to builder', 'asuka-product-designer'); ?></a>
                </div>
            </div>

            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-card apd-structure-card">
                <input type="hidden" name="action" value="apd_save_structure_config">
                <input type="hidden" name="config_id" value="<?php echo esc_attr((string) $configId); ?>">
                <?php wp_nonce_field('apd_save_structure_config_' . $configId, 'apd_structure_nonce'); ?>

                <div class="js-apd-tabs" data-default-tab="experience">
                    <div class="apd-tab-nav" role="tablist">
                        <button type="button" class="apd-tab-button is-active" data-tab="experience"><?php esc_html_e('Experience', 'asuka-product-designer'); ?></button>
                        <button type="button" class="apd-tab-button" data-tab="canvas"><?php esc_html_e('Canvas structure', 'asuka-product-designer'); ?></button>
                        <button type="button" class="apd-tab-button" data-tab="assets"><?php esc_html_e('Assets & pricing', 'asuka-product-designer'); ?></button>
                        <button type="button" class="apd-tab-button" data-tab="advanced"><?php esc_html_e('Advanced JSON', 'asuka-product-designer'); ?></button>
                    </div>
                    <section class="apd-tab-panel is-active" data-panel="experience">
                        <div class="apd-form-grid apd-form-grid-2">
                            <?php $this->renderField('_apd_mode', $config['_apd_mode'] ?? 'standalone'); ?>
                            <?php $this->renderField('_apd_theme', $config['_apd_theme'] ?? ''); ?>
                            <?php $this->renderField('_apd_layout', $config['_apd_layout'] ?? ''); ?>
                            <?php $this->renderField('_apd_modules', $config['_apd_modules'] ?? ''); ?>
                            <?php $this->renderField('_apd_permissions', $config['_apd_permissions'] ?? ''); ?>
                            <?php $this->renderField('_apd_selection_menu', $config['_apd_selection_menu'] ?? ''); ?>
                            <?php $this->renderField('_apd_ui', $config['_apd_ui'] ?? ''); ?>
                            <?php $this->renderField('_apd_front_behavior', $config['_apd_front_behavior'] ?? ''); ?>
                            <?php $this->renderField('_apd_mobile_behavior', $config['_apd_mobile_behavior'] ?? ''); ?>
                        </div>
                    </section>

                    <section class="apd-tab-panel" data-panel="canvas">
                        <div class="apd-form-grid">
                            <?php $this->renderField('_apd_views', $config['_apd_views'] ?? ''); ?>
                            <?php $this->renderField('_apd_drawing_zones', $config['_apd_drawing_zones'] ?? ''); ?>
                            <?php $this->renderField('_apd_initial_document', $config['_apd_initial_document'] ?? ''); ?>
                        </div>
                    </section>

                    <section class="apd-tab-panel" data-panel="assets">
                        <div class="apd-form-grid apd-form-grid-2">
                            <?php $this->renderField('_apd_fonts', $config['_apd_fonts'] ?? ''); ?>
                            <?php $this->renderField('_apd_upload', $config['_apd_upload'] ?? ''); ?>
                            <?php $this->renderField('_apd_colors', $config['_apd_colors'] ?? ''); ?>
                            <?php $this->renderField('_apd_pricing_rules', $config['_apd_pricing_rules'] ?? ''); ?>
                        </div>
                    </section>

                    <section class="apd-tab-panel" data-panel="advanced">
                        <div class="apd-callout">
                            <strong><?php esc_html_e('Advanced note', 'asuka-product-designer'); ?></strong>
                            <p><?php esc_html_e('Only use this page for structural or low-level changes. Day-to-day product building should happen on the main canvas screen.', 'asuka-product-designer'); ?></p>
                        </div>
                        <div class="apd-form-grid">
                            <?php foreach (array_keys($this->fields) as $key) : ?>
                                <?php $this->renderField($key, $config[$key] ?? ''); ?>
                            <?php endforeach; ?>
                        </div>
                    </section>
                </div>

                <div class="apd-inline-actions apd-structure-actions">
                    <button type="submit" class="button button-primary"><?php esc_html_e('Save structure', 'asuka-product-designer'); ?></button>
                    <a class="button button-secondary" href="<?php echo esc_url($editUrl); ?>"><?php esc_html_e('Return to builder', 'asuka-product-designer'); ?></a>
                </div>
            </form>
        </div>
        <?php
    }

    public function save() : void
    {
        $post = RequestData::post();
        $configId = absint($post['config_id'] ?? 0);
        if (! $configId || ! current_user_can('edit_post', $configId)) {
            wp_die(esc_html__('You do not have permission to update this config.', 'asuka-product-designer'));
        }

        if (! isset($post['apd_structure_nonce']) || ! wp_verify_nonce(sanitize_text_field((string) $post['apd_structure_nonce']), 'apd_save_structure_config_' . $configId)) {
            wp_die(esc_html__('Security check failed.', 'asuka-product-designer'));
        }

        foreach ($this->fields as $key => $field) {
            $raw = $post[$key] ?? null;
            if ($raw === null) {
                continue;
            }
            $value = is_string($raw) ? $raw : '';
            if ($field['type'] === 'json') {
                $value = $this->sanitizeJson($value);
                update_post_meta($configId, $key, wp_slash($value));
                continue;
            }

            $value = sanitize_text_field($value);
            update_post_meta($configId, $key, $value);
        }

        wp_safe_redirect(admin_url('admin.php?page=apd-config-structure&config_id=' . $configId . '&updated=1'));
        exit;
    }

    private function renderField(string $key, string $value) : void
    {
        $field = $this->fields[$key];
        echo '<label class="apd-field apd-field-stacked">';
        echo '<span>' . esc_html($this->translateFieldLabel((string) $field['label'])) . '</span>';
        if ($field['type'] === 'select') {
            echo '<select name="' . esc_attr($key) . '">';
            foreach ($field['options'] as $option) {
                echo '<option value="' . esc_attr($option) . '" ' . selected($value ?: 'standalone', $option, false) . '>' . esc_html($this->translateModeOption((string) $option)) . '</option>';
            }
            echo '</select>';
        } else {
            echo '<textarea class="apd-codearea" name="' . esc_attr($key) . '" rows="' . esc_attr((string) ($field['rows'] ?? 8)) . '">' . esc_textarea($value) . '</textarea>';
        }
        echo '</label>';
    }



    private function translateFieldLabel(string $label) : string
    {
        return match ($label) {
            'Mode' => __('Mode', 'asuka-product-designer'),
            'Theme JSON' => __('Theme JSON', 'asuka-product-designer'),
            'Layout JSON' => __('Layout JSON', 'asuka-product-designer'),
            'Modules JSON' => __('Modules JSON', 'asuka-product-designer'),
            'Permissions JSON' => __('Permissions JSON', 'asuka-product-designer'),
            'Views JSON' => __('Views JSON', 'asuka-product-designer'),
            'Drawing zones JSON' => __('Drawing zones JSON', 'asuka-product-designer'),
            'Fonts JSON' => __('Fonts JSON', 'asuka-product-designer'),
            'Upload JSON' => __('Upload JSON', 'asuka-product-designer'),
            'Colors JSON' => __('Colors JSON', 'asuka-product-designer'),
            'Pricing rules JSON' => __('Pricing rules JSON', 'asuka-product-designer'),
            'Selection menu JSON' => __('Selection menu JSON', 'asuka-product-designer'),
            'Front behavior JSON' => __('Front behavior JSON', 'asuka-product-designer'),
            'Mobile behavior JSON' => __('Mobile behavior JSON', 'asuka-product-designer'),
            'Initial document JSON' => __('Initial document JSON', 'asuka-product-designer'),
            default => $label,
        };
    }

    private function translateModeOption(string $mode) : string
    {
        return match ($mode) {
            'standalone' => __('Standalone', 'asuka-product-designer'),
            'customer' => __('Customer', 'asuka-product-designer'),
            'admin' => __('Admin', 'asuka-product-designer'),
            default => $mode,
        };
    }
    private function sanitizeJson(string $value) : string
    {
        $trimmed = trim($value);
        if ($trimmed === '') {
            return '';
        }

        $decoded = json_decode($trimmed, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return $value;
        }

        return (string) wp_json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
}
