<?php

if (!defined('ABSPATH')) exit;

require __DIR__ . '/BlockDataLoader.php';

class Rdg_Blocks_Team_Schedules extends Rdg_Blocks_Base
{
    protected $block_name = BLOCK_RDG_TEAM_SCHEDULES;
    private $block_folder_name = 'rdg-team-schedules';
    private $block_title = 'RDG Team Schedules';
    private $block_description = 'The block is a form where is possible to define the sport, league, team and season, with this data will be shown on site a table with the schedule of the selected team and its other specifications';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'team', 'schedules'];
    private $block_mode = 'auto';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_styles_load = true;

    private \Rdgcorp\Blocks\TeamSchedules\BlockDataLoader $blockDataLoader;

    public function __construct()
    {
        $this->blockDataLoader = new \Rdgcorp\Blocks\TeamSchedules\BlockDataLoader();
    }

    public function init()
    {
        $this->register_block();
        $this->register_fields();
        $this->register_option_fields();
        $this->register_option_save();
        $this->register_js();
        $this->register_selects();
    }

    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'),
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-team-schedules-template-preview.jpg",
                        ),
                    ),
                ),
            ]);
        }
    }

    private function register_fields()
    {
        if (function_exists('acf_add_local_field_group')) {
            $json = file_get_contents(__DIR__ . '/fields/block_fields.json');

            acf_add_local_field_group(json_decode($json, true));
        }
    }

    private function register_option_fields()
    {
        if (function_exists('acf_add_local_field_group')) {
            $json = file_get_contents(__DIR__ . '/fields/cache_maintenance_fields.json');

            acf_add_local_field_group(json_decode($json, true));
        }
    }

    private function register_option_save()
    {
        $blockDataLoader = $this->blockDataLoader;

        add_action('acf/options_page/save', function ($postId, $menuSlug) use ($blockDataLoader) {
            if ('acf-options-cache-maintenance' !== $menuSlug) {
                return;
            }

            if ((int)get_field('delete_team_schedules_cache', $postId)) {
                $blockDataLoader->deleteAllCacheFiles();

                update_field('delete_team_schedules_cache', 0, $postId);
            }

        }, 10, 2);
    }

    private function register_js()
    {
        add_action('acf/input/admin_footer', function () {
            echo '<script>' . file_get_contents(__DIR__ . '/assets/acf-extra-script.js') . '</script>';
        });
    }

    private function sortSeasons(array $seasons): array
    {
        uasort($seasons, function ($a, $b) {
            preg_match('/(\d{4})/', $a, $yearA);
            preg_match('/(\d{4})/', $b, $yearB);
            $yearA = isset($yearA[1]) ? (int)$yearA[1] : 0;
            $yearB = isset($yearB[1]) ? (int)$yearB[1] : 0;
            return $yearB - $yearA;
        });
        
        return $seasons;
    }

    private function getSortedSeasonKeys(array $seasons): array
    {
        $sortedSeasons = $this->sortSeasons($seasons);
        return array_keys($sortedSeasons);
    }

    private function register_selects()
    {
        $blockDataLoader = $this->blockDataLoader;

        add_filter('acf/load_field/key=field_65c24e23461a3', function ($field) use ($blockDataLoader) {
            if (defined('DOING_AJAX') && DOING_AJAX) {
                $field['choices'] = $blockDataLoader->getSports();
            }

            return $field;
        }, 10, 1);

        add_filter('acf/load_field/key=field_65c24f0a461a4', function ($field) use ($blockDataLoader) {
            if (defined('DOING_AJAX') && DOING_AJAX && (isset($_POST['customData']) || get_field('sport'))) {
                $sportId = isset($_POST['customData']) ? $_POST['customData'] : get_field('sport');

                $field['choices'] = $blockDataLoader->getLeagues($sportId);
            }

            return $field;
        }, 10, 1);

        add_filter('acf/load_field/key=field_65c24f21461a5', function ($field) use ($blockDataLoader) {
            if (defined('DOING_AJAX') && DOING_AJAX && (isset($_POST['customData']) || get_field('league'))) {
                $leagueId = isset($_POST['customData']) ? $_POST['customData'] : get_field('league');

                $field['choices'] = $blockDataLoader->getTeams($leagueId);
            }

            return $field;
        }, 10, 1);

        add_filter('acf/load_field/key=field_65c24f34461a6', function ($field) use ($blockDataLoader) {
            if (defined('DOING_AJAX') && DOING_AJAX && (isset($_POST['customData']) || get_field('league'))) {
                $leagueId = isset($_POST['customData']) ? $_POST['customData'] : get_field('league');
                $seasons = $blockDataLoader->getSeasons($leagueId);
        
                if (!empty($seasons)) {
                    $sortedSeasons = $this->sortSeasons($seasons);
                    $field['choices'] = [
                        'latest' => 'Latest'
                    ] + $sortedSeasons;
                } else {
                    $field['choices'] = [];
                }
            }
        
            return $field;
        }, 10, 1);

    }

    public function get_data()
    {
        $data = [
            'schedulesByType' => null,
            'parameters' => [
                'teamId' => null,
                'seasonId' => null,
            ],
            'error' => null,
            'log' => null,
        ];

        try {
            $data['parameters']['teamId'] = $teamId = get_field('team');
            $data['parameters']['seasonId'] = $seasonId = get_field('season');
            $leagueId = get_field('league');

            if ($teamId) {
                if ($seasonId === 'latest' && $leagueId) {
                    $seasons = $this->blockDataLoader->getSeasons($leagueId);
                    $seasonIds = $this->getSortedSeasonKeys($seasons);

                    foreach ($seasonIds as $clave=>$currentSeasonId) {
                        $data['log'] = 'http://masterfeed.shnadmin.com/feed/sportdirect/schedules?key=' . 
                            $this->blockDataLoader->getApiKey() . 
                            '&team_id=' . $teamId . 
                            '&season_id=' . $currentSeasonId;

                        $schedules = $this->blockDataLoader->getSchedules($teamId, $currentSeasonId);
                        
                        if (!empty($schedules)) {
                            $data['schedulesByType'] = $schedules;
                            $data['parameters']['seasonId'] = $currentSeasonId;
                            break;
                        }
                    }

                    if (empty($data['schedulesByType'])) {
                        $data['log'] .= ' - No schedules found for any season.';
                    }
                } else {
                    if ($seasonId) {
                        $data['log'] = 'http://masterfeed.shnadmin.com/feed/sportdirect/schedules?key=' . 
                            $this->blockDataLoader->getApiKey() . 
                            '&team_id=' . $teamId . 
                            '&season_id=' . $seasonId;
                        $data['schedulesByType'] = $this->blockDataLoader->getSchedules($teamId, $seasonId);
                    } else {
                        $data['log'] = 'The block requires a season, go to edit mode and complete the form.';
                    }
                }
            } else {
                $data['log'] = 'The block requires a team, go to edit mode and complete the form.';
            }
        } catch (\Throwable $exception) {
            $data['error'] = $exception->getMessage();
            $data['log'] .= ' - Error: ' . $data['error'];
        }

        return $data;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-rdg-team-schedules-title','slug' => 'color-rdg-team-schedules-title','color' => '#031C3F'],
            ['name' => 'color-rdg-team-schedules-title-border','slug' => 'color-rdg-team-schedules-title-border','color' => '#efeeec'],
            ['name' => 'color-rdg-team-schedules-border','slug' => 'color-rdg-team-schedules-border','color' => '#ffffff'],
            ['name' => 'color-rdg-team-schedules-header','slug' => 'color-rdg-team-schedules-header','color' => '#ffffff'],
            ['name' => 'color-rdg-team-schedules-header-bg','slug' => 'color-rdg-team-schedules-header-bg','color' => '#031C3F'],
            ['name' => 'color-rdg-team-schedules-td','slug' => 'color-rdg-team-schedules-td','color' => '#111111'],
            ['name' => 'color-rdg-team-schedules-td-bg','slug' => 'color-rdg-team-schedules-td-bg','color' => '#efeeec'],
            ['name' => 'color-rdg-team-schedules-td-first','slug' => 'color-rdg-team-schedules-td-first','color' => '#ffffff'],
            ['name' => 'color-rdg-team-schedules-td-first-bg','slug' => 'color-rdg-team-schedules-td-first-bg','color' => '#7f8b90'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-team-schedules .title',
                'fontWeight' => '600',
                'fontSize' => '1.2rem',
            ],
            [
                'customSelector' => '.rdg-team-schedules table tbody tr td.type',
                'fontWeight' => '600',
                'fontSize' => '1rem',
            ],
            [
                'customSelector' => '.rdg-team-schedules table tbody tr td.data',
                'fontWeight' => '500',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-team-schedules table thead tr th',
                'fontWeight' => '700',
                'fontSize' => '1rem',
                'textTransform' => 'uppercase',
            ],
        ];
    }
}

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

return $rdg_team_schedules;
