<?php
/** Paid UI and AJAX endpoint for selecting an One-click Store Type. */
class BeRocket_AAPF_Paid_One_Click_Store_Types_UI {
    public function __construct() {
        add_action('brapf_one_click_store_type_control', array($this, 'render_control'), 10, 2);
        add_action('brapf_one_click_before_create', array($this, 'save_request_selection'), 10, 2);
        add_action('before_wizard_run_br-aapf-setup', array($this, 'enqueue_wizard_assets'), 30);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_filter_list_assets'));
    }

    public function render_control($source, $analysis) {
        if (!$this->current_user_can_use_store_types()) {
            return;
        }
        $selected_type = BeRocket_AAPF_Paid_One_Click_Store_Types::get_selected_type();
        ?>
        <fieldset class="brapf-store-type-control" data-recommendation-sets="<?php echo esc_attr(wp_json_encode($this->get_client_recommendation_sets($analysis))); ?>">
            <legend><?php esc_html_e('Choose your store type', 'BeRocket_AJAX_domain'); ?></legend>
            <label class="screen-reader-text" for="brapf-one-click-store-type-<?php echo esc_attr(sanitize_key($source)); ?>"><?php esc_html_e('Store type', 'BeRocket_AJAX_domain'); ?></label>
            <select id="brapf-one-click-store-type-<?php echo esc_attr(sanitize_key($source)); ?>" class="brapf-store-type-input" name="brapf_one_click_store_type">
                <?php foreach (BeRocket_AAPF_Paid_One_Click_Store_Types::get_types() as $type => $definition) { ?>
                    <option value="<?php echo esc_attr($type); ?>"<?php selected($selected_type, $type); ?>><?php echo esc_html(isset($definition['label']) ? $definition['label'] : $type); ?></option>
                <?php } ?>
            </select>
        </fieldset>
        <?php
    }

    /** Non-JavaScript fallback: persist the selected option immediately before creation. */
    public function save_request_selection($source, $wizard = null) {
        if (!$this->current_user_can_use_store_types() || !isset($_POST['brapf_one_click_store_type'])) {
            return;
        }
        BeRocket_AAPF_Paid_One_Click_Store_Types::save_selected_type(
            wp_unslash($_POST['brapf_one_click_store_type'])
        );
    }

    public function enqueue_wizard_assets() {
        if ($this->current_user_can_use_store_types()) {
            $this->enqueue_assets();
        }
    }

    public function enqueue_filter_list_assets() {
        if (!$this->is_filter_list_screen() || !$this->current_user_can_use_store_types()) {
            return;
        }
        $this->enqueue_assets();
    }

    protected function enqueue_assets() {
        wp_enqueue_style(
            'brapf-paid-one-click-store-types',
            plugins_url('assets/store-types.css', __FILE__),
            array(),
            $this->get_asset_version('store-types.css')
        );
        wp_enqueue_script(
            'brapf-paid-one-click-store-types',
            plugins_url('assets/store-types.js', __FILE__),
            array('jquery'),
            $this->get_asset_version('store-types.js'),
            true
        );
    }

    protected function get_asset_version($filename) {
        $path = __DIR__ . '/assets/' . ltrim($filename, '/\\');
        return BeRocket_AJAX_filters_version . '.' . (file_exists($path) ? (string) filemtime($path) : '0');
    }

    /**
     * Prepare every profile's short recommendation list once for this page.
     * This reuses the in-memory snapshot and has no product, taxonomy, or
     * postmeta queries, so changing an option can update instantly in JavaScript.
     */
    protected function get_client_recommendation_sets($analysis) {
        if (empty($analysis['snapshot']) || !is_array($analysis['snapshot'])
            || !class_exists('BeRocket_AAPF_One_Click_Attribute_Analyzer')
            || !class_exists('BeRocket_AAPF_One_Click_Recommendation_Ranker')
            || !class_exists('BeRocket_AAPF_Paid_One_Click_Store_Type_Ranking')) {
            return array();
        }
        $sets = array();
        foreach (BeRocket_AAPF_Paid_One_Click_Store_Types::get_types() as $type => $definition) {
            $sets[$type] = BeRocket_AAPF_Paid_One_Click_Store_Type_Ranking::with_preview_type($type, function() use ($analysis) {
                $attribute_analysis = (new BeRocket_AAPF_One_Click_Attribute_Analyzer())->analyze($analysis['snapshot']);
                $ranking = (new BeRocket_AAPF_One_Click_Recommendation_Ranker())->rank($analysis['snapshot'], $attribute_analysis);
                $labels = array();
                foreach ((array) $ranking['recommendations'] as $recommendation) {
                    $labels[] = class_exists('BeRocket_AAPF_One_Click_Welcome')
                        ? BeRocket_AAPF_One_Click_Welcome::get_recommendation_label($recommendation)
                        : (isset($recommendation['key']) ? $recommendation['key'] : '');
                }
                return array_values(array_filter($labels, 'strlen'));
            });
        }
        return $sets;
    }

    protected function current_user_can_use_store_types() {
        return BeRocket_AAPF_Paid_One_Click_Store_Types::is_available()
            && current_user_can('manage_woocommerce')
            && class_exists('BeRocket_AAPF_One_Click_Capabilities')
            && BeRocket_AAPF_One_Click_Capabilities::current_user_can_manage_setup('create');
    }

    protected function is_filter_list_screen() {
        if (!function_exists('get_current_screen')) {
            return false;
        }
        $screen = get_current_screen();
        return $screen && $screen->base === 'edit' && $screen->post_type === 'br_product_filter';
    }
}
new BeRocket_AAPF_Paid_One_Click_Store_Types_UI();
