<?php

namespace Formatrica\Admin\Pages;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Formatrica\Capability\Feature_Gate;
use Formatrica\Capability\Free_Capability_Provider;
use Formatrica\Forms\Form_Repository;
use Formatrica\Forms\Form_Sanitizer;
use Formatrica\Integrations\Integration_Manager;
use Formatrica\License\Null_License_Manager;

final class Form_Builder_Page
{
    private ?Feature_Gate $gate;

    public function __construct(?Feature_Gate $gate = null)
    {
        // Hook registration moved to boot() to avoid early loading issues
        $this->gate = $gate;
    }

    public function boot(): void
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    public function enqueue_assets(): void
    {
		//Bail out if not on the builder page
		if (!$this->is_builder_screen()) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        wp_enqueue_script('formatrica-admin');
        wp_set_script_translations('formatrica-admin', 'formatrica', FORMATRICA_PATH . 'languages');

        if (wp_style_is('formatrica-admin-style', 'registered')) {
            wp_enqueue_style('formatrica-admin-style');
        }

        $form_id = $this->get_form_id();

        $form_meta = [
            'captchaSecretSet' => false,
        ];

        if ($form_id > 0) {
            $repository = new Form_Repository();
            $raw_config = $repository->raw_config($form_id);
            if (!empty($raw_config['options']['captcha']['secret_key'] ?? '')) {
                $form_meta['captchaSecretSet'] = true;
            }
        }

        $gate = $this->gate ?? self::fallback_gate();

        wp_localize_script(
            'formatrica-admin',
            'formatrica',
            [
                'builder' => [
                    'restUrl' => esc_url_raw(rest_url('formatrica/v1')),
                    'nonce' => wp_create_nonce('wp_rest'),
                    'formId' => $form_id,
                    'builderUrl' => esc_url_raw(admin_url('admin.php?page=formatrica-builder')),
                    // Site root for resolving relative asset paths (e.g. the
                    // static image field's src) inside admin previews.
                    'homeUrl' => esc_url_raw(home_url('/')),
                    'defaults' => Form_Sanitizer::default_config(),
                    'integrationsMeta' => Integration_Manager::get_integrations(),
                    'meta' => $form_meta,
                    'capabilities' => $gate->all(),
                    'license' => $gate->license_summary(),
                    'wpData' => [
                        'postTypes' => $this->get_post_types_payload(),
                        'postStatuses' => $this->get_post_statuses_payload(),
                        'taxonomies' => $this->get_taxonomies_payload(),
                    ],
                    'dataSources' => class_exists(\Formatrica\Pro\Fields\Data_Source_Registry::class) ? \Formatrica\Pro\Fields\Data_Source_Registry::metadata() : [],
                    // Quick-action deep-links (Pro forms.quick_actions).
                    'quickActions' => [
                        'newPageUrl' => esc_url_raw(admin_url('post-new.php?post_type=page')),
                        'newPostUrl' => esc_url_raw(admin_url('post-new.php')),
                    ],
                    'woo' => $this->get_woocommerce_payload(),
                    // AI assistant runtime state (Pro ai.assistant): the toolbar
                    // button shows only when the admin has enabled it in settings.
                    'ai' => $this->get_ai_state(),
                    'i18n' => [
                        'formSaved' => __('Form saved.', 'formatrica'),
                        'formCreated' => __('Form created.', 'formatrica'),
                        'saving' => __('Saving…', 'formatrica'),
                        'defaultTitle' => __('Untitled form', 'formatrica'),
                    ],
                ],
            ]
        );
    }

    /**
     * @return array{enabled:bool, keySet:bool}
     */
    private function get_ai_state(): array
    {
        // app/Ai is stripped from the wporg package — report disabled there.
        if (!class_exists(\Formatrica\Ai\Ai_Settings::class)) {
            return ['enabled' => false, 'keySet' => false];
        }

        $s = \Formatrica\Ai\Ai_Settings::load();

        return [
            'enabled' => (bool) ($s['enabled'] ?? false),
            'keySet'  => (bool) ($s['api_key_set'] ?? false),
        ];
    }

