<?php

/**
 * Plugin Name: NoonElite Audit Engine
 * Plugin URI:  https://noonelite.com
 * Description: Interactive audit quizzes that score visitors and capture leads. Embed with [noon_audit type="salesforce-health"].
 * Version:     1.0.6
 * Author:      Noon Elite
 * Author URI:  https://profiles.wordpress.org/noonelite/
 * License:     GPL-2.0-or-later
 * Text Domain: noonelite-audit-engine
 * 
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
define( 'NOON_AUDIT_VERSION', '1.0.5' );
define( 'NOON_AUDIT_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'NOON_AUDIT_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
// ─── Freemius SDK (Pro licensing) ────────────────────────────────────────────
// Freemius is loaded first so premium checks work in all subsequent classes.
if ( function_exists( 'noon_audit_fs' ) ) {
    noon_audit_fs()->set_basename( false, __FILE__ );
} else {
    if ( !function_exists( 'noon_audit_fs' ) ) {
        // Create a helper function for easy SDK access.
        function noon_audit_fs() {
            global $noon_audit_fs;
            if ( !isset( $noon_audit_fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
                $noon_audit_fs = fs_dynamic_init( array(
                    'id'               => '25138',
                    'slug'             => 'auditace',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_641150b0be0f2628d5b6810c9d9ac',
                    'is_premium'       => false,
                    'premium_suffix'   => 'Pro',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => true,
                    'menu'             => array(
                        'slug'    => 'noonelite-audit-engine',
                        'support' => true,
                        'pricing' => true,
                        'contact' => true,
                        'forums'  => true,
                    ),
                    'is_live'          => true,
                ) );
            }
            return $noon_audit_fs;
        }

        // Init Freemius.
        noon_audit_fs();
        // Fix WordPress.org forum slug (internal Freemius slug is 'auditace').
        noon_audit_fs()->add_filter( 'support_forum_url', function () {
            return 'https://wordpress.org/support/plugin/noonelite-audit-engine/';
        } );
        // Signal that SDK was initiated.
        do_action( 'noon_audit_fs_loaded' );
        /*
        // Load text domain for translations.
        // NOTE: WordPress.org automatically loads translations from their systems now.
        // If you are hosting this plugin elsewhere, you may need to uncomment this.
        load_plugin_textdomain( 'noonelite-audit-engine', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
        */
    }
    // ─── Include Classes ─────────────────────────────────────────────────────────
    require_once NOON_AUDIT_PLUGIN_DIR . 'includes/class-database.php';
    require_once NOON_AUDIT_PLUGIN_DIR . 'includes/class-rest-api.php';
    require_once NOON_AUDIT_PLUGIN_DIR . 'includes/class-admin-settings.php';
    require_once NOON_AUDIT_PLUGIN_DIR . 'includes/class-admin-audits.php';
    require_once NOON_AUDIT_PLUGIN_DIR . 'includes/class-admin-leads.php';
    // ─── Activation / Deactivation ───────────────────────────────────────────────
    register_activation_hook( __FILE__, ['Noon_Audit_Database', 'activate'] );
    register_deactivation_hook( __FILE__, ['Noon_Audit_Database', 'deactivate'] );
    noon_audit_fs()->add_action( 'after_uninstall', ['Noon_Audit_Database', 'uninstall'] );
    // ─── Initialise Components ───────────────────────────────────────────────────
    add_action( 'init', function () {
        Noon_Audit_REST_API::register();
    } );
    add_action( 'admin_menu', function () {
        Noon_Audit_Admin_Settings::register_menu();
        Noon_Audit_Admin_Audits::register_menu();
        Noon_Audit_Admin_Leads::register_menu();
    } );
    add_action( 'admin_init', function () {
        Noon_Audit_Admin_Settings::register_settings();
        Noon_Audit_Admin_Audits::handle_actions();
        Noon_Audit_Admin_Leads::handle_actions();
        Noon_Audit_Database::maybe_upgrade();
    } );
    // ─── AJAX: Dismiss Getting Started Guide ─────────────────────────────────────
    add_action( 'wp_ajax_noon_audit_dismiss_guide', function () {
        check_ajax_referer( 'noon_audit_dismiss' );
        update_user_meta( get_current_user_id(), 'noon_audit_dismiss_guide', '1' );
        wp_send_json_success();
    } );
    // ─── Shortcode ───────────────────────────────────────────────────────────────
    add_shortcode( 'noon_audit', function ( $atts ) {
        $atts = shortcode_atts( [
            'type' => '',
        ], $atts, 'noon_audit' );
        $slug = sanitize_title( $atts['type'] );
        // Resolve audit from slug.
        $audit_id = '';
        if ( $slug ) {
            $audit = Noon_Audit_Database::get_audit_by_slug( $slug );
            if ( $audit ) {
                $audit_id = $audit->id;
            }
        }
        // Enqueue the React app.
        $dist_dir = NOON_AUDIT_PLUGIN_DIR . 'frontend/dist/';
        $dist_url = NOON_AUDIT_PLUGIN_URL . 'frontend/dist/';
        $asset_js = 'auditace.js';
        // The built filename shouldn't break the plugin directory rules.
        $asset_css = 'auditace.css';
        if ( file_exists( $dist_dir . $asset_css ) ) {
            wp_enqueue_style(
                'noon-audit-styles',
                $dist_url . $asset_css,
                [],
                NOON_AUDIT_VERSION
            );
        }
        wp_enqueue_script(
            'noon-audit-app',
            $dist_url . $asset_js,
            [],
            NOON_AUDIT_VERSION,
            true
        );
        // Determine watermark visibility (opt-in: only shown if admin enables it).
        $settings = get_option( 'noon_audit_settings', [] );
        $show_watermark = !empty( $settings['show_watermark'] );
        $watermark_text = '';
        if ( $show_watermark ) {
            $watermark_text = ( !empty( $settings['custom_watermark_text'] ) ? $settings['custom_watermark_text'] : __( 'Powered by Noon Elite', 'noonelite-audit-engine' ) );
        }
        // Determine theme mode.
        $theme_mode = 'auto';
        // auto = prefers-color-scheme
        if ( !empty( $settings['theme_mode'] ) && in_array( $settings['theme_mode'], ['dark', 'light'], true ) ) {
            $theme_mode = $settings['theme_mode'];
        }
        $turnstile_site_key = '';
        // Pass config to the React app.
        $root_id = 'noon-audit-root-' . wp_unique_id();
        wp_localize_script( 'noon-audit-app', 'noon_audit_config', [
            'rootId'           => $root_id,
            'auditSlug'        => $slug,
            'auditId'          => $audit_id,
            'restUrl'          => esc_url_raw( rest_url( 'noon_audit/v1' ) ),
            'nonce'            => wp_create_nonce( 'wp_rest' ),
            'accentColor'      => $settings['accent_color'] ?? '#6366f1',
            'consultantName'   => $settings['consultant_name'] ?? '',
            'bookingUrl'       => $settings['booking_url'] ?? '',
            'privacyUrl'       => $settings['privacy_url'] ?? '',
            'termsUrl'         => $settings['terms_url'] ?? '',
            'logoUrl'          => $settings['logo_url'] ?? '',
            'hideTitle'        => !empty( $settings['hide_title'] ),
            'glassMode'        => !empty( $settings['glass_mode'] ),
            'showWatermark'    => $show_watermark,
            'watermarkText'    => $watermark_text,
            'watermarkUrl'     => $settings['custom_watermark_url'] ?? 'https://noonelite.com',
            'themeMode'        => $theme_mode,
            'turnstileSiteKey' => $turnstile_site_key,
        ] );
        $theme_attr = ( $theme_mode !== 'auto' ? ' data-noon-theme="' . esc_attr( $theme_mode ) . '"' : '' );
        return '<div id="' . esc_attr( $root_id ) . '" class="noon-audit-wrapper" data-audit-slug="' . esc_attr( $slug ) . '"' . $theme_attr . '></div>';
    } );
}
// End of Freemius else block.