<?php

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

class Rdg_Blocks_Leader_Board extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_LEADER_BOARD;
    private $block_folder_name = 'rdg-leader-board';
    protected $block_title = 'RDG Leader Board';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'leader', 'board'];
    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 Leader Board';
    protected $config_menu_title = 'Leader Board';

    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_leader_board.css'),
                'enqueue_assets' => function() {
                    wp_register_script('rdg_leader_board_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-leader-board/assets/js/rdg-leader-board.js', array('jquery'), '1', true);
                    wp_enqueue_script('rdg_leader_board_script');
                    wp_localize_script('rdg_leader_board_script','rdg_leader_board_var',['ajaxurl' => admin_url('admin-ajax.php')]);

                    wp_register_script('rdg_leader_board_sortable', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-leader-board/assets/js/sortable.min.js', [], '1', true);
                    wp_enqueue_script('rdg_leader_board_sortable');
                },
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
            ]);
        }
    }

    public function register_fields() {
        $rdg_helpers = new Rdg_Blocks_Helpers();

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_leader_board_block_sdf4334r',
                'title' => 'Block_rdg_leader_board',
                'fields' => array(
                    array(
                        'key' => 'field_63efd2d309f19',
                        'label' => 'Category',
                        'name' => 'category',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => $rdg_helpers->getSporstCategoriesOptions(true),
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_63f50249d675a',
                        'label' => 'Menu',
                        'name' => 'menu',
                        '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_63f506a553aeb',
                                'label' => 'Status Menu',
                                'name' => 'status_menu',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => array(
                                    'active' => 'Active',
                                    'inactive' => 'Default',
                                ),
                                'default_value' => 'inactive',
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_63f50249d675a',
                            ),
                            array(
                                'key' => 'field_63f50262d675b',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63f50249d675a',
                            ),
                            array(
                                'key' => 'field_63f610d25c285',
                                'label' => 'Category',
                                'name' => 'category',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => $rdg_helpers->getSporstCategoriesOptions(true),
                                'default_value' => 1,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_63f50249d675a',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_63efd2d30dba5',
                        'label' => 'Date Range',
                        'name' => 'date_range',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => $this->get_leader_board_date_range(),
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_64e4cc6b6091f',
                        'label' => 'Items per page',
                        'name' => 'items_per_page',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 10,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-leader-board',
                        ),
                    ),
                ),
                '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_leader_board_block_sdfw34fs2332',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_63f377df91eea',
                        'label' => 'URL',
                        'name' => 'leader_board_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_63f377df958fa',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'leader_board_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_63f377df9946e',
                        'label' => 'Token',
                        'name' => 'leader_board_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_63f8bf9516731',
                        'label' => 'Date Range',
                        'name' => 'leader_board_date_range',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        '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_63f8bfcf16732',
                                'label' => 'Value',
                                'name' => 'value',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63f8bf9516731',
                            ),
                            array(
                                'key' => 'field_63f8bfe416733',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63f8bf9516731',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-leader-board',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function get_leader_board_date_range() {
        $date_range = [];
        $ranges = get_field('leader_board_date_range', 'option');

        if (is_array($ranges) && count($ranges) > 0) {
            foreach ($ranges as $range) {
                $date_range[$range['value']] = $range['title'];
            }
        }

        return $date_range;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('leader_board_api_url', 'option');
        $api_token = get_field('leader_board_api_token', 'option');
        $cache_refresh = get_field('leader_board_interval', 'option');
        $items = (!empty($items)) ? $items : 10;
        $duration = (isset($attributes['duration']) && !empty($attributes['duration'])) ? $attributes['duration'] : 365;
        $page = (isset($attributes['page']) && !empty($attributes['page'])) ? $attributes['page'] : 1;

        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;

        if (isset($attributes['category']) && strpos($attributes['category'], '-')) {
            list($category_primary, $sub_category) = explode('-', $attributes['category']);
        } else {
            $sub_category = null;

            if (isset($attributes['category']) && !empty($attributes['category'])) {
                $category_primary = $attributes['category'];
            } else {
                $category_primary = 7;
            }
        }

        $api_url .= '?perPage='.$items;
        $api_url .= '&pageSelected='.$page;
        $api_url .= '&duration='.$duration;
        $api_url .= '&sport='.$category_primary;

        if (!empty($sub_category)) {
            $api_url .= '&category='.$sub_category;
        }
        
        $api_request = $api_url.'&api_token='.$api_token;

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

        return $request;
    }

    public function getApiParams() {
        return [
            'category' => 'category',
            'duration' => 'duration',
            'page' => 'page',
        ];
    }

    public function getResources($request, $cache_file) {
        $data = new StdClass();
        $data->json = '';
        $data->message = '';

        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $leader_board = $rdgb_helpers->getApiDataAjax($this->block_name, $request);

        if (!empty($leader_board->message)) {
            $data->message = $leader_board->message;
        
            return $data;
        }

        $data->json = $leader_board->json;

        return $data;
    }

    public function getResourcesAjax($request) {
        $data = new StdClass();
        $data->json = '';
        $data->message = '';

        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $leader_board = $rdgb_helpers->getApiDataAjax($this->block_name, $request);

        if (!empty($leader_board->message)) {
            $data->message = $leader_board->message;
        
            return $data;
        }

        $data->json = $leader_board->json;

        return $data;
    }

    public function getFieldsValidate() {
        return [
            'rank' => ['required', 'notnull'],
            //'id_handicapper' => ['required', 'notnull'],
            'name' => ['required', 'notnull'],
            //'slug' => ['required', 'notnull'],
            'win' => ['required'],
            'loss' => ['required'],
            'push' => ['required'],
            'risk_amount' => ['required'],
            'win_amount' => ['required'],
            //'lost_amount' => ['required', 'notnull'],
            'win_percentaje' => ['required'],
            'net' => ['required'],
            'total_bets' => ['required'],
            //'image_url' => ['required', 'notnull'],
            //'handicapper_detail_url' => ['required', 'notnull'],
        ];
    }

    public function getColorsToloadGeneratePress()
    {
        return [
            [
                'name' => 'color-rdg-leader-board-table-menu-i',
                'slug' => 'color-rdg-leader-board-table-menu-i',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-table-menu-active',
                'slug' => 'color-rdg-leader-board-table-menu-active',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-table-menu-inactive',
                'slug' => 'color-rdg-leader-board-table-menu-inactive',
                'color' => '#111111'
            ],
            [
                'name' => 'color-rdg-leader-board-table-filter',
                'slug' => 'color-rdg-leader-board-table-filter',
                'color' => '#ffffff'
            ],
            [
                'name' => 'color-rdg-leader-board-table-filter-bg',
                'slug' => 'color-rdg-leader-board-table-filter-bg',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-list-item-table-wrapper-border',
                'slug' => 'color-rdg-leader-board-list-item-table-wrapper-border',
                'color' => '#cadae5'
            ],
            [
                'name' => 'color-rdg-leader-board-list-item-table-wrapper-scrollbar',
                'slug' => 'color-rdg-leader-board-list-item-table-wrapper-scrollbar',
                'color' => '#dedede'
            ],
            [
                'name' => 'color-rdg-leader-board-list-item-table-wrapper-static-column',
                'slug' => 'color-rdg-leader-board-list-item-table-wrapper-static-column',
                'color' => '#262626'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-before',
                'slug' => 'color-rdg-leader-board-sortable-th-before',
                'color' => 'transparent'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-after',
                'slug' => 'color-rdg-leader-board-sortable-th-after',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-hover-after',
                'slug' => 'color-rdg-leader-board-sortable-th-hover-after',
                'color' => '#03467d'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-dir-d-after',
                'slug' => 'color-rdg-leader-board-sortable-dir-d-after',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-dir-u-after',
                'slug' => 'color-rdg-leader-board-sortable-dir-u-after',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-indicador-left-hover-before',
                'slug' => 'color-rdg-leader-board-sortable-indicador-left-hover-before',
                'color' => 'inherit'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-indicador-left-dir-d-before',
                'slug' => 'color-rdg-leader-board-sortable-indicador-left-dir-d-before',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-indicador-left-dir-u-before',
                'slug' => 'color-rdg-leader-board-sortable-indicador-left-dir-u-before',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th',
                'slug' => 'color-rdg-leader-board-sortable-th',
                'color' => '#111111'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-bg',
                'slug' => 'color-rdg-leader-board-sortable-th-bg',
                'color' => '#f8f8f8'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-td-bg',
                'slug' => 'color-rdg-leader-board-sortable-td-bg',
                'color' => '#ffffff'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-td-name',
                'slug' => 'color-rdg-leader-board-sortable-td-name',
                'color' => '#111111'
            ],
        ];
    }

    public function getStylesToloadGeneratePress()
    {
        return [
            [
                'customSelector' => '.rdg-leader-board .table .table-menu .menu li',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .table .table-menu .menu li i',
                'fontSize' => '0.8rem',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .table .table-filter .filter .filter-option',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .table .list',
                'fontSize' => '1rem',
                'fontSizeTablet' => '.875rem',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .sortable th::after, .rdg-leader-board .sortable th::before',
                'fontSize' => '1.2rem',
            ],
            [
                'customSelector' => '.rdg-leader-board .sortable th',
                'fontWeight' => '600',
                'textTransform' => 'capitalize',
            ],
        ];
    }
}

