<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) exit;

class Rdg_Blocks_Av_Picks_Sticky extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_AV_PICKS_STICKY;
    private $block_folder_name = 'rdg-av-picks-sticky';
    protected $block_title = 'RDG AV Picks Sticky';
    private $block_description = 'The block displays available picks in a sticky bar at the bottom of the page';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'picks', 'sticky', 'bar', 'api'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = false;
    protected $is_config = true;
    protected $is_styles_load = true;
    protected $config_page_title = 'Available Picks Sticky Bar';
    protected $config_menu_title = 'AV Picks Sticky';

    public function init() {
        $this->register_block();
        add_action('acf/init', [$this, 'register_fields'], 20);
        add_action('acf/init', [$this, 'register_config_menu'], 20);
    }

    private function register_block() {
        if (function_exists('acf_register_block_type')) {
            $rdg_helpers = new Rdg_Blocks_Helpers();
            
            $block_config = [
                'name' => $this->block_name,
                'title' => __($this->block_title),
                'description' => __($this->block_description),
                'category' => $this->block_category,
                'icon' => $this->block_icon,
                'keywords' => $this->block_keywords,
                'mode' => $this->block_mode,
                'render_template' => RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php",
            ];
            
            // Try to enqueue style if it exists in the manifest
            // Only add enqueue_style if the file exists to avoid errors
            $enqueue_style = null;
            try {
                $enqueue_style = $rdg_helpers->webpack('rdg_av_picks_sticky.css');
            } catch (\InvalidArgumentException $e) {
                // CSS file not yet built, skip enqueue for now
                $enqueue_style = null;
            } catch (\Exception $e) {
                // Catch any other exceptions as well
                $enqueue_style = null;
            }
            
            if ($enqueue_style !== null) {
                $block_config['enqueue_style'] = $enqueue_style;
            }
            
            // Try to enqueue script if it exists in the manifest
            $enqueue_script = null;
            try {
                $enqueue_script = $rdg_helpers->webpack('rdg_av_picks_sticky.js');
            } catch (\InvalidArgumentException $e) {
                // JS file not yet built, skip enqueue for now
                $enqueue_script = null;
            } catch (\Exception $e) {
                // Catch any other exceptions as well
                $enqueue_script = null;
            }
            
            if ($enqueue_script !== null) {
                $block_config['enqueue_script'] = $enqueue_script;
            }
            
            $block_config['example'] = array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-av-picks-sticky-template-preview.jpg",
                        ),
                    ),
                );
            $block_config['supports'] = [
                    'jsx' => true,
                    'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ];
            $block_config['render_callback'] = function($block) use ($rdg_helpers) {
                    global $wp_query;
                    $loop = $wp_query->in_the_loop;
                    $template_path = RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php";

                    if ($loop) {
                        include $template_path;
                        return;
                    }

                    $trace_config = $rdg_helpers->getBacktraceConfig();
                    $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $trace_config['max_trace']);
                    $trace_valid_admin = $rdg_helpers->checkExistsTraceFunction($traces, $trace_config['max_trace'], $trace_config['functions']);

                    if (is_admin() && !$trace_valid_admin) {
                        include $template_path;
                        return;
                    }
                };
            
            acf_register_block_type($block_config);
        }
    }

    public function register_fields() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_av_picks_sticky_block',
                'title' => 'Block_rdg_av_picks_sticky',
                'fields' => array(
                    array(
                        'key' => 'field_av_picks_sticky_bar_bg_color',
                        'label' => 'Bar Background Color',
                        'name' => 'bar_background_color',
                        'aria-label' => '',
                        'type' => 'color_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'enable_opacity' => 0,
                        'return_format' => 'string',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_disable',
                        'label' => 'Disable Sticky',
                        'name' => 'disable_sticky',
                        'aria-label' => '',
                        'type' => 'true_false',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'message' => '',
                        'default_value' => 0,
                        'ui' => 1,
                        'ui_on_text' => '',
                        'ui_off_text' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_button_theme',
                        'label' => 'Button Theme',
                        'name' => 'button_theme',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'default' => 'Default',
                            'hndcps' => 'Handicappers',
                        ),
                        'default_value' => 'default',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_hide_zero',
                        'label' => 'Hide Zero Picks',
                        'name' => 'hide_zero_picks',
                        'aria-label' => '',
                        'type' => 'true_false',
                        'instructions' => 'Hide sports that have 0 picks',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'message' => '',
                        'default_value' => 0,
                        'ui' => 1,
                        'ui_on_text' => '',
                        'ui_off_text' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_links_behavior',
                        'label' => 'Links Open Behavior',
                        'name' => 'links_behavior',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'default' => 'Same Tab',
                            'blank' => 'New Tab',
                        ),
                        'default_value' => 'default',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_link_url_behavior',
                        'label' => 'Links Url Behavior',
                        'name' => 'link_url_behavior',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => 'Select the link behavior, the backend leaves the link as they come from the api, the Front End allows you to send users to custom relative url',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'backend' => 'Backend',
                            'frontend' => 'Front End',
                            'custom' => 'Custom Links',
                        ),
                        'default_value' => 'backend',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_internal_url',
                        'label' => 'Internal Url',
                        'name' => 'internal_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => 'Enter a relative or absolute URL',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_av_picks_sticky_link_url_behavior',
                                    'operator' => '==',
                                    'value' => 'frontend',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_custom_links',
                        'label' => 'Custom Links',
                        'name' => 'custom_links',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => 'Map sport names to custom URLs. The sport name must match exactly as it appears in the API response (case-sensitive). You can check the API response or preview the block to see available sport names.',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_av_picks_sticky_link_url_behavior',
                                    'operator' => '==',
                                    'value' => 'custom',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'block',
                        'pagination' => 0,
                        'min' => 0,
                        'max' => 0,
                        'collapsed' => '',
                        'button_label' => 'Add Custom Link',
                        'rows_per_page' => 20,
                        'sub_fields' => array(
                            array(
                                'key' => 'field_av_picks_sticky_custom_links_sport_name',
                                'label' => 'Sport Name',
                                'name' => 'sport_name',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => 'Enter the sport name exactly as it appears in the API response (e.g., "NFL", "NBA", "MLB")',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => 'e.g., NFL',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_av_picks_sticky_custom_links',
                            ),
                            array(
                                'key' => 'field_av_picks_sticky_custom_links_custom_url',
                                'label' => 'Custom URL',
                                'name' => 'custom_url',
                                'aria-label' => '',
                                'type' => 'url',
                                'instructions' => 'Enter the custom URL for this sport (can be relative or absolute)',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'placeholder' => 'e.g., /sports/nfl or https://example.com/nfl',
                                'parent_repeater' => 'field_av_picks_sticky_custom_links',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_expand_btn_bg_color',
                        'label' => 'Expand Button Background Color',
                        'name' => 'expand_button_background_color',
                        'aria-label' => '',
                        'type' => 'color_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'enable_opacity' => 0,
                        'return_format' => 'string',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_expand_btn_text_color',
                        'label' => 'Expand Button Text Color',
                        'name' => 'expand_button_text_color',
                        'aria-label' => '',
                        'type' => 'color_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'enable_opacity' => 0,
                        'return_format' => 'string',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-av-picks-sticky',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function register_config_menu() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'api_configuration_av_picks_sticky_block',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_av_picks_sticky_api_endpoint',
                        'label' => 'API Endpoint',
                        'name' => 'av_picks_sticky_api_endpoint',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_api_token',
                        'label' => 'API Token',
                        'name' => 'av_picks_sticky_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_av_picks_sticky_picks_admin_url',
                        'label' => 'Picks Admin URL',
                        'name' => 'av_picks_sticky_picks_admin_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => 'Base URL that will be prepended to the game links (e.g., https://example.com)',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-av-picks-sticky',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_endpoint = get_field('av_picks_sticky_api_endpoint', 'option');
        $api_token = get_field('av_picks_sticky_api_token', 'option');
        
        $api_endpoint = (substr($api_endpoint, -1) == '/') ? substr($api_endpoint, 0, strlen($api_endpoint) -1) : $api_endpoint;
        $api_request = $api_endpoint;
        
        $api_request .= '?api_token=' . $api_token;
        
        return [
            'method' => 'GET',
            'headers' => ['Accept: application/json'],
            'request' => $api_request,
        ];
    }

    public function getApiParams() {
        return [];
    }

    public function getFieldsValidate() {
        return [];
    }

    public function getPreSavedData($data, $attributes = []) {
        return $data;
    }

    public function getColorsToloadGeneratePress() {
        return [];
    }

    public function getStylesToloadGeneratePress() {
        return [];
    }
}

$rdg_av_picks_sticky_class = new Rdg_Blocks_Av_Picks_Sticky();
$rdg_av_picks_sticky_class->init();

return $rdg_av_picks_sticky_class;

