<?php

require __DIR__ . '/BlockDataLoader.php';

if (!isset($teamSchedulesBlockDataLoader)) {
    $teamSchedulesBlockDataLoader = new \Rdgcorp\Blocks\TeamSchedules\BlockDataLoader();
}

add_action('acf/init', function () {
    if (function_exists('acf_register_block_type')) {
        $manifest = file_get_contents(__DIR__ . '/../../dist/manifest.json');
        $assets = json_decode($manifest, true);

        acf_register_block_type([
            'name' => 'rdg-team-schedules',
            'title' => __('RDG Team Schedules'),
            'description' => __('List of team schedules'),
            'category' => RDGBLOCKS_NAME_SLUG,
            'icon' => 'admin-links',
            'keywords' => ['rdg', 'custom', 'team', 'schedules'],
            'render_template' => __DIR__ . '/template.php',
            'enqueue_style' => plugin_dir_url(__DIR__ . '/../../../') . 'dist/' . $assets['rdg_team_schedules.css'],
            'mode' => 'auto',
        ]);
    }
}, 20);

add_action('acf/init', function () {
    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));
    }
}, 20);

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

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

    return $field;
}, 10, 1);

add_filter('acf/load_field/key=field_65c24f0a461a4', function ($field) use ($teamSchedulesBlockDataLoader) {
    if (defined('DOING_AJAX') && DOING_AJAX && ($_POST['customData'] || get_field('sport'))) {
        $field['choices'] = $teamSchedulesBlockDataLoader->getLeagues($_POST['customData'] ?? get_field('sport'));
    }

    return $field;
}, 10, 1);

add_filter('acf/load_field/key=field_65c24f21461a5', function ($field) use ($teamSchedulesBlockDataLoader) {
    if (defined('DOING_AJAX') && DOING_AJAX && ($_POST['customData'] || get_field('league'))) {
        $field['choices'] = $teamSchedulesBlockDataLoader->getTeams($_POST['customData'] ?? get_field('league'));
    }

    return $field;
}, 10, 1);

add_filter('acf/load_field/key=field_65c24f34461a6', function ($field) use ($teamSchedulesBlockDataLoader) {
    if (defined('DOING_AJAX') && DOING_AJAX && ($_POST['customData'] || get_field('league'))) {
        $field['choices'] = $teamSchedulesBlockDataLoader->getSeasons($_POST['customData'] ?? get_field('league'));
    }

    return $field;
}, 10, 1);
