<?php

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

class Rdg_Blocks_Picks_Vs_Categories extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_PICKS_VS_CATEGORIES;
    private $block_folder_name = 'rdg-picks-vs-categories';
    protected $block_title = 'RDG Picks Vs Categories';
    private $block_description = 'This block allow to create a 3 columns table with multiple picks categorized by sport or sport categories';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'sports', 'picks', 'category', 'categories', 'api'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = true;
    protected $is_config = true;
    protected $is_styles_load = true;
    protected $config_page_title = 'RDG Picks Vs Categories';
    protected $config_menu_title = 'Picks Vs Categories';
    protected $interval_field = 'picks_vs_categories_interval';

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

    private function register_block() {
        if (function_exists('acf_register_block_type')) {
            $rdg_helpers = new Rdg_Blocks_Helpers();
            acf_register_block_type([
                '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",
                'enqueue_style' => $rdg_helpers->webpack('rdg_picks_vs_categories.css'),
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-picks-vs-categori-template-preview.jpg",
                        ),
                    ),
                ),
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
                '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;
                    }
                },
            ]);
        }
    }

    public function register_fields() {
        $rdgb_helpers = New Rdg_Blocks_Helpers;

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'block_rdg_picks_vs_category_group_64b04a8884b9d',
                'title' => 'Block RDG Picks Vs Category',
                'fields' => array(
                    array(
                        'key' => 'field_64b04a888fa07',
                        'label' => 'Show In',
                        'name' => 'show_in',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'full' => 'Full width',
                            'content' => 'Content width',
                        ),
                        'default_value' => 'full',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_64b04a88936a4',
                        'label' => 'Link Options',
                        'name' => 'link_options',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'none' => 'None',
                            'default' => 'API',
                            'custom' => 'Custom',
                        ),
                        'default_value' => 'none',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_64b04a8897166',
                        'label' => 'Link',
                        'name' => 'custom_link',
                        'aria-label' => '',
                        'type' => 'link',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88936a4',
                                    'operator' => '==',
                                    'value' => 'custom',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'return_format' => 'array',
                    ),
                    array(
                        'key' => 'field_64b04a88ad2ff',
                        'label' => 'Filter Date',
                        'name' => 'filter_date',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'hide' => 'Hide',
                            'show' => 'Show',
                        ),
                        'default_value' => 'hide',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_64b04a88b0fac',
                        'label' => 'Date Type',
                        'name' => 'date_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88ad2ff',
                                    'operator' => '==',
                                    'value' => 'show',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'yesterday' => 'Yesterday',
                            'now' => 'Now',
                            'tomorrow' => 'Tomorrow',
                            'range' => 'Range',
                        ),
                        'default_value' => 'now',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_64b04a88b4a24',
                        'label' => 'Since Date',
                        'name' => 'since_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88b0fac',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                    array(
                        'key' => 'field_64b04a88b84ca',
                        'label' => 'To Date',
                        'name' => 'to_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88b0fac',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                    array(
                        'key' => 'field_64bebc7f85434',
                        'label' => 'Heading',
                        'name' => 'category_heading',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'h1' => 'Heading H1',
                            'h2' => 'Heading H2',
                            'h3' => 'Heading H3',
                            'span' => 'Heading Span',
                        ),
                        'default_value' => 'h1',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_64b1daa829050',
                        'label' => 'Sports',
                        'name' => 'sports',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'block',
                        'pagination' => 0,
                        'min' => 0,
                        'max' => 0,
                        'collapsed' => '',
                        'button_label' => 'Add Row',
                        'rows_per_page' => 20,
                        'sub_fields' => array(
                            array(
                                'key' => 'field_64b04a88a5bb2',
                                'label' => 'Category',
                                'name' => 'category',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : $rdgb_helpers->getSporstCategoriesOptions(true),
                                'default_value' => 1,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_64b1daa829050',
                            ),
                            array(
                                'key' => 'field_64b04a88a9820',
                                'label' => 'Number of Items',
                                'name' => 'number_of_items',
                                'aria-label' => '',
                                'type' => 'number',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => 3,
                                'min' => 0,
                                'max' => '',
                                'placeholder' => '',
                                'step' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64b1daa829050',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-picks-vs-categories',
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-picks-vs-categories',
                        ),
                    ),
                ),
                '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_picks_vs_categories_block_sdfweewrrwrwr2',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_63d9b9werrwer',
                        'label' => 'URL',
                        'name' => 'picks_vs_categories_api_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '70',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_6werwffwssdfsf',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'picks_vs_categories_interval',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_dfggdgdfdgfdsdsfg',
                        'label' => 'Token',
                        'name' => 'picks_vs_categories_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        '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-picks-vs-categories',
                        ),
                    ),
                ),
                '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_url = get_field('picks_vs_categories_api_url', 'option');
        $api_token = get_field('picks_vs_categories_api_token', 'option');
        $cache_refresh = get_field('picks_vs_categories_interval', 'option');

        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $categories_params = $this->get_sports_categories_url_params($attributes);

        if (!empty($categories_params) ) {
            $api_url .= '?'.$categories_params;
        } else {
            $api_url .= '?';
        }

        if (isset($attributes['date']) && is_array($attributes['date']) && count($attributes['date']) == 2) {
            if (!empty($attributes['date']['start'])) {
                $api_url .= '&principalDate='.$attributes['date']['start'];
            }
            
            if (!empty($attributes['date']['end'])) {
                $api_url .= '&secondaryDate='.$attributes['date']['end'];
            }
        }

        $api_request = $api_url.'&api_token='.$api_token;

        return [
            'items' => null,
            'method' => 'GET',
            'cache_refresh' => $cache_refresh,
            'headers' => ['Accept: application/json'],
            'request' => $api_request
        ];
    }

    public function get_sports_categories_url_params($attributes) {
        if (!isset($attributes['sports']) || empty($attributes['sports']) || !is_array($attributes['sports']) || count($attributes['sports']) == 0) return null;

        $sports = [];
        $qty_per_sport = [];
        $cat_per_sport = [];

        foreach($attributes['sports'] as $sport) {
            $sport_param = null;
            $category_param = 'NULL';

            if (isset($sport['category']) && !empty($sport['category'])) {
                $items_param = (isset($sport['number_of_items']) && !empty($sport['number_of_items'])) ? intval($sport['number_of_items']) : 1;

                if (strpos($sport['category'], '-')) {
                    list($sport_param, $category_param) = explode('-', $sport['category']);
                } else {
                    $sport_param = $sport['category'];
                }

                // DEV-853: Clean hierarchy ID - remove non-numeric characters (e.g., G215 -> 215)
                $sport_param_clean = preg_replace('/\D/', '', $sport_param);
                $category_param_clean = ($category_param !== 'NULL') ? preg_replace('/\D/', '', $category_param) : 'NULL';

                $qty_per_sport[] = $items_param;
                $sports[] = $sport_param_clean;
                $cat_per_sport[] = $category_param_clean;
            }
        }

        if (count($qty_per_sport) == 0 || count($sports) != count($qty_per_sport) || count($cat_per_sport) != count($qty_per_sport)) {
            return null;
        }
        
        $params = [
            'qtyPerSport='.implode(',', $qty_per_sport),
            'hierarchy='.implode(',', $sports),
            'catPerSport='.implode(',', $cat_per_sport),
        ];
        
        return implode('&', $params);
    }

    public function get_date_filter($date_type, $since_date, $to_date) {
        $date = [
            'start' => null,
            'end' => null
        ];

        if ($date_type == API_DATE_TYPE_YESTERDAY) {
            $date['start'] = date('Y-m-d', strtotime("-1 days"));

            return $date;
        }

        if ($date_type == API_DATE_TYPE_NOW) {

            return $date;
        }
        
        if ($date_type == API_DATE_TYPE_TOMORROW) {
            $date['start'] = date('Y-m-d',strtotime("+1 days"));
            
            return $date;
        }

        if ($date_type == API_DATE_TYPE_RANGE) {
            if (!empty($since_date) && !empty($to_date)) {
                $date['start'] = $since_date;
                $date['end'] = $to_date;
            
                return $date;
            }

            if (empty($since_date) && empty($to_date)) {
                return $date;
            }

            if (!empty($since_date) && empty($to_date)) {
                $date['start'] = $since_date;
            
                return $date;
            }

            if (empty($since_date) && !empty($to_date)) {
                $date['start'] = $to_date;
            
                return $date;
            }
        }

        return $date;
    }

    public function getApiParams() {
        return [
            'sports' => 'sports',
            '_to_transform_' => [
                [
                    'key' => 'date',
                    'function' => 'get_date_filter',
                    'params' => ['date_type', 'since_date', 'to_date'],
                    'fields_date' => ['since_date', 'to_date'],
                ]
            ],
            '_to_array_' => [
                'key' => 'sports',
                'fields' => ['category', 'number_of_items'],
            ]
        ];
    }

    public function get_image($url_image, $attributes = []) {
        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $url_image = $rdgb_helpers->getImageSource($url_image, $attributes);

        return $url_image;
    }

    public function get_picks_vs_title_format($title) {
        if (strpos($title, '|') && is_array(explode(' | ', $title)) && count(explode(' | ', $title)) == 2) {
            $title_parts = explode(' | ', $title);
    
            return "<span style='color: var(--color-black); text-shadow: none;'>$title_parts[0] | </span> $title_parts[1]";
        }
        
        return "<span style='color: var(--color-black); text-shadow: none;'>$title</span>";
    }

    public function get_categories_sports($sports) {
        $sports_array = [];

        if (!empty($sports) && is_array($sports) && count($sports) > 0) {
            foreach ($sports as $sport_params) {
                if (isset($sport_params['category']) && !empty($sport_params['category'])) {
                    $tem = explode('-', $sport_params['category']);
                    $sports_array[$tem[0]] = (isset($tem[1])) ? $tem[1] : 'NULL';
                }
            }
        }

        return $sports_array;
    }

    public function getFieldsValidate() {
        return [
            //'id_game' => ['required'],
            //'id_sport' => ['required'],
            'sport_name' => ['required', 'notnull'],
            'game_date' => ['required', 'notnull'],
            //'id_visitor_team' => ['required'],
            //'id_master_visitor_team' => ['required'],
            'visitor_name' => ['required', 'notnull'],
            //'id_home_team' => ['required'],
            //'id_master_home_team' => ['required'],
            'home_name' => ['required', 'notnull'],
            'game_stat' => ['required', 'notnull'],
            'num_picks' => ['required', 'notnull'],
            'game_url' => ['required', 'notnull'],
            'visitor_image' => ['required', 'notnull'],
            'home_image' => ['required', 'notnull'],
            //'visitor_image_type' => ['required'],
            //'home_image_type' => ['required'],
        ];
    }

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

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-picks-vs-categories-pick-bg','slug' => 'color-picks-vs-categories-pick-bg','color' => '#FFFFFF'],
            ['name' => 'color-picks-vs-categories-vs','slug' => 'color-picks-vs-categories-vs','color' => '#FFFFFF'],
            ['name' => 'color-picks-vs-categories-vs-bg','slug' => 'color-picks-vs-categories-vs-bg','color' => '#0160ac'],
            ['name' => 'color-picks-vs-categories-name','slug' => 'color-picks-vs-categories-name','color' => '#FFFFFF'],
            ['name' => 'color-picks-vs-categories-name-bg','slug' => 'color-picks-vs-categories-name-bg','color' => '#0160ac'],
            ['name' => 'color-picks-vs-categories-sport','slug' => 'color-picks-vs-categories-sport','color' => '#111111'],
            ['name' => 'color-picks-vs-categories-date','slug' => 'color-picks-vs-categories-date','color' => '#111111'],
            ['name' => 'color-picks-vs-categories-status','slug' => 'color-picks-vs-categories-status','color' => '#111111'],
            ['name' => 'color-picks-vs-categories-team-name','slug' => 'color-picks-vs-categories-team-name','color' => '#111111'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-header .content .sport',
                'fontWeight' => '700',
                'fontSize' => '0.9rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-header .content .date-time',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-header .content .status',
                'fontWeight' => '700',
                'fontSize' => '0.9rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-body .teams .team .team-name',
                'fontWeight' => '700',
                'fontSize' => '0.8rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-body .teams .team-vs .vs-logo span',
                'fontWeight' => '500',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-body .teams .team-vs .vs-name span',
                'fontWeight' => '600',
                'fontSize' => '0.9rem',
                'textTransform' => 'uppercase',
            ],
        ];
    }
}

$rdg_picks_vs_categories_class = new Rdg_Blocks_Picks_Vs_Categories();
$rdg_picks_vs_categories_class->init();

return $rdg_picks_vs_categories_class;
