<?php

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

class Rdg_Blocks_Trends extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_TRENDS;
    private $block_folder_name = BLOCK_RDG_TRENDS;
    protected $block_title = 'RDG Trends';
    private $block_description = 'The block is a dynamic list of the trends news, it is possible to define the title of the table, the type of the info, sport, leagues, teams and the number of the items';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'trend', '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 Trends';
    protected $config_menu_title = 'Trends';
    protected $config_menu_order = 30;
    protected $is_pre_saved = false;

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

        add_filter('acf/load_field/key=key_rdg_trends_sports', [$this, 'loadSports']);
        add_filter('acf/prepare_field', [$this, 'loadLeagues']);
    }

    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_trends.css'),
                'enqueue_assets' => function() {
                    wp_register_script('rdg_trends_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-trends/assets/js/rdg-trends.js', array('jquery'), '1', true);
                    wp_enqueue_script('rdg_trends_script');
                    wp_localize_script('rdg_trends_script','rdg_trends_var',['ajaxurl' => admin_url('admin-ajax.php')]);
                },
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-trends-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() {
        if (function_exists('acf_add_local_field_group')):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_trends_block_23432rsadfsd',
                'title' => 'Block_rdg_trends',
                'fields' => array(
                    array(
                        'key' => 'key_rdg_trends_title',
                        'label' => 'Title',
                        'name' => 'rdg_trends_title',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'default_value' => '',
                        'maxlength' => '',
                        'allow_in_bindings' => 0,
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_rdg_trends_type',
                        'label' => 'Type',
                        'name' => 'rdg_trends_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => [
                            'over_under_trend' => 'Over/Under',
                            'spread_line_trend' => 'Spread Line',
                        ],
                        'default_value' => 'over_under_trend',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_trends_sports',
                        'label' => 'Sports',
                        'name' => 'rdg_trends_sports',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => '',
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'class' => 'rdg_trends_sports',
                    ),
                    array(
                        'key' => 'key_rdg_trends_leagues',
                        'label' => 'Leagues',
                        'name' => 'rdg_trends_leagues',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => '',
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'class' => 'rdg_trends_leagues',
                    ),
                    array(
                        'key' => 'key_rdg_trends_teams',
                        'label' => 'Teams',
                        'name' => 'rdg_trends_teams',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => '',
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_trends_items',
                        'label' => 'Items',
                        'name' => 'number_of_items',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'default_value' => 10,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-trends',
                        ),
                    ),
                ),
                '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_trends_block_dfwefwef',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'key_trends_api_url',
                        'label' => 'URL',
                        'name' => 'trends_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' => 'key_trends_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'trends_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' => 'key_trends_api_token',
                        'label' => 'Token',
                        'name' => 'trends_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-trends',
                        ),
                    ),
                ),
                '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('trends_api_url', 'option');
        $api_token = get_field('trends_api_token', 'option');
        $cache_refresh = get_field('trends_interval', 'option');

        $sport = (isset($attributes['sport']) && !empty($attributes['sport'])) ? $attributes['sport'] : null;
        $team = (isset($attributes['team']) && !empty($attributes['team'])) ? $attributes['team'] : null;
        $type = (isset($attributes['type']) && !empty($attributes['type'])) ? $attributes['type'] : null;

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

        if (!empty($type)) {
            $api_url .= '&type='.$type;
        }

        if (!empty($sport)) {
            $api_url .= '&sport_id='.$sport;
        }

        if (!empty($team)) {
            $api_url .= '&team_id='.$team;
        }

        if (!empty($items)) {
            $api_url .= '&per_page='.$items;
        }

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

        return $request;
    }

    public function getApiParams() {
        return [
            'league' => 'rdg_trends_leagues',
            'team' => 'rdg_trends_teams',
            'type' => 'rdg_trends_type',
        ];
    }

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

        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $trends = $rdgb_helpers->getApiData($this->block_name, $cache_file, $request);

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

        $data->json = $trends->json;

        return $data;
    }

    public function getFieldsValidate() {
        return [];
    }

    public function getColorsToloadGeneratePress()
    {
        return [
            ['name' => 'color-rdg-trends-title','slug' => 'color-rdg-trends-title','color' => '#ffffff'],
            ['name' => 'color-rdg-trends-title-bg','slug' => 'color-rdg-trends-title-bg','color' => '#338BDC'],
            ['name' => 'color-rdg-trends-border','slug' => 'color-rdg-trends-border','color' => '#d3d3d3'],
        ];
    }

    public function getStylesToloadGeneratePress()
    {
        return [
            [
                'customSelector' => '.rdg-trends .content .trends-box .trends-title',
                'fontWeight' => '700',
                'fontSize' => '1.2rem',
            ],
            [
                'customSelector' => '.rdg-trends .content .trends-box .trends-body .trends .trend .content',
                'fontWeight' => '600',
                'fontSize' => '.9rem',
            ],
        ];
    }

    public function loadSports($field)
    {
        $sports = (function_exists('shMappingSportsDirect')) ? shMappingSportsDirect() : [];

        if (is_array($sports) && count($sports) > 0) {
            $field['choices'] = array_merge(['' => 'Select Option'], $sports);
        }

        return $field;
    }

    public function loadLeagues($field)
    {
        if ($field['key'] == 'key_rdg_trends_leagues') {
            $sport = get_field_object('key_rdg_trends_sports');

            if (is_array($sport) && isset($sport['value']) && !empty($sport['value'])) {
                $leagues = (function_exists('shMappingLeaguesSportsDirect')) ? shMappingLeaguesSportsDirect($sport['value']) : [];
                if (is_array($leagues) && count($leagues) > 0) {
                    $field['choices'] = $leagues;
                }
            }
        } elseif ($field['key'] == 'key_rdg_trends_teams') {
            $league = get_field_object('key_rdg_trends_leagues');

            if (is_array($league) && isset($league['value']) && !empty($league['value'])) {
                $teams = (function_exists('shMappingTeamsLeagueDirect')) ? shMappingTeamsLeagueDirect($league['value']) : [];
                if (is_array($teams) && count($teams) > 0) {
                    $field['choices'] = $teams;
                }
            }
        }

        return $field;
    }
}

add_action('wp_ajax_nopriv_load_leagues_sports','getLeaguesSports');
add_action('wp_ajax_load_leagues_sports','getLeaguesSports');

function getLeaguesSports() {
    $sport = $_POST['sport'];
    $leagues = (function_exists('shMappingLeaguesSportsDirect')) ? shMappingLeaguesSportsDirect($sport) : [];

    if (is_array($leagues) && count($leagues) > 0) {
        echo '<option value="">Select Option</option>';

        foreach ($leagues as $id => $league) {
            echo '<option value="'.$id.'">'.$league.'</option>';
        }
    }

    wp_die();
}

add_action('wp_ajax_nopriv_load_teams_league','getTeamsLeague');
add_action('wp_ajax_load_teams_league','getTeamsLeague');

function getTeamsLeague() {
    $league = $_POST['league'];
    $teams = (function_exists('shMappingTeamsLeagueDirect')) ? shMappingTeamsLeagueDirect($league) : [];

    if (is_array($teams) && count($teams) > 0) {
        echo '<option value="">Select Option</option>';

        foreach ($teams as $id => $team) {
            echo '<option value="'.$id.'">'.$team.'</option>';
        }
    }

    wp_die();
}

$rdg_trends_class = new Rdg_Blocks_Trends();
$rdg_trends_class->init();

return $rdg_trends_class;
