<?php

/**
 * Global plugin settings page (WP Admin → NoonElite Audit Engine → Settings).
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class Noon_Audit_Admin_Settings {
    const OPTION_KEY = 'noon_audit_settings';

    const PAGE_SLUG = 'noonelite-audit-engine';

    public static function register_menu() {
        // Top-level menu.
        add_menu_page(
            __( 'NoonElite Audit Engine', 'noonelite-audit-engine' ),
            __( 'Site Audit', 'noonelite-audit-engine' ),
            'manage_options',
            'noonelite-audit-engine',
            [__CLASS__, 'render_page'],
            'dashicons-chart-bar',
            30
        );
        // Override the auto-generated top-level submenu item label.
        add_submenu_page(
            'noonelite-audit-engine',
            __( 'Settings', 'noonelite-audit-engine' ),
            __( 'Settings', 'noonelite-audit-engine' ),
            'manage_options',
            'noonelite-audit-engine',
            [__CLASS__, 'render_page']
        );
        // Enqueue WP Media Library scripts on our settings page.
        add_action( 'admin_enqueue_scripts', [__CLASS__, 'enqueue_admin_assets'] );
    }

    /**
     * Enqueue admin JS and CSS on plugin pages only.
     */
    public static function enqueue_admin_assets( $hook ) {
        // Only load on our plugin pages.
        $our_pages = ['toplevel_page_noonelite-audit-engine', 'site-audit_page_noonelite-audit-engine-audits', 'site-audit_page_noonelite-audit-engine-leads'];
        if ( !in_array( $hook, $our_pages, true ) ) {
            return;
        }
        // Shared admin CSS.
        wp_enqueue_style(
            'noonelite-audit-admin',
            NOON_AUDIT_PLUGIN_URL . 'includes/css/admin-styles.css',
            [],
            NOON_AUDIT_VERSION
        );
        // Settings page JS.
        if ( 'toplevel_page_noonelite-audit-engine' === $hook ) {
            wp_enqueue_media();
            wp_enqueue_script(
                'noonelite-audit-admin-settings',
                NOON_AUDIT_PLUGIN_URL . 'includes/js/admin-settings.js',
                ['jquery'],
                NOON_AUDIT_VERSION,
                true
            );
            wp_localize_script( 'noonelite-audit-admin-settings', 'noonAuditSettings', [
                'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
                'dismissNonce'  => wp_create_nonce( 'noon_audit_dismiss' ),
                'testConnNonce' => wp_create_nonce( 'noon_audit_test_conn' ),
                'i18n'          => [
                    'selectLogo'      => __( 'Select Logo', 'noonelite-audit-engine' ),
                    'shortcodeCopied' => __( 'Shortcode copied to clipboard', 'noonelite-audit-engine' ),
                    'testConnection'  => __( 'Test Connection', 'noonelite-audit-engine' ),
                    'requestFailed'   => __( 'Request failed.', 'noonelite-audit-engine' ),
                ],
            ] );
        }
    }

    public static function register_settings() {
        register_setting( 'noon_audit_settings_group', self::OPTION_KEY, [
            'sanitize_callback' => [__CLASS__, 'sanitize_branding'],
        ] );
        // ── Section: Branding & CTA ──────────────────────────────────────────
        add_settings_section(
            'noon_audit_branding',
            __( 'Branding & CTA', 'noonelite-audit-engine' ),
            null,
            self::PAGE_SLUG
        );
        $branding_fields = [
            'accent_color'    => [__( 'Accent Colour', 'noonelite-audit-engine' ), 'color'],
            'consultant_name' => [__( 'Consultant / Agency Name', 'noonelite-audit-engine' ), 'text'],
            'booking_url'     => [__( 'Booking URL or Email Address', 'noonelite-audit-engine' ), 'text'],
            'privacy_url'     => [__( 'Privacy Policy URL', 'noonelite-audit-engine' ), 'url'],
            'terms_url'       => [__( 'Terms & Conditions URL', 'noonelite-audit-engine' ), 'url'],
            'hide_title'      => [__( 'Hide Audit Title on Landing Screen', 'noonelite-audit-engine' ), 'checkbox'],
            'glass_mode'      => [__( 'Enable Glass Background (Dark Mode Only)', 'noonelite-audit-engine' ), 'checkbox'],
        ];
        foreach ( $branding_fields as $key => [$label, $type] ) {
            add_settings_field(
                $key,
                $label,
                function () use($key, $type) {
                    $opts = get_option( self::OPTION_KEY, [] );
                    $value = esc_attr( $opts[$key] ?? '' );
                    if ( $type === 'checkbox' ) {
                        $checked = ( !empty( $opts[$key] ) ? 'checked' : '' );
                        echo "<label><input type='checkbox' name='" . esc_attr( self::OPTION_KEY . "[{$key}]" ) . "' value='1' " . esc_attr( $checked ) . " /> " . esc_html__( 'Yes', 'noonelite-audit-engine' ) . "</label>";
                    } else {
                        echo "<input type='" . esc_attr( $type ) . "' name='" . esc_attr( self::OPTION_KEY . "[{$key}]" ) . "' value='" . esc_attr( $value ) . "' class='regular-text' />";
                    }
                },
                self::PAGE_SLUG,
                'noon_audit_branding'
            );
        }
        // Logo URL — with WP Media Library picker.
        add_settings_field(
            'logo_url',
            __( 'Logo', 'noonelite-audit-engine' ),
            function () {
                $opts = get_option( self::OPTION_KEY, [] );
                $value = esc_attr( $opts['logo_url'] ?? '' );
                ?>
            <div style="display:flex;align-items:center;gap:10px;">
                <input type="url" id="noon-audit-logo-url" name="<?php 
                echo esc_attr( self::OPTION_KEY );
                ?>[logo_url]" value="<?php 
                echo esc_attr( $value );
                ?>" class="regular-text" />
                <button type="button" class="button" id="noon-audit-logo-btn"><?php 
                esc_html_e( 'Choose Image', 'noonelite-audit-engine' );
                ?></button>
            </div>
            <?php 
                if ( $value ) {
                    ?>
                <div style="margin-top:10px;"><img src="<?php 
                    echo esc_url( $value );
                    ?>" style="max-height:60px;border:1px solid #ccd0d4;border-radius:4px;padding:4px;" /></div>
            <?php 
                }
                ?>
            <?php 
            },
            self::PAGE_SLUG,
            'noon_audit_branding'
        );
        // ── Section: Watermark (Opt-in) ──────────────────────────────────────
        add_settings_section(
            'noon_audit_watermark',
            __( 'Attribution', 'noonelite-audit-engine' ),
            function () {
                echo '<p class="description">' . esc_html__( 'Optionally show a credit link on your audit quizzes.', 'noonelite-audit-engine' ) . '</p>';
            },
            self::PAGE_SLUG
        );
        add_settings_field(
            'show_watermark',
            __( 'Show "Powered by" Credit', 'noonelite-audit-engine' ),
            function () {
                $opts = get_option( self::OPTION_KEY, [] );
                $checked = ( !empty( $opts['show_watermark'] ) ? 'checked' : '' );
                echo "<label><input type='checkbox' name='" . esc_attr( self::OPTION_KEY . "[show_watermark]" ) . "' value='1' " . esc_attr( $checked ) . " /> " . esc_html__( 'Display a "Powered by" credit on public audit pages', 'noonelite-audit-engine' ) . "</label>";
            },
            self::PAGE_SLUG,
            'noon_audit_watermark'
        );
        add_settings_field(
            'custom_watermark_text',
            __( 'Custom Credit Text', 'noonelite-audit-engine' ),
            function () {
                $opts = get_option( self::OPTION_KEY, [] );
                $value = esc_attr( $opts['custom_watermark_text'] ?? '' );
                echo "<input type='text' name='" . esc_attr( self::OPTION_KEY . "[custom_watermark_text]" ) . "' value='" . esc_attr( $value ) . "' class='regular-text' placeholder='" . esc_attr__( 'Powered by Your Agency', 'noonelite-audit-engine' ) . "' />";
                echo '<p class="description">' . esc_html__( 'Leave blank to use the default text.', 'noonelite-audit-engine' ) . '</p>';
            },
            self::PAGE_SLUG,
            'noon_audit_watermark'
        );
        add_settings_field(
            'custom_watermark_url',
            __( 'Custom Credit URL', 'noonelite-audit-engine' ),
            function () {
                $opts = get_option( self::OPTION_KEY, [] );
                $value = esc_attr( $opts['custom_watermark_url'] ?? '' );
                echo "<input type='url' name='" . esc_attr( self::OPTION_KEY . "[custom_watermark_url]" ) . "' value='" . esc_attr( $value ) . "' class='regular-text' placeholder='https://youragency.com' />";
                echo '<p class="description">' . esc_html__( 'Where should the watermark link to? Leaves as default if blank.', 'noonelite-audit-engine' ) . '</p>';
            },
            self::PAGE_SLUG,
            'noon_audit_watermark'
        );
        // ── Section: Theme Mode ──────────────────────────────────────────────
        add_settings_section(
            'noon_audit_theme',
            __( 'Theme', 'noonelite-audit-engine' ),
            function () {
                echo '<p class="description">' . esc_html__( 'Control the colour scheme of your public audit quizzes.', 'noonelite-audit-engine' ) . '</p>';
            },
            self::PAGE_SLUG
        );
        add_settings_field(
            'theme_mode',
            __( 'Quiz Theme Mode', 'noonelite-audit-engine' ),
            function () {
                $opts = get_option( self::OPTION_KEY, [] );
                $current = $opts['theme_mode'] ?? 'auto';
                $name_attr = self::OPTION_KEY . '[theme_mode]';
                echo "<select name='" . esc_attr( $name_attr ) . "'>";
                foreach ( [
                    'auto'  => __( 'Auto (match visitor\'s OS)', 'noonelite-audit-engine' ),
                    'dark'  => __( 'Force Dark', 'noonelite-audit-engine' ),
                    'light' => __( 'Force Light', 'noonelite-audit-engine' ),
                ] as $val => $label ) {
                    $sel = selected( $current, $val, false );
                    echo "<option value='" . esc_attr( $val ) . "' " . esc_attr( $sel ) . ">" . esc_html( $label ) . "</option>";
                }
                echo '</select>';
                echo '<p class="description">' . esc_html__( 'Auto detects the visitor\'s light/dark preference. Force overrides it for all visitors.', 'noonelite-audit-engine' ) . '</p>';
            },
            self::PAGE_SLUG,
            'noon_audit_theme'
        );
        // ── CRM Settings (stored separately, handled via custom form) ────────
        // CRM settings use their own save handler — see render_page().
    }

    // ─── Sanitize Branding ───────────────────────────────────────────────────
    public static function sanitize_branding( $input ) {
        $theme_mode = sanitize_text_field( $input['theme_mode'] ?? 'auto' );
        if ( !in_array( $theme_mode, ['auto', 'dark', 'light'], true ) ) {
            $theme_mode = 'auto';
        }
        return [
            'accent_color'          => sanitize_hex_color( $input['accent_color'] ?? '#6366f1' ),
            'consultant_name'       => sanitize_text_field( $input['consultant_name'] ?? '' ),
            'booking_url'           => ( is_email( $input['booking_url'] ?? '' ) ? sanitize_email( $input['booking_url'] ) : esc_url_raw( $input['booking_url'] ?? '' ) ),
            'privacy_url'           => esc_url_raw( $input['privacy_url'] ?? '' ),
            'terms_url'             => esc_url_raw( $input['terms_url'] ?? '' ),
            'logo_url'              => esc_url_raw( $input['logo_url'] ?? '' ),
            'hide_title'            => ( !empty( $input['hide_title'] ) ? '1' : '' ),
            'glass_mode'            => ( !empty( $input['glass_mode'] ) ? '1' : '' ),
            'show_watermark'        => ( !empty( $input['show_watermark'] ) ? '1' : '' ),
            'custom_watermark_text' => sanitize_text_field( $input['custom_watermark_text'] ?? '' ),
            'custom_watermark_url'  => esc_url_raw( $input['custom_watermark_url'] ?? '' ),
            'theme_mode'            => $theme_mode,
        ];
    }

    // ─── Render ──────────────────────────────────────────────────────────────
    public static function render_page() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( isset( $_GET['settings-updated'] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'All settings saved.', 'noonelite-audit-engine' ) . '</p></div>';
        }
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php 
        esc_html_e( 'Audit Engine Settings', 'noonelite-audit-engine' );
        ?></h1>
            <?php 
        if ( function_exists( 'noon_audit_fs' ) && !noon_audit_fs()->is_premium() ) {
            ?>
                <a href="<?php 
            echo esc_url( noon_audit_fs()->get_upgrade_url() );
            ?>" class="page-title-action" style="color:#6366f1; border-color:#6366f1;"><?php 
            esc_html_e( '🚀 Explore Pro Features', 'noonelite-audit-engine' );
            ?></a>
            <?php 
        }
        ?>
            <hr class="wp-header-end">
            <div class="noon-toast" id="noon-toast"></div>

            <!-- License Status -->
            <div class="noon-license-box">
                <?php 
        if ( function_exists( 'noon_audit_fs' ) && noon_audit_fs()->can_use_premium_code() ) {
            ?>
                    <p class="noon-license-active"><span class="dashicons dashicons-yes-alt"></span> <strong><?php 
            esc_html_e( 'Pro license active.', 'noonelite-audit-engine' );
            ?></strong> <?php 
            esc_html_e( 'All features unlocked.', 'noonelite-audit-engine' );
            ?></p>
                <?php 
        } elseif ( function_exists( 'noon_audit_fs' ) && noon_audit_fs() ) {
            ?>
                    <p class="noon-license-inactive"><span class="dashicons dashicons-lock"></span> <strong><?php 
            esc_html_e( 'Free plan.', 'noonelite-audit-engine' );
            ?></strong>
                    <a href="<?php 
            echo esc_url( noon_audit_fs()->get_upgrade_url() );
            ?>"><?php 
            esc_html_e( 'Upgrade to Pro', 'noonelite-audit-engine' );
            ?></a></p>
                <?php 
        } else {
            ?>
                    <p class="noon-license-inactive"><span class="dashicons dashicons-lock"></span> <strong><?php 
            esc_html_e( 'Free plan.', 'noonelite-audit-engine' );
            ?></strong> <?php 
            esc_html_e( 'Pro features are locked.', 'noonelite-audit-engine' );
            ?></p>
                <?php 
        }
        ?>
            </div>

            <!-- Getting Started (dismissable) -->
            <?php 
        if ( !get_user_meta( get_current_user_id(), 'noon_audit_dismiss_guide', true ) ) {
            ?>
            <div class="noon-guide-box notice notice-info is-dismissible" id="noon-audit-guide">
                <h3 style="margin-top:6px;"><span class="dashicons dashicons-clipboard" style="margin-right:4px;"></span><?php 
            esc_html_e( 'Quick Setup', 'noonelite-audit-engine' );
            ?></h3>
                <ol style="margin:8px 0 12px 20px;line-height:1.8;">
                    <li><?php 
            /* translators: %s: HTML link */
            printf( esc_html__( 'Go to %s to create or edit an audit', 'noonelite-audit-engine' ), '<a href="' . esc_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits' ) ) . '"><strong>' . esc_html__( 'Site Audit → Audits', 'noonelite-audit-engine' ) . '</strong></a>' );
            ?></li>
                    <li><?php 
            esc_html_e( 'Add the shortcode to any page or post:', 'noonelite-audit-engine' );
            ?>
                        <code id="noon-audit-shortcode" style="cursor:pointer;background:#f0f0f1;padding:3px 8px;border-radius:3px;" title="<?php 
            esc_attr_e( 'Click to copy', 'noonelite-audit-engine' );
            ?>">[noon_audit type="your-slug"]</code>
                        <button type="button" class="button button-small" id="noon-audit-copy-btn" style="margin-left:4px;"><span class="dashicons dashicons-clipboard" style="font-size:14px;width:14px;height:14px;vertical-align:middle;"></span> <?php 
            esc_html_e( 'Copy', 'noonelite-audit-engine' );
            ?></button>
                    </li>
                    <li><?php 
            esc_html_e( 'Done! Your audit quiz is live on the front end.', 'noonelite-audit-engine' );
            ?></li>
                </ol>
                <p class="description"><?php 
            /* translators: 1: slug placeholder, 2: HTML link */
            printf( esc_html__( 'Replace %1$s with the audit slug from the %2$s page. You can find the exact shortcode next to each audit.', 'noonelite-audit-engine' ), '<code>your-slug</code>', '<a href="' . esc_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits' ) ) . '">' . esc_html__( 'Audits', 'noonelite-audit-engine' ) . '</a>' );
            ?></p>
                <button type="button" class="button-link notice-dismiss noon-audit-dismiss-guide" style="position:absolute;top:0;right:1px;border:none;margin:0;padding:9px;"><span class="screen-reader-text"><?php 
            esc_html_e( 'Dismiss this notice', 'noonelite-audit-engine' );
            ?></span></button>
            </div>
            <?php 
        }
        ?>

            <!-- Branding + Watermark + White Label (WP Settings API) -->
            <form method="post" action="options.php">
                <?php 
        settings_fields( 'noon_audit_settings_group' );
        do_settings_sections( self::PAGE_SLUG );
        ?>

                <hr>

                <!-- CRM Settings (Injected into Main Form) -->
                <?php 
        ?>
                
                <?php 
        submit_button( __( 'Save All Settings', 'noonelite-audit-engine' ), 'primary' );
        ?>
            </form>
        </div>
        <?php 
    }

}