add_action('wp_ajax_nopriv_load_leader_board','get_leader_board_data');
add_action('wp_ajax_load_leader_board','get_leader_board_data');

function get_leader_board_data() {
    $items = $_POST['items'];
    $duration = $_POST['duration'];
    $id_sub_category = $_POST['id_sub_category'];
    $page = $_POST['page'];

    $message = null;
    $api_url = get_field('leader_board_api_url', 'option');
    $api_token = get_field('leader_board_api_token', 'option');

    if (!empty($api_url) && !empty($api_token)) {
        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

        $block_name = BLOCK_RDG_LEADER_BOARD;
        $block_leader_board = $rdgb->settings->getBlock($block_name);
        $api_attributes = $block_leader_board->getApiAttributes($items, ['category' => $id_sub_category, 'duration' => $duration, 'page' => $page]);
        $response = $block_leader_board->getResourcesAjax($api_attributes);

        if (empty($response->message)) {
            $page = (isset($response->json['page_selected'])) ? $response->json['page_selected'] : 1;
            unset($response->json['page_selected']);
            $total_pages = (isset($response->json['total_pages'])) ? $response->json['total_pages'] : 1;
            unset($response->json['total_pages']);

            $leaders = $response->json;
        } else {
            $leaders = null;
            $message = $response->message;
        }
    } else {
        $message = 'Configure API connection correctly.';
    }

    if (!empty($message)) {
        $message = 'Leaders with these characteristics were not found.';
        require 'partials/message.php';
        wp_die();
    }

    require 'partials/api.php';

    wp_die();
}

$rdg_leader_board_class = new Rdg_Blocks_Leader_Board();
$rdg_leader_board_class->init();

return $rdg_leader_board_class;
