<?php
class SeekMake_Admin {

    private $plugin_name;
    private $version;

    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    public function enqueue_styles($hook) {
        $allowed_hooks = array(
            'toplevel_page_seekmake',
            'seekmake_page_seekmake-settings'
        );

        if (!in_array($hook, $allowed_hooks)) {
            return;
        }

        $css_file = SEEKMAKE_PLUGIN_DIR . 'assets/css/admin.css';
        $version = file_exists($css_file) ? filemtime($css_file) : $this->version;
        
        wp_enqueue_style(
            $this->plugin_name,
            SEEKMAKE_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            $version,
            'all'
        );
        
        $is_authenticated = get_option('seekmake_authenticated', false);

        if ($is_authenticated) {
            $lovable_css = SEEKMAKE_PLUGIN_DIR . 'assets/css/lovable-success.css';
            $lovable_version = file_exists($lovable_css) ? filemtime($lovable_css) : $this->version;
            
            wp_enqueue_style(
                $this->plugin_name . '-lovable',
                SEEKMAKE_PLUGIN_URL . 'assets/css/lovable-success.css',
                array(),
                $lovable_version,
                'all'
            );
        } else {
            $connect_css = SEEKMAKE_PLUGIN_DIR . 'assets/css/lovable-connect.css';
            $connect_version = file_exists($connect_css) ? filemtime($connect_css) : $this->version;

            wp_enqueue_style(
                $this->plugin_name . '-connect',
                SEEKMAKE_PLUGIN_URL . 'assets/css/lovable-connect.css',
                array(),
                $connect_version,
                'all'
            );
        }
    }

    public function enqueue_scripts($hook) {
        $allowed_hooks = array(
            'toplevel_page_seekmake',
            'seekmake_page_seekmake-settings'
        );

        if (!in_array($hook, $allowed_hooks)) {
            return;
        }

        $js_file = SEEKMAKE_PLUGIN_DIR . 'assets/js/admin-iframe.js';
        $version = file_exists($js_file) ? filemtime($js_file) : $this->version;
        
        wp_enqueue_script(
            $this->plugin_name,
            SEEKMAKE_PLUGIN_URL . 'assets/js/admin-iframe.js',
            array('jquery'),
            $version,
            false
        );

        wp_localize_script(
            $this->plugin_name,
            'seekmakeAdmin',
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('seekmake_event'),
                'settingsNonce' => wp_create_nonce('seekmake_settings'),
                'manufacturerId' => get_option('seekmake_manufacturer_id', ''),
                'dashboardUrl' => SEEKMAKE_DASHBOARD_URL,
                'isEmbed' => true,
                'cacheVersion' => $version
            )
        );

