<?php

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

$teamId = get_field('team');
$seasonId = get_field('season');

$schedules = ($teamId && $seasonId) ? $teamSchedulesBlockDataLoader->getSchedules($teamId, $seasonId) : [];

?>

<div class="rdg-blocks">
    <div class="rdg-team-schedules">
        <?php if (count($schedules)): ?>
            <table>
                <?php foreach ($schedules as $schedule): ?>
                    <tr>
                        <td><?php echo $schedule['week']; ?></td>
                        <td><?php echo $schedule['date']; ?></td>
                        <td><?php echo $schedule['opponent']; ?></td>
                        <td><?php echo $schedule['result']; ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>

        <?php elseif ($teamId && $seasonId): ?>
            <p>No schedules found.</p>
        <?php else: ?>
            <p>Please complete the form.</p>
        <?php endif; ?>
    </div>
</div>

<?php
if ('active' === get_field('rdg_blocks_debug_cache', 'options') || 'active' === get_field('rdg_blocks_debug_request', 'options')) {
    if (is_user_logged_in() && current_user_can('administrator')) {
        if ($teamId && $seasonId) {
            $log = json_encode($teamSchedulesBlockDataLoader->getLastSchedulesLog(), JSON_PRETTY_PRINT);
        } else {
            $log = 'The block requires more data, go to edit mode and complete the form.';
        }

        echo "<!--\n";
        echo "==================================================================================================================\n";
        echo "--------------------------------------------Debug Team schedules block--------------------------------------------\n";
        echo "==================================================================================================================\n";
        echo  $log. "\n";
        echo "==================================================================================================================\n";
        echo "-->";
    }
}
?>
