<?php

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

class Rdg_Blocks_Team_Schedules extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_TEAM_SCHEDULES;
    private $block_folder_name = BLOCK_RDG_TEAM_SCHEDULES;
    protected $block_title = 'RDG Team Schedules';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'team', 'schedule'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = true;
    protected $is_config = true;
    protected $config_page_title = 'RDG Team Schedules';
    protected $config_menu_title = 'Team Schedules';
    protected $config_menu_order = 15;

    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_team_schedules.css'),
                '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_team_schedules_block_adadasd',
                'title' => 'RDG Team Schedules',
                'fields' => array(
                    array(
                        'key' => 'field_65859e37e565e',
                        'label' => 'League / Teams',
                        'name' => 'sports_teams',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'choices' => shMappingTeamsDirect(),
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'max' => '',
                        'prepend' => '',
                        'append' => '',
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'allow_custom' => 0,
                        'search_placeholder' => '',
                        'min' => '',
                    ),
                    array(
                        'key' => 'field_6585a05d359c4',
                        'label' => 'League / Seasons',
                        'name' => 'sports_seasons',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'choices' => shMappingSeasonsDirect(),
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'max' => '',
                        'prepend' => '',
                        'append' => '',
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'allow_custom' => 0,
                        'search_placeholder' => '',
                        'min' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-team-schedules',
                        ),
                    ),
                ),
                '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_team_schedules_65843eb54a5c6',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_65843eb5e4ad1',
                        'label' => 'URL',
                        'name' => 'team_schedules_api_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '70',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'default_value' => '',
                        'required_message' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65843eeae4ad2',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'team_schedules_api_frequency',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'default_value' => 1,
                        'required_message' => '',
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65843f39e4ad3',
                        'label' => 'Token',
                        'name' => 'team_schedules_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_save_meta' => 0,
                        'default_value' => '',
                        'required_message' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-team-schedules',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function get_api_attributes($items = null, $attributes = []) {
        $api_url = get_field('team_schedules_api_url', 'option');
        $api_token = get_field('team_schedules_api_token', 'option');
        $cache_refresh = get_field('team_schedules_api_frequency', 'option');
        $items = (!empty($items)) ? intval($items) : 10;

        $sport = $attributes['filter']['sport'];
        $team = $sport.'/team:'.$attributes['filter']['team'];
        $season = $sport.'/season:'.$attributes['filter']['season'];

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

        if (isset($attributes['filter']['season']) && !empty($attributes['filter']['season'])) {
            $api_url .= '&season_id='.$season;
        }

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

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

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

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

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

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

        $data->json = $sports_picks->json;

        return $data;
    }

    #TODO: Es obligatorio implementar?
    public function get_fields_validate() {
        return [
            //'id_game' => ['required'],
            //'id_sport' => ['required'],
            'sport_external' => ['required', 'notnull'],
            'game_date' => ['required', 'notnull'],
            //'id_visitor_team' => ['required'],
            //'id_master_visitor_team' => ['required'],
            'visitor_name' => ['required', 'notnull'],
            //'id_home_team' => ['required'],
            //'id_master_home_team' => ['required'],
            'home_name' => ['required', 'notnull'],
            'game_stat' => ['required', 'notnull'],
            'num_picks' => ['required', 'notnull'],
            'game_url' => ['required', 'notnull'],
            'visitor_image' => ['required', 'notnull'],
            'home_image' => ['required', 'notnull'],
            //'visitor_image_type' => ['required'],
            //'home_image_type' => ['required'],
        ];
    }

    public function get_team_id($filter) {
        $team = $filter['sport'].'/team:';
        $team .= $filter['team'];
        
        return $team;
    }

    public function get_team_name($team_id) {
        $teams_names = shMappingTeamsDirect();

        foreach ($teams_names as $sport_name => $teams) {
            if (isset($teams[$team_id])) {
                return $teams[$team_id];
            } else {
                continue;
            }
        }
        
        return '';
    }
}

$rdg_team_schedules_class = new Rdg_Blocks_Team_Schedules();
$rdg_team_schedules_class->init();

return $rdg_team_schedules_class;
