<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

fixture_module_boot();

if (!can_generate_fixtures()) {
    abort_request(403, 'Access denied', 'You do not have permission to generate fixtures.');
}

$pageTitle = 'Generate Fixtures';
$formErrors = flash('errors') ?? [];
$competitionOptions = fixture_competition_options(true);
$weekdayOptions = [
    '1' => 'Monday',
    '2' => 'Tuesday',
    '3' => 'Wednesday',
    '4' => 'Thursday',
    '5' => 'Friday',
    '6' => 'Saturday',
    '7' => 'Sunday',
];
$fieldValue = static function (string $field, mixed $default = '') {
    if (isset($_SESSION['_old']) && array_key_exists($field, $_SESSION['_old'])) {
        return old($field, $default);
    }

    if ($field === 'competition_id' && isset($_GET['competition_id'])) {
        return (string) (int) $_GET['competition_id'];
    }

    return $default;
};

require dirname(__DIR__, 2) . '/includes/header.php';
require dirname(__DIR__, 2) . '/includes/sidebar.php';
require dirname(__DIR__, 2) . '/includes/topbar.php';
require dirname(__DIR__, 2) . '/includes/flash.php';
?>
<section class="panel-card">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Competition scheduling</p>
            <h2 class="h4 mb-0">Generate fixtures</h2>
        </div>
    </div>
    <p class="text-muted">This generator creates a round-robin schedule for league competitions, a first knockout bracket for cup competitions, and a grouped round-robin first stage for group-stage or mixed competitions. It will stop if the competition already has fixtures or if the eligible club count does not match the configured team count.</p>
    <form method="post" action="<?php echo e(base_url('app/modules/fixtures/actions.php')); ?>" novalidate>
        <?php echo csrf_input(); ?>
        <input type="hidden" name="action" value="generate">
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label" for="competition_id">Competition</label>
                <select class="form-select <?php echo validation_error($formErrors, 'competition_id') ? 'is-invalid' : ''; ?>" id="competition_id" name="competition_id" required>
                    <option value="">Select competition</option>
                    <?php foreach ($competitionOptions as $competition): ?>
                        <option value="<?php echo e((string) $competition['id']); ?>" <?php echo (int) $fieldValue('competition_id') === (int) $competition['id'] ? 'selected' : ''; ?>>
                            <?php echo e($competition['name']); ?> (<?php echo e($competition['season_name']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (validation_error($formErrors, 'competition_id')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'competition_id')); ?></div><?php endif; ?>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="start_date">First matchday date</label>
                <input class="form-control <?php echo validation_error($formErrors, 'start_date') ? 'is-invalid' : ''; ?>" id="start_date" name="start_date" type="date" value="<?php echo e((string) $fieldValue('start_date')); ?>">
                <?php if (validation_error($formErrors, 'start_date')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'start_date')); ?></div><?php endif; ?>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="match_time">Default kickoff time</label>
                <input class="form-control <?php echo validation_error($formErrors, 'match_time') ? 'is-invalid' : ''; ?>" id="match_time" name="match_time" type="time" value="<?php echo e((string) $fieldValue('match_time')); ?>">
                <?php if (validation_error($formErrors, 'match_time')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'match_time')); ?></div><?php endif; ?>
            </div>
            <div class="col-md-4">
                <label class="form-label" for="days_between_matchdays">Days between matchdays</label>
                <input class="form-control <?php echo validation_error($formErrors, 'days_between_matchdays') ? 'is-invalid' : ''; ?>" id="days_between_matchdays" name="days_between_matchdays" type="number" min="1" value="<?php echo e((string) $fieldValue('days_between_matchdays', '7')); ?>">
                <?php if (validation_error($formErrors, 'days_between_matchdays')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'days_between_matchdays')); ?></div><?php endif; ?>
                <div class="form-text">Used only when you do not pick specific weekdays.</div>
            </div>
            <div class="col-md-8">
                <label class="form-label d-block">Allowed match days</label>
                <div class="d-flex flex-wrap gap-3 pt-2">
                    <?php $selectedWeekdays = (array) $fieldValue('matchdays_of_week', []); ?>
                    <?php foreach ($weekdayOptions as $weekdayValue => $weekdayLabel): ?>
                        <div class="form-check">
                            <input class="form-check-input" id="weekday_<?php echo e($weekdayValue); ?>" name="matchdays_of_week[]" type="checkbox" value="<?php echo e($weekdayValue); ?>" <?php echo in_array($weekdayValue, array_map('strval', $selectedWeekdays), true) ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="weekday_<?php echo e($weekdayValue); ?>"><?php echo e($weekdayLabel); ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php if (validation_error($formErrors, 'matchdays_of_week')): ?><div class="invalid-feedback d-block"><?php echo e((string) validation_error($formErrors, 'matchdays_of_week')); ?></div><?php endif; ?>
                <div class="form-text">If you select days here, fixtures will be scheduled only on those weekdays and the interval field will be ignored.</div>
            </div>
            <div class="col-md-8 d-flex align-items-end">
                <div class="form-check mb-2">
                    <input class="form-check-input" id="double_round" name="double_round" type="checkbox" value="1" <?php echo $fieldValue('double_round', '0') === '1' ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="double_round">Create home and away legs</label>
                </div>
            </div>
        </div>
        <div class="d-flex gap-2 mt-4">
            <button class="btn btn-jlfc" type="submit">Generate fixtures</button>
            <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/fixtures/index.php')); ?>">Cancel</a>
        </div>
    </form>
</section>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>