<?php
/**
 * Setup wizard class
 *
 * Intial Setup Wizard for FluentCRM
 *
 */

namespace FluentCrm\App\Hooks\Handlers;

use FluentCrm\App\Services\PermissionManager;
use FluentCrm\App\Services\TransStrings;
use FluentCrm\App\Vite;
use FluentCrm\Framework\Support\Arr;

/**
 *  SetupWizard Class
 *
 * @package FluentCrm\App\Hooks
 *
 * @version 1.0.0
 */
class SetupWizard
{
    /**
     * Hook in tabs.
     */
    public function __construct()
    {
        /**
         * Determine whether to enable the FluentCRM setup wizard.
         *
         * This filter allows you to enable or disable the setup wizard for FluentCRM.
         *
         * @since 1.0.0
         *
         * @param bool Whether to enable the setup wizard. Default true.
         */
        if (apply_filters('fluentcrm_setup_wizard', true) && current_user_can('manage_options')) {
            if(fluentcrm_get_option('fluentcrm_setup_wizard_ran') == 'yes') {
                wp_redirect(admin_url('admin.php?page=fluentcrm-admin&setup_complete=' . time()));
                exit();
            }

            fluentcrm_update_option('fluentcrm_setup_wizard_ran', 'yes');
            $this->setup_wizard();
        }
    }

    /**
     * Show the setup wizard
     */
    public function setup_wizard()
    {
        add_filter('user_can_richedit', '__return_true');

        if (!function_exists('media_handle_upload')) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/media.php');
        }
        

        if (current_user_can('upload_files')) {
            wp_enqueue_script('media-upload');
        }
        add_thickbox();

        wp_enqueue_editor();
        

        if (function_exists('wp_enqueue_media')) {
            wp_enqueue_media();
        }


        // Inject Vite HMR client — mirrors AdminMenu::loadCssJs().
        // Without this, Vue <style> blocks are not applied in dev mode.
        add_action('admin_head', function () {
            Vite::injectViteClient();
        }, 1);

        // style.css is the merged bundle of all Vue component CSS + Element Plus CSS,
        // produced by vite.config.mjs's mergeCssChunksPlugin. The manifest is
        // stripped of references to the merged files at build time
        // (moveManifestPlugin), so Vite::enqueueScript's auto-enqueue won't
        // pick it up — load it explicitly here. In dev mode, Vite HMR
        // injects the styles via the client above.
        if (!Vite::underDevelopment()) {
            wp_enqueue_style(
                'fluentcrm_vendor',
                fluentCrmMix('admin/css/style.css'),
                [],
                FLUENTCRM_PLUGIN_VERSION
            );
        }

        wp_enqueue_style(
            'fluentcrm-setup',
            fluentCrmMix('admin/css/setup-wizard.css'),
            ['dashicons']
        );

        // Use Vite::enqueueScript so handles are added to $moduleScripts,
        // ensuring type="module" is applied correctly in both dev and production.
        Vite::enqueueScript('fluentcrm-boot', 'admin/boot.js', ['jquery'], FLUENTCRM_PLUGIN_VERSION, true);
        Vite::enqueueScript('fluentcrm-setup', 'admin/setup-wizard.js', ['fluentcrm-boot'], FLUENTCRM_PLUGIN_VERSION, true);

        wp_enqueue_script('lodash');

        $existingSettings = get_option(FLUENTCRM . '-global-settings');
        $businessSettings = Arr::get($existingSettings, 'business_settings', []);

        $currentUser = wp_get_current_user();

        wp_localize_script('fluentcrm-boot', 'fcAdmin', [
            'ajaxurl'           => admin_url('admin-ajax.php'),
            'slug'              => FLUENTCRM,
            'rest'              => $this->getRestInfo(FluentCrm()),
            'trans'             => TransStrings::getStrings(),
            'dashboard_url'     => admin_url('admin.php?page=fluentcrm-admin&setup_complete=' . time()),
            'business_settings' => (object) $businessSettings,
            'has_fluentform'    => defined('FLUENTFORM'),
            'has_fluentcart'    => defined('FLUENTCART_VERSION'),
            'auth' => [
                'permissions' => PermissionManager::currentUserPermissions(),
                'first_name' => $currentUser->first_name,
                'last_name' => $currentUser->last_name,
                'email' => $currentUser->user_email,
                'avatar' => fluentcrmGetAvatarHtml($currentUser->user_email, $currentUser->display_name, 128),
                'user_id' => $currentUser->ID
            ],
        ]);

        $this->outputHtml();
    }

    /**
     * Setup Wizard HTML
     */
    public function outputHtml()
    {
        ob_start();
        fluentCrm('view')->render('admin.setup_wizard');
        exit();
    }

    protected function getRestInfo($app)
    {
        $ns = $app->config->get('app.rest_namespace');
        $v = $app->config->get('app.rest_version');

        return [
            'base_url'  => esc_url_raw(rest_url()),
            'url'       => rest_url($ns . '/' . $v),
            'nonce'     => wp_create_nonce('wp_rest'),
            'namespace' => $ns,
            'version'   => $v,
        ];
    }
}
