<?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\Mail\DevelopmentMailpitTransport;
use APD\Support\CommercialRuntimeConfig;
use APD\Support\DesignerAssets;
use APD\PostTypes\TemplatePostType;
use APD\PostTypes\ThemePostType;
use APD\Repositories\TemplateRepository;
use APD\Support\RequestData;
use APD\Theme\DesignerTheme;

defined('ABSPATH') || exit;

class SettingsPage
{
    public function render() : void
    {
        $settings = (new AdminSettings())->all();
        $themeService = new DesignerTheme();
        $themeChoices = $themeService->choices();
        $templateRepository = new TemplateRepository();
        $templateChoices = $templateRepository->allForSelect();
        $adminTemplateId = (string) ($settings['admin_designer_template_id'] ?? '0');
        if ($adminTemplateId !== '0' && $templateRepository->getMetaPayload((int) $adminTemplateId) === []) {
            $adminTemplateId = '0';
        }
        $adminDesignerThemeId = $themeService->hasTheme((string) ($settings['admin_designer_theme_id'] ?? ''))
            ? (string) $settings['admin_designer_theme_id']
            : $themeService->defaultThemeId();
        $defaultThemeId = $themeService->hasTheme((string) ($settings['default_designer_theme_id'] ?? ''))
            ? (string) $settings['default_designer_theme_id']
            : $themeService->defaultThemeId();
        $defaultTheme = $themeService->published($defaultThemeId);
        $commercialService = new CommercialRuntimeConfig();
        $commercialRuntime = $commercialService->build($settings);
        $licenseRuntime = is_array($commercialRuntime['license'] ?? null) ? $commercialRuntime['license'] : [];
        $entitlements = $commercialService->entitlementsFromLicense($licenseRuntime);
        $licensedAddons = DesignerAssets::addons((array) ($entitlements['features'] ?? []));
        $licenseConfigured = trim((string) ($settings['license_key'] ?? '')) !== '';
        $licenseConnected = ! empty($licenseRuntime['token']);
        $licenseEnabled = (string) ($settings['license_enabled'] ?? '1') === '1';
        $apiUrl = $commercialService->apiBaseUrl();
        $mailpitStatus = ['supported' => false];
        if (class_exists(DevelopmentMailpitTransport::class)) {
            $mailpitStatus = (new DevelopmentMailpitTransport())->status();
        }
        $licenseStatus = ! $licenseEnabled
            ? __('Disabled', 'asuka-product-designer')
            : (! $licenseConfigured
                ? __('License key required', 'asuka-product-designer')
                : ($licenseConnected
                    ? __('Connected', 'asuka-product-designer')
                    : __('API unavailable or license rejected', 'asuka-product-designer')));
        ?>
        <div class="wrap apd-admin-shell apd-admin-theme-<?php echo esc_attr($settings['admin_theme']); ?> apd-settings-page">
            <div class="apd-page-heading">
                <div>
                    <span class="apd-badge"><?php esc_html_e('Global settings', 'asuka-product-designer'); ?></span>
                    <h1><?php esc_html_e('Settings', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('Tune runtime defaults, external provider credentials, and plugin-wide behavior.', 'asuka-product-designer'); ?></p>
                </div>
            </div>

            <?php if (! empty($mailpitStatus['supported'])) $this->renderMailpitNotice(); ?>

            <form method="post" action="options.php" class="apd-settings-grid">
                <?php settings_fields('apd_settings_group'); ?>
                <section class="apd-card apd-settings-card apd-settings-card--half">
                    <h2><?php esc_html_e('Runtime defaults', 'asuka-product-designer'); ?></h2>
                    <div class="apd-form-grid">
                        <label class="apd-field">
                            <span><?php esc_html_e('Default designer height', 'asuka-product-designer'); ?></span>
                            <input type="text" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[default_height]" value="<?php echo esc_attr($settings['default_height']); ?>" placeholder="720px">
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Default mode', 'asuka-product-designer'); ?></span>
                            <select name="<?php echo esc_attr(AdminSettings::OPTION); ?>[default_mode]">
                                <option value="standalone" <?php selected($settings['default_mode'], 'standalone'); ?>><?php esc_html_e('Standalone', 'asuka-product-designer'); ?></option>
                                <option value="customer" <?php selected($settings['default_mode'], 'customer'); ?>><?php esc_html_e('Customer', 'asuka-product-designer'); ?></option>
                                <option value="admin" <?php selected($settings['default_mode'], 'admin'); ?>><?php esc_html_e('Admin', 'asuka-product-designer'); ?></option>
                            </select>
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Maximum upload size (MB)', 'asuka-product-designer'); ?></span>
                            <input type="number" step="1" min="1" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[upload_max_size_mb]" value="<?php echo esc_attr($settings['upload_max_size_mb']); ?>">
                        </label>
                    </div>
                </section>

                <section class="apd-card apd-settings-card apd-settings-card--half">
                    <h2><?php esc_html_e('Experience and feature flags', 'asuka-product-designer'); ?></h2>
                    <div class="apd-form-grid">
                        <label class="apd-field">
                            <span><?php esc_html_e('Admin theme', 'asuka-product-designer'); ?></span>
                            <select name="<?php echo esc_attr(AdminSettings::OPTION); ?>[admin_theme]">
                                <option value="midnight" <?php selected($settings['admin_theme'], 'midnight'); ?>><?php esc_html_e('Midnight', 'asuka-product-designer'); ?></option>
                                <option value="light" <?php selected($settings['admin_theme'], 'light'); ?>><?php esc_html_e('Light', 'asuka-product-designer'); ?></option>
                                <option value="violet" <?php selected($settings['admin_theme'], 'violet'); ?>><?php esc_html_e('Violet', 'asuka-product-designer'); ?></option>
                            </select>
                        </label>
                        <label class="apd-toggle">
                            <input type="checkbox" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[enable_gutenberg]" value="1" <?php checked($settings['enable_gutenberg'], '1'); ?>>
                            <span><?php esc_html_e('Enable Gutenberg integration', 'asuka-product-designer'); ?></span>
                        </label>
                        <label class="apd-toggle">
                            <input type="checkbox" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[enable_woocommerce_binding]" value="1" <?php checked($settings['enable_woocommerce_binding'], '1'); ?>>
                            <span><?php esc_html_e('Enable WooCommerce product bindings', 'asuka-product-designer'); ?></span>
                        </label>
                    </div>
                </section>

                <section class="apd-card apd-settings-card apd-settings-card--theme" id="apd-admin-designer-presentation">
                    <div class="apd-card-head">
                        <div>
                            <span class="apd-badge"><?php esc_html_e('Administration workspace', 'asuka-product-designer'); ?></span>
                            <h2><?php esc_html_e('Administration designer', 'asuka-product-designer'); ?></h2>
                            <p><?php esc_html_e('Choose the template and theme used while building products in WordPress. Customer-facing product assignments remain unchanged.', 'asuka-product-designer'); ?></p>
                        </div>
                        <div class="apd-inline-actions-wrap">
                            <a class="button button-secondary" href="<?php echo esc_url(admin_url('edit.php?post_type=' . TemplatePostType::TYPE)); ?>"><?php esc_html_e('Manage templates', 'asuka-product-designer'); ?></a>
                            <a class="button button-secondary" href="<?php echo esc_url(admin_url('edit.php?post_type=' . ThemePostType::TYPE)); ?>"><?php esc_html_e('Manage themes', 'asuka-product-designer'); ?></a>
                        </div>
                    </div>
                    <div class="apd-form-grid apd-form-grid-2">
                        <label class="apd-field">
                            <span><?php esc_html_e('Administration template', 'asuka-product-designer'); ?></span>
                            <select name="<?php echo esc_attr(AdminSettings::OPTION); ?>[admin_designer_template_id]">
                                <option value="0" <?php selected($adminTemplateId, '0'); ?>><?php esc_html_e('Built-in administration workspace', 'asuka-product-designer'); ?></option>
                                <?php foreach ($templateChoices as $choice) : ?>
                                    <option value="<?php echo esc_attr((string) $choice['id']); ?>" <?php selected($adminTemplateId, (string) $choice['id']); ?>><?php echo esc_html((string) $choice['title']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small><?php esc_html_e('The selected reusable template controls module placement inside product editors.', 'asuka-product-designer'); ?></small>
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Administration designer theme', 'asuka-product-designer'); ?></span>
                            <select name="<?php echo esc_attr(AdminSettings::OPTION); ?>[admin_designer_theme_id]">
                                <?php foreach ($themeChoices as $choice) : ?>
                                    <option value="<?php echo esc_attr((string) $choice['id']); ?>" <?php selected($adminDesignerThemeId, (string) $choice['id']); ?>><?php echo esc_html((string) $choice['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small><?php esc_html_e('This visual theme applies only to the designer embedded in WordPress administration.', 'asuka-product-designer'); ?></small>
                        </label>
                    </div>
                </section>

                <section class="apd-card apd-settings-card apd-settings-card--theme" id="apd-default-designer-theme" data-apd-default-theme-picker>
                    <div class="apd-card-head">
                        <div>
                            <span class="apd-badge"><?php esc_html_e('Customer experience', 'asuka-product-designer'); ?></span>
                            <h2><?php esc_html_e('Default designer theme', 'asuka-product-designer'); ?></h2>
                            <p><?php esc_html_e('Products set to inherit automatically follow this theme. Explicit product assignments remain unchanged.', 'asuka-product-designer'); ?></p>
                        </div>
                        <a class="button button-secondary" href="<?php echo esc_url(admin_url('edit.php?post_type=' . ThemePostType::TYPE)); ?>"><?php esc_html_e('Manage themes', 'asuka-product-designer'); ?></a>
                    </div>
                    <script type="application/json" data-apd-default-theme-options><?php echo wp_json_encode($themeChoices, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES); ?></script>
                    <div class="apd-settings-theme-picker">
                        <label class="apd-field">
                            <span><?php esc_html_e('Theme used by default', 'asuka-product-designer'); ?></span>
                            <select name="<?php echo esc_attr(AdminSettings::OPTION); ?>[default_designer_theme_id]" data-apd-default-theme-select>
                                <?php foreach ($themeChoices as $choice) : ?>
                                    <option value="<?php echo esc_attr((string) $choice['id']); ?>" <?php selected($defaultThemeId, (string) $choice['id']); ?>><?php echo esc_html((string) $choice['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small><?php esc_html_e('Changing this setting does not duplicate theme data and takes effect for new designer sessions.', 'asuka-product-designer'); ?></small>
                        </label>
                        <div class="apd-settings-theme-preview" data-apd-default-theme-preview style="--theme-bg: <?php echo esc_attr((string) ($defaultTheme['colors']['layout.appBg'] ?? '#f5f7fb')); ?>; --theme-panel: <?php echo esc_attr((string) ($defaultTheme['colors']['layout.panelBg'] ?? '#ffffff')); ?>; --theme-text: <?php echo esc_attr((string) ($defaultTheme['colors']['text.primary'] ?? '#0f172a')); ?>; --theme-accent: <?php echo esc_attr((string) ($defaultTheme['colors']['accent.primary'] ?? '#2563eb')); ?>;">
                            <span class="apd-settings-theme-preview__canvas"><i></i><i></i><i></i><b></b></span>
                            <span><strong data-apd-default-theme-name><?php echo esc_html((string) $defaultTheme['name']); ?></strong><small><?php esc_html_e('Published version', 'asuka-product-designer'); ?></small></span>
                        </div>
                    </div>
                </section>

                <section class="apd-card apd-settings-card apd-settings-card--license">
                    <h2><?php esc_html_e('Licensing and Asuka API', 'asuka-product-designer'); ?></h2>
                    <p><?php esc_html_e('Connect the plugin to AsukaDesigner commercial services. The license key remains on WordPress and the browser receives only a signed runtime token.', 'asuka-product-designer'); ?></p>
                    <div class="apd-stat-grid">
                        <div class="apd-mini-stat">
                            <strong><?php echo esc_html($licenseStatus); ?></strong>
                            <span><?php esc_html_e('License status', 'asuka-product-designer'); ?></span>
                        </div>
                        <div class="apd-mini-stat">
                            <strong><?php echo esc_html((string) ($entitlements['plan'] ?? 'free')); ?></strong>
                            <span><?php esc_html_e('Resolved plan', 'asuka-product-designer'); ?></span>
                        </div>
                        <div class="apd-mini-stat">
                            <strong><?php echo esc_html(DesignerAssets::designerVersion()); ?></strong>
                            <span><?php esc_html_e('Bundled AsukaDesigner', 'asuka-product-designer'); ?></span>
                        </div>
                        <div class="apd-mini-stat">
                            <strong><?php echo esc_html((string) count($licensedAddons)); ?></strong>
                            <span><?php esc_html_e('Licensed add-on chunks', 'asuka-product-designer'); ?></span>
                        </div>
                    </div>
                    <?php if ($licensedAddons !== []) : ?>
                        <p><strong><?php esc_html_e('Available add-ons:', 'asuka-product-designer'); ?></strong> <?php echo esc_html(implode(', ', array_column($licensedAddons, 'feature'))); ?></p>
                    <?php endif; ?>
                    <div class="apd-form-grid">
                        <label class="apd-toggle apd-field-full">
                            <input type="checkbox" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[license_enabled]" value="1" <?php checked($settings['license_enabled'], '1'); ?>>
                            <span><?php esc_html_e('Enable commercial license runtime', 'asuka-product-designer'); ?></span>
                        </label>
                        <label class="apd-field apd-field-full">
                            <span><?php esc_html_e('License key', 'asuka-product-designer'); ?></span>
                            <input type="password" autocomplete="new-password" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[license_key]" value="" placeholder="<?php echo esc_attr($licenseConfigured ? __('Configured - leave blank to keep it', 'asuka-product-designer') : 'ASK-XXXX-XXXX-XXXX'); ?>">
                            <small><?php esc_html_e('The key stays server-side. Browsers receive only a short-lived signed token.', 'asuka-product-designer'); ?></small>
                        </label>
                        <?php if ($licenseConfigured) : ?>
                            <label class="apd-toggle apd-field-full">
                                <input type="checkbox" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[license_key_clear]" value="1">
                                <span><?php esc_html_e('Remove the stored license key when saving', 'asuka-product-designer'); ?></span>
                            </label>
                        <?php endif; ?>
                        <div class="apd-field apd-field-full">
                            <span><?php esc_html_e('Commercial API', 'asuka-product-designer'); ?></span>
                            <code><?php echo esc_html($apiUrl); ?></code>
                            <small><?php esc_html_e('Managed by AsukaDesigner and shared by licensing, AI, and paid exports. This endpoint cannot be changed from WordPress.', 'asuka-product-designer'); ?></small>
                        </div>
                    </div>
                </section>

                <section class="apd-card apd-settings-card apd-settings-card--providers">
                    <h2><?php esc_html_e('External provider defaults', 'asuka-product-designer'); ?></h2>
                    <div class="apd-form-grid">
                        <label class="apd-field">
                            <span><?php esc_html_e('Pixabay API key', 'asuka-product-designer'); ?></span>
                            <input type="text" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[pixabay_api_key]" value="<?php echo esc_attr($settings['pixabay_api_key']); ?>">
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Pexels API key', 'asuka-product-designer'); ?></span>
                            <input type="text" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[pexels_api_key]" value="<?php echo esc_attr($settings['pexels_api_key']); ?>">
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Unsplash access key', 'asuka-product-designer'); ?></span>
                            <input type="text" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[unsplash_access_key]" value="<?php echo esc_attr($settings['unsplash_access_key']); ?>">
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Google Fonts API key', 'asuka-product-designer'); ?></span>
                            <input type="text" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[google_fonts_api_key]" value="<?php echo esc_attr($settings['google_fonts_api_key']); ?>">
                        </label>
                        <label class="apd-field">
                            <span><?php esc_html_e('Facebook app ID', 'asuka-product-designer'); ?></span>
                            <input type="text" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[facebook_app_id]" value="<?php echo esc_attr($settings['facebook_app_id']); ?>">
                        </label>
                    </div>
                </section>

                <section class="apd-card apd-settings-card apd-settings-card--retention">
                    <h2><?php esc_html_e('Data retention', 'asuka-product-designer'); ?></h2>
                    <p><?php esc_html_e('By default, deactivating or uninstalling the plugin keeps configurations, designs, settings, and catalog data so they can be restored later.', 'asuka-product-designer'); ?></p>
                    <label class="apd-toggle">
                        <input type="checkbox" name="<?php echo esc_attr(AdminSettings::OPTION); ?>[delete_data_on_uninstall]" value="1" <?php checked($settings['delete_data_on_uninstall'], '1'); ?>>
                        <span><?php esc_html_e('Permanently delete plugin data when the plugin is uninstalled', 'asuka-product-designer'); ?></span>
                    </label>
                    <p><small><?php esc_html_e('WooCommerce orders and their historical customization metadata are always preserved.', 'asuka-product-designer'); ?></small></p>
                </section>

                <footer class="apd-settings-actions">
                    <div>
                        <strong><?php esc_html_e('Apply plugin settings', 'asuka-product-designer'); ?></strong>
                        <span><?php esc_html_e('Saved changes are used for new designer sessions and future admin requests.', 'asuka-product-designer'); ?></span>
                    </div>
                    <?php submit_button(__('Save settings', 'asuka-product-designer'), 'primary', 'submit', false); ?>
                </footer>
            </form>

            <?php if ($mailpitStatus['supported']) : ?>
                <section class="apd-card apd-settings-card apd-settings-local-mail">
                    <div class="apd-card-head">
                        <div>
                            <span class="apd-badge"><?php esc_html_e('Development only', 'asuka-product-designer'); ?></span>
                            <h2><?php esc_html_e('Local email testing', 'asuka-product-designer'); ?></h2>
                            <p><?php esc_html_e('Route WordPress emails to Mailpit and inspect demo invitations, newsletter previews, and operational messages without sending anything to real recipients.', 'asuka-product-designer'); ?></p>
                        </div>
                        <?php if ($mailpitStatus['enabled']) : ?>
                            <a class="button button-secondary" href="<?php echo esc_url($mailpitStatus['inboxUrl']); ?>" target="_blank" rel="noopener noreferrer">
                                <?php esc_html_e('Open Mailpit inbox', 'asuka-product-designer'); ?>
                            </a>
                        <?php endif; ?>
                    </div>

                    <div class="apd-stat-grid apd-mailpit-stat-grid">
                        <div class="apd-mini-stat">
                            <strong><?php echo esc_html(ucfirst((string) $mailpitStatus['environment'])); ?></strong>
                            <span><?php esc_html_e('WordPress environment', 'asuka-product-designer'); ?></span>
                        </div>
                        <div class="apd-mini-stat">
                            <strong><?php echo esc_html($mailpitStatus['enabled'] ? __('Enabled', 'asuka-product-designer') : __('Disabled', 'asuka-product-designer')); ?></strong>
                            <span><?php esc_html_e('Mailpit transport', 'asuka-product-designer'); ?></span>
                        </div>
                        <div class="apd-mini-stat">
                            <strong><?php echo esc_html($mailpitStatus['reachable'] ? __('Reachable', 'asuka-product-designer') : __('Unavailable', 'asuka-product-designer')); ?></strong>
                            <span><?php echo esc_html(sprintf('%s:%d', $mailpitStatus['host'], $mailpitStatus['port'])); ?></span>
                        </div>
                    </div>

                    <?php if ($mailpitStatus['enabled']) : ?>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-mailpit-test-form">
                            <?php wp_nonce_field('apd_send_mailpit_test'); ?>
                            <input type="hidden" name="action" value="apd_send_mailpit_test">
                            <label class="apd-field">
                                <span><?php esc_html_e('Test recipient', 'asuka-product-designer'); ?></span>
                                <input type="email" name="recipient" value="<?php echo esc_attr((string) wp_get_current_user()->user_email); ?>" required>
                                <small><?php esc_html_e('Mailpit captures the message locally, so this address will not receive a real email.', 'asuka-product-designer'); ?></small>
                            </label>
                            <button type="submit" class="button button-primary" <?php disabled(! $mailpitStatus['reachable']); ?>>
                                <?php esc_html_e('Send test email', 'asuka-product-designer'); ?>
                            </button>
                        </form>
                    <?php else : ?>
                        <div class="apd-inline-note">
                            <strong><?php esc_html_e('Enable the local transport in wp-config.php', 'asuka-product-designer'); ?></strong>
                            <code>define('APD_MAILPIT_ENABLED', true);</code>
                            <p><?php esc_html_e('The transport remains disabled automatically on staging and production, even if the constant is accidentally copied.', 'asuka-product-designer'); ?></p>
                        </div>
                    <?php endif; ?>
                </section>
            <?php endif; ?>
        </div>
        <?php
    }

    private function renderMailpitNotice() : void
    {
        $query = RequestData::query();
        $result = sanitize_key((string) ($query['apd_mailpit_test'] ?? ''));
        if ($result === '') {
            return;
        }

        $recipient = sanitize_email((string) ($query['apd_mailpit_recipient'] ?? ''));
        $messages = [
            'sent' => [
                'success',
                $recipient !== ''
                    ? sprintf(
                        /* translators: %s: email address captured by Mailpit. */
                        __('Test email sent to Mailpit for %s.', 'asuka-product-designer'),
                        $recipient
                    )
                    : __('Test email sent to Mailpit.', 'asuka-product-designer'),
            ],
            'failed' => ['error', __('WordPress could not hand the message to Mailpit. Check that the SMTP service is running.', 'asuka-product-designer')],
            'disabled' => ['warning', __('The Mailpit transport is not enabled for this environment.', 'asuka-product-designer')],
            'invalid_recipient' => ['error', __('Enter a valid test recipient email address.', 'asuka-product-designer')],
        ];

        if (! isset($messages[$result])) {
            return;
        }

        [$type, $message] = $messages[$result];
        ?>
        <div class="notice notice-<?php echo esc_attr($type); ?> is-dismissible">
            <p><?php echo esc_html($message); ?></p>
        </div>
        <?php
    }
}