	//Render some heade HTML
    public function render(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'formatrica'));
        }

        echo '<div class="wrap">';

        if (!wp_script_is('formatrica-admin', 'enqueued')) {
            echo '<div class="notice notice-warning"><p>' . esc_html__('Form builder assets are not loaded. Run the asset build (`npm install && npm run build`) so the interface can render.', 'formatrica') . '</p></div>';
        }

        $icon_url = FORMATRICA_URL . 'assets/formatrica.svg';

        echo '<div class="formatrica-builder__heading" style="display:flex;align-items:center;gap:8px;margin-bottom:16px;">';
        echo '<img src="' . esc_url($icon_url) . '" alt="' . esc_attr__('Formatrica', 'formatrica') . '" style="width:32px;height:32px;" />';
        echo '<h1 class="wp-heading-inline" style="margin:0;">' . esc_html__('Form Builder', 'formatrica') . '</h1>';
        echo '</div>';

        echo '<div id="formatrica-builder" class="formatrica-builder"></div>';
        echo '</div>';
    }

    /**
     * Defensive fallback so the builder payload always carries the full
     * capability map (all false) even if the gate was not injected.
     */
    private static function fallback_gate(): Feature_Gate
    {
        $gate = new Feature_Gate(new Null_License_Manager());
        $gate->add_provider(new Free_Capability_Provider());

        return $gate;
    }

	//Gets the form ID from the URL
    private function get_form_id(): int
    {
        return isset($_GET['form_id']) ? (int) $_GET['form_id'] : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    }

    private function is_builder_screen(): bool
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin screen check, no data modification
        return isset($_GET['page']) && $_GET['page'] === 'formatrica-builder';
    }

    /**
     * We need the post types and taxonomies to populate the dropdowns in the builder.
     *
     * @return array<int, array<string,string>>
     */
    private function get_post_types_payload(): array
    {
        $post_types = get_post_types(
            [
                'show_ui' => true,
                'show_in_nav_menus' => true,
            ],
            'objects'
        );

        $payload = [];

        foreach ($post_types as $name => $object) {
            $payload[] = [
                'name' => $name,
                'label' => (string) ($object->labels->singular_name ?? $object->label ?? $name),
            ];
        }

        return $payload;
    }

    /**
     * We also need the post statuses to populate the dropdowns in the builder.
     *
     * @return array<int, array<string,string>>
     */
    private function get_post_statuses_payload(): array
    {
        $statuses = get_post_statuses();
        $payload = [];

        foreach ($statuses as $name => $label) {
            $payload[] = [
                'name' => $name,
                'label' => (string) $label,
            ];
        }

        return $payload;
    }

    /**
     * We also need the taxonomies
     *
     * @return array<int, array<string,mixed>>
     */
    private function get_taxonomies_payload(): array
    {
        $taxonomies = get_taxonomies(
            [
                'show_ui' => true,
            ],
            'objects'
        );

        $payload = [];

        foreach ($taxonomies as $name => $object) {
            $payload[] = [
                'name' => $name,
                'label' => (string) ($object->labels->singular_name ?? $object->label ?? $name),
                'object_types' => array_values(array_map('strval', (array) $object->object_type)),
            ];
        }

        return $payload;
    }

    /**
     * Now, get the WooCommerce data.
     *
     * @return array<string,mixed>
     */
    private function get_woocommerce_payload(): array
    {
        if (!class_exists('\WooCommerce')) {
            return [
                'active' => false,
            ];
        }

        $currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '';
        $order_statuses = [];
        if (function_exists('wc_get_order_statuses')) {
            foreach (wc_get_order_statuses() as $status_key => $status_label) {
                $order_statuses[] = [
                    'name' => $status_key,
                    'label' => (string) $status_label,
                ];
            }
        }

        return [
            'active' => true,
            'currency' => $currency,
            'orderStatuses' => $order_statuses,
        ];
    }
}