        if (in_array($hook, $allowed_hooks)) {
            wp_enqueue_script(
                $this->plugin_name . '-settings',
                SEEKMAKE_PLUGIN_URL . 'assets/js/settings.js',
                array('jquery'),
                $version,
                true
            );

            wp_localize_script(
                $this->plugin_name . '-settings',
                'seekmakeSettings',
                array(
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('seekmake_event'),
                    'confirmMsg' => __('Are you sure you want to disconnect your SeekMake account? This will remove all authentication data and you will need to log in again to use the widgets.', 'seekmake'),
                    'disconnectingMsg' => __('Disconnecting...', 'seekmake'),
                    'successMsg' => __('Account disconnected successfully! All data cleared.', 'seekmake'),
                    'redirectUrl' => admin_url('admin.php?page=seekmake&logout=1&t='),
                    'errorMsg' => __('An error occurred. Please try again.', 'seekmake'),
                    'failMsg' => __('Failed to disconnect. Please try again.', 'seekmake'),
                    'logoutUrl' => SEEKMAKE_LOGOUT_URL,
                    'btnText' => __('Disconnect Account', 'seekmake')
                )
            );
        }
    }

    public function add_plugin_admin_menu() {
        add_menu_page(
            __('SeekMake', 'seekmake'),
            __('SeekMake', 'seekmake'),
            'manage_options',
            'seekmake',
            array($this, 'display_dashboard_page'),
            SEEKMAKE_PLUGIN_URL . 'assets/images/icon.svg',
            30
        );

        add_submenu_page(
            'seekmake',
            __('Dashboard', 'seekmake'),
            __('Dashboard', 'seekmake'),
            'manage_options',
            'seekmake',
            array($this, 'display_dashboard_page')
        );

        add_submenu_page(
            'seekmake',
            __('Settings', 'seekmake'),
            __('Settings', 'seekmake'),
            'manage_options',
            'seekmake-settings',
            array($this, 'display_settings_page')
        );
    }

    public function display_dashboard_page() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'seekmake'));
        }

        if (isset($_GET['seekmake_auth_callback']) && $_GET['seekmake_auth_callback'] === '1') {
            $this->handle_oauth_callback();
        }

        $manufacturer_id = get_option('seekmake_manufacturer_id', '');

        include_once SEEKMAKE_PLUGIN_DIR . 'admin/views/dashboard.php';
    }

    private function handle_oauth_callback() {
        if (isset($_GET['success']) && $_GET['success'] === 'true') {
            if (isset($_GET['businessId'])) {
                $business_id = sanitize_text_field($_GET['businessId']);
                
                update_option('seekmake_manufacturer_id', $business_id);
                update_option('seekmake_authenticated', true);

                $default_widgets = array('Instant Quote', 'Client Dashboard', 'Astra AI');
                update_option('seekmake_active_plugins', $default_widgets);
                update_option('seekmake_widgets_activated', true);
                
                wp_redirect(admin_url('admin.php?page=seekmake&auth_success=1'));
                exit;
            } else {
                add_settings_error(
                    'seekmake_messages',
                    'seekmake_auth_error',
                    __('Authentication successful but business ID was not provided. Please try again.', 'seekmake'),
                    'error'
                );
            }
        } else {
            add_settings_error(
                'seekmake_messages',
                'seekmake_auth_error',
                __('Authentication failed. Please try again.', 'seekmake'),
                'error'
            );
        }
    }

    public function display_settings_page() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'seekmake'));
        }

        include_once SEEKMAKE_PLUGIN_DIR . 'admin/views/settings.php';
    }

    public function register_settings() {
        register_setting(
            'seekmake_settings_group',
            'seekmake_manufacturer_id',
            array(
                'type' => 'string',
                'sanitize_callback' => array('SeekMake_Security', 'sanitize_manufacturer_id'),
                'default' => ''
            )
        );

        register_setting(
            'seekmake_settings_group',
            'seekmake_settings',
            array(
                'type' => 'array',
                'sanitize_callback' => array('SeekMake_Security', 'sanitize_event_data'),
                'default' => array()
            )
        );

        add_settings_section(
            'seekmake_general_section',
            __('General Settings', 'seekmake'),
            array($this, 'general_section_callback'),
            'seekmake-settings'
        );

        add_settings_field(
            'seekmake_manufacturer_id',
            __('Manufacturer ID', 'seekmake'),
            array($this, 'manufacturer_id_field_callback'),
            'seekmake-settings',
            'seekmake_general_section'
        );

        // WooCommerce Integration
        register_setting(
            'seekmake_settings_group',
            'seekmake_woocommerce_enabled',
            array(
                'type' => 'boolean',
                'sanitize_callback' => 'rest_sanitize_boolean',
                'default' => false
            )
        );

        add_settings_section(
            'seekmake_integrations_section',
            __('Integrations', 'seekmake'),
            array($this, 'integrations_section_callback'),
            'seekmake-settings'
        );

        add_settings_field(
            'seekmake_woocommerce_enabled',
            __('WooCommerce Integration', 'seekmake'),
            array($this, 'woocommerce_field_callback'),
            'seekmake-settings',
            'seekmake_integrations_section'
        );
    }

    public function general_section_callback() {
        echo '<p>' . esc_html__('Configure your SeekMake integration settings.', 'seekmake') . '</p>';
    }

    public function manufacturer_id_field_callback() {
        $manufacturer_id = get_option('seekmake_manufacturer_id', '');
        $is_authenticated = get_option('seekmake_authenticated', false);
        
        ?>
        <input 
            type="text" 
            id="seekmake_manufacturer_id" 
            name="seekmake_manufacturer_id" 
            value="<?php echo esc_attr($manufacturer_id); ?>" 
            class="regular-text"
            readonly
            style="background-color: #f0f0f1; cursor: not-allowed;"
            placeholder="<?php esc_attr_e('Not connected yet', 'seekmake'); ?>"
        />
        <p class="description">
            <?php if ($is_authenticated && !empty($manufacturer_id)): ?>
                <span style="color: #10b981; font-weight: 600;">✓ Auto-synced from SeekMake</span><br>
                <?php esc_html_e('This ID was automatically captured when you connected your SeekMake account.', 'seekmake'); ?>
            <?php else: ?>
                <span style="color: #1d6ade; font-weight: 600;">ℹ Connect your SeekMake account from the Dashboard to automatically sync your Manufacturer ID.</span>
            <?php endif; ?>
        </p>
        <?php
    }

    public function integrations_section_callback() {
        echo '<p>' . esc_html__('Connect SeekMake with other plugins on your site.', 'seekmake') . '</p>';
    }

    public function woocommerce_field_callback() {
        $enabled = get_option('seekmake_woocommerce_enabled', false);
        $woo_active = class_exists('WooCommerce');

        ?>
        <label for="seekmake_woocommerce_enabled">
            <input
                type="checkbox"
                id="seekmake_woocommerce_enabled"
                name="seekmake_woocommerce_enabled"
                value="1"
                <?php checked($enabled, true); ?>
                <?php disabled(!$woo_active); ?>
            />
            <?php esc_html_e('Enable WooCommerce cart integration for the Instant Quote widget', 'seekmake'); ?>
        </label>
        <?php if (!$woo_active): ?>
            <p class="description" style="color: #d63638;">
                <?php esc_html_e('WooCommerce must be installed and activated to use this feature.', 'seekmake'); ?>
            </p>
        <?php else: ?>
            <p class="description">
                <?php esc_html_e('When enabled, customers can add quotes directly to the WooCommerce cart from the Instant Quote widget.', 'seekmake'); ?>
            </p>
        <?php endif; ?>
        <?php
    }
}
