<?php

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

class Rdg_Blocks_Picks_Vs_Multi extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_PICKS_VS_MULTI;
    private $block_folder_name = 'rdg-picks-vs-multi';
    protected $block_title = 'RDG Picks Vs Multi';
    private $block_description = 'This block allow to create a 3 columns table with teams pick but with multi categories';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'sports', 'picks', '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 Multi';
    protected $config_menu_title = 'Picks Vs Multi';
    protected $interval_field = 'picks_vs_multi_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_multi.css'),
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-picks-vs-multi-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() {
        $sports = (function_exists('shMappingLeaderboardCategories')) ? shMappingLeaderboardCategories() : [];

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_picks_vs_multi_block',
                'title' => 'Block_rdg_picks_vs_multi',
                'fields' => array(
                    array(
                        'key' => 'rdg_picks_vs_multi_source',
                        'label' => 'Source',
                        'name' => 'source',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'manual' => 'Manual',
                            'api' => 'API',
                        ),
                        'default_value' => 'manual',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'save_other_choice' => 0,
                        'layout' => 'horizontal',
                    ),                   
                    array(
                        'key' => 'field_63cc527c9d04e',
                        'label' => 'Picks',
                        'name' => 'picks',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'rdg_picks_vs_multi_source',
                                    'operator' => '==',
                                    'value' => 'manual',
                                ),
                            ),
                        ),
                        '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_63cc527cbe269',
                                'label' => 'Category',
                                'name' => 'category',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_63cc527cc1bba',
                                'label' => 'Time',
                                'name' => 'time',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_63cc527cc584e',
                                'label' => 'Status',
                                'name' => 'status',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_63cc527cccd29',
                                'label' => 'Teams',
                                'name' => 'teams',
                                'aria-label' => '',
                                'type' => 'repeater',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'layout' => 'block',
                                'pagination' => 0,
                                'min' => 0,
                                'max' => 2,
                                'collapsed' => '',
                                'button_label' => 'Add Row',
                                'rows_per_page' => 20,
                                'sub_fields' => array(
                                    array(
                                        'key' => 'field_63cc527ce34ba',
                                        'label' => 'Logo',
                                        'name' => 'logo',
                                        'aria-label' => '',
                                        'type' => 'image',
                                        'instructions' => '',
                                        'required' => 1,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'return_format' => 'array',
                                        'library' => 'all',
                                        'min_width' => '',
                                        'min_height' => '',
                                        'min_size' => '',
                                        'max_width' => '',
                                        'max_height' => '',
                                        'max_size' => '',
                                        'mime_types' => '',
                                        'preview_size' => 'medium',
                                        'parent_repeater' => 'field_63cc527cccd29',
                                    ),
                                    array(
                                        'key' => 'field_63cc527ce6f33',
                                        'label' => 'Name',
                                        'name' => 'name',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 1,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_63cc527cccd29',
                                    ),
                                ),
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_67f7d58aff741',
                                'label' => 'Picks Availables',
                                'name' => 'picks_availables',
                                'aria-label' => '',
                                'type' => 'link',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'allow_in_bindings' => 0,
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'rdg_picks_vs_multi_picks_sports',
                        'label' => 'Sports',
                        'name' => 'sports',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'rdg_picks_vs_multi_source',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        '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_category',
                                'label' => 'Category',
                                'name' => 'category',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => [0 => 'Choose an option'] + $sports,
                                'default_value' => 1,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'rdg_picks_vs_multi_picks_sports',
                            ),
                            array(
                                'key' => 'field_quantity',
                                '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' => 'rdg_picks_vs_multi_picks_sports',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_63dbbff733345',
                        'label' => 'Filter Date',
                        'name' => 'filter_date',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'rdg_picks_vs_multi_source',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        '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_63e6b06bc7010',
                        'label' => 'Date Type',
                        'name' => 'date_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_63dbbff733345',
                                    '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_63e6af4c50608',
                        'label' => 'Since Date',
                        'name' => 'since_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_63e6b06bc7010',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                    array(
                        'key' => 'field_63e6afb550609',
                        'label' => 'To Date',
                        'name' => 'to_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_63e6b06bc7010',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-picks-vs-multi',
                        ),
                    ),
                ),
                '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_multi_block',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_63d9b555d0be',
                        'label' => 'URL',
                        'name' => 'picks_vs_multi_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_63d9b987c0adf',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'picks_vs_multi_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_63d9b987c4506',
                        'label' => 'Token',
                        'name' => 'picks_vs_multi_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-multi',
                        ),
                    ),
                ),
                '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_multi_api_url', 'option');
        $api_token = get_field('picks_vs_multi_api_token', 'option');
        $cache_refresh = get_field('picks_vs_multi_interval', 'option');
        $items = (!empty($items)) ? intval($items) : 10;
        
        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $categories_params = $this->getSportsCategoriesParams($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' => $items,
            'method' => 'GET',
            'cache_refresh' => $cache_refresh,
            'headers' => ['Accept: application/json'],
            'request' => $api_request,
        ];
    }

    public function getSportsCategoriesParams($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'];
                }

                $qty_per_sport[] = $items_param;
                $sports[] = $sport_param;
                $cat_per_sport[] = $category_param;
            }
        }

        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),
            'sports='.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 getFieldsValidate() {
        return [
            'sport_external' => ['required', 'notnull'],
            'game_date' => ['required', 'notnull'],
            'visitor_name' => ['required', 'notnull'],
            'home_name' => ['required', 'notnull'],
            'game_stat' => ['required', 'notnull'],
            'num_picks' => ['required', 'notnull'],
            'game_url' => ['required', 'notnull'],
            'visitor_image' => ['required', 'notnull'],
            'home_image' => ['required', 'notnull'],
        ];
    }
    
    public function getPreSavedData($data, $attributes = [])
    {
        return $data;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-rdg-pvm-bg','slug' => 'color-rdg-pvm-bg','color' => '#FFFFFF'],
            ['name' => 'color-rdg-pvm-vs-bg','slug' => 'color-rdg-pvm-vs-bg','color' => '#0160ac'],
            ['name' => 'color-rdg-pvm-vs-p','slug' => 'color-rdg-pvm-vs-p','color' => '#FFFFFF'],
            ['name' => 'color-rdg-pvm-btn-bg','slug' => 'color-rdg-pvm-btn-bg','color' => '#0160ac'],
            ['name' => 'color-rdg-pvm-btn-p','slug' => 'color-rdg-pvm-btn-p','color' => '#FFFFFF'],
            ['name' => 'color-rdg-pvm-btn-hover','slug' => 'color-rdg-pvm-btn-hover','color' => '#014f8c'],
            
        ]; 
    }

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

$rdg_picks_vs_multi_class = new Rdg_Blocks_Picks_Vs_Multi();
$rdg_picks_vs_multi_class->init();

return $rdg_picks_vs_multi_class;
