<?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';
    private $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 $config_page_title = 'RDG Leader Board';
    protected $config_menu_title = 'Leader Board';
    protected $config_menu_order = 4;

    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')]);
                },
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
            ]);
        }
    }

    public function register_fields() {
        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' => $this->get_leader_board_titles(true),
                        'default_value' => '',
                        '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',
                                    'unactive' => 'Default',
                                ),
                                'default_value' => 'unactive',
                                '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' => $this->get_leader_board_titles(true),
                                'default_value' => '',
                                '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' => 'number_of_items',
                        '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' => '',
                    ),
                ),
                '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_63f377df9cf93',
                        'label' => 'Leaders Titles',
                        'name' => 'leader_board_titles',
                        '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_63f377dfa88a8',
                                'label' => 'Title Slug',
                                'name' => 'leader_board_title_slug',
                                '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_63f377df9cf93',
                            ),
                            array(
                                'key' => 'field_63f377dfac1eb',
                                'label' => 'Title Value',
                                'name' => 'leader_board_title_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_63f377df9cf93',
                            ),
                            array(
                                'key' => 'field_63f377dfafe50',
                                'label' => 'Sub Titles',
                                'name' => 'sub_titles',
                                'aria-label' => '',
                                'type' => 'repeater',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'layout' => 'table',
                                'pagination' => 0,
                                'min' => 0,
                                'max' => 0,
                                'collapsed' => '',
                                'button_label' => 'Add Row',
                                'rows_per_page' => 20,
                                'sub_fields' => array(
                                    array(
                                        'key' => 'field_63f377dfbb6af',
                                        'label' => 'Sub Title Slug',
                                        'name' => 'sub_title_slug',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 0,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_63f377dfafe50',
                                    ),
                                    array(
                                        'key' => 'field_63f377dfbf399',
                                        'label' => 'Sub Title Value',
                                        'name' => 'sub_title_value',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 0,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_63f377dfafe50',
                                    ),
                                ),
                                'parent_repeater' => 'field_63f377df9cf93',
                            ),
                        ),
                    ),
                    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_titles($is_sub_title = false) {
        $sport_titles = [];
        $titles = get_field('leader_board_titles', 'option');

        if (is_array($titles) && count($titles) > 0) {
            foreach ($titles as $title) {
                if (is_array($title['sub_titles']) && count($title['sub_titles']) > 0 && $is_sub_title) {
                    $sub_titles = [];
                    foreach ($title['sub_titles'] as $sub_title) {
                        $sub_titles[$title['leader_board_title_slug'].'-'.$sub_title['sub_title_slug']] = $sub_title['sub_title_value'];
                    }
                } else {
                    $sub_titles = $title['leader_board_title_value'];
                }

                $sport_titles[$title['leader_board_title_value']] = $sub_titles;
            }
        }

        return $sport_titles;
    }

    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 get_api_attributes($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 : 365;

        $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 .= '/'.$category_primary;
        $api_url .= '/'.strtoupper($sub_category);
        $api_url .= '/'.$items;

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

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

    public function get_api_params() {
        return [
            'category' => 'category'
        ];
    }

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

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

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

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

        return $data;
    }

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

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

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

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

        return $data;
    }
}

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'];
    $id_sub_category = $_POST['id_sub_category'];

    $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;
        $block_name = BLOCK_RDG_LEADER_BOARD;
        $block_leader_board = $rdgb->settings->get_block($block_name);
        $api_attributes = $block_leader_board->get_api_attributes($items, ['category' => $id_sub_category]);
        $response = $block_leader_board->get_resources_ajax($api_attributes);

        if (empty($response->message)) {
            $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;
