<div class="container my-4">
    <div class="card shadow-sm border-0 rounded-4 overflow-hidden">
        <div class="card-body p-0">
            <?php
            /* @var $this yii\web\View */
            /* @var $model app\models\Application */
            /* @var $schedules app\models\Schedule[] */
            /* @var $user app\models\User */

            use yii\helpers\Html;
            use yii\widgets\ActiveForm;
            use yii\helpers\Url;

            $this->title = 'Запись на игру';
            $this->params['breadcrumbs'][] = $this->title;
            ?>

            <div class="site-create-application">
                <div class="row g-0">
                    <!-- Основная форма -->
                    <div class="col-lg-8">
                        <div class="p-4 p-md-5 h-100 bg-white">
                            <h1 class="h3 mb-4 text-primary fw-bold"><?= Html::encode($this->title) ?></h1>

                            <?php $form = ActiveForm::begin([
                                'id' => 'application-form',
                                'fieldConfig' => [
                                    'template' => "{label}\n{input}\n{error}",
                                    'labelOptions' => ['class' => 'form-label fw-semibold text-dark'],
                                    'inputOptions' => ['class' => 'form-control'],
                                    'errorOptions' => ['class' => 'invalid-feedback'],
                                ],
                            ]); ?>

                            <!-- Инструкция -->
                            <div class="alert alert-light border border-info-subtle bg-info-subtle mb-4 rounded-3">
                                <div class="d-flex align-items-start">
                                    <i class="fas fa-info-circle text-info mt-1 me-2 fs-5"></i>
                                    <div>
                                        <strong>Как это работает?</strong><br>
                                        Выберите игру из расписания — все данные подставятся автоматически.
                                    </div>
                                </div>
                            </div>

                            <!-- Шаг 1: Расписание -->
                            <div class="mb-5">
                                <h2 class="h5 fw-bold text-dark mb-3 d-flex align-items-center">
                                    <span class="badge bg-primary rounded-circle me-2" style="width:24px; height:24px; display:flex; align-items:center; justify-content:center; font-size:0.8rem;">1</span>
                                    Выберите игру
                                </h2>
                                <?php if (empty($schedules)): ?>
                                    <div class="alert alert-warning rounded-3">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        К сожалению, сейчас нет доступных игр для записи.
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive rounded-3 border">
                                        <table class="table table-hover mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th scope="col" style="width:15%">Дата</th>
                                                    <th scope="col" style="width:12%">Время</th>
                                                    <th scope="col">Игра</th>
                                                    <th scope="col" style="width:15%">Адрес</th>
                                                    <th scope="col" class="text-end" style="width:10%">Стоимость</th>
                                                    <th scope="col" class="text-center" style="width:12%">Места</th>
                                                    <th scope="col" style="width:10%"></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($schedules as $schedule): ?>
                                                    <tr id="schedule-<?= $schedule->id ?>" class="schedule-row" style="cursor: pointer;">
                                                        <td><?= Yii::$app->formatter->asDate($schedule->date) ?></td>
                                                        <td><?= $schedule->start_time ?></td>
                                                        <td>
                                                            <div class="fw-bold"><?= Html::encode($schedule->game->name) ?></div>
                                                            <small class="text-muted"><?= $schedule->game->getCategoryLabel() ?></small>
                                                        </td>
                                                        <td class="text-nowrap"><?= Html::encode($schedule->address) ?></td>
                                                        <td class="text-end"><?= $schedule->price ?> ₽</td>
                                                        <td class="text-center">
                                                            <span class="badge <?= $schedule->current_players < $schedule->max_players ? 'bg-success' : 'bg-danger' ?> rounded-pill px-2 py-1">
                                                                <?= $schedule->current_players ?>/<?= $schedule->max_players ?>
                                                            </span>
                                                        </td>
                                                        <td class="text-center">
                                                            <button type="button" class="btn btn-sm btn-outline-primary select-schedule"
                                                                    data-id="<?= $schedule->id ?>"
                                                                    data-game="<?= Html::encode($schedule->game->name) ?>"
                                                                    data-category="<?= $schedule->game->category ?>"
                                                                    data-date="<?= $schedule->date ?>"
                                                                    data-time="<?= $schedule->start_time ?>"
                                                                    data-address="<?= Html::encode($schedule->address) ?>"
                                                                    data-price="<?= $schedule->price ?>">
                                                                Выбрать
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <hr class="my-4">

                            <!-- Шаг 2: Данные игры -->
                            <div class="mb-5">
                                <h2 class="h5 fw-bold text-dark mb-3 d-flex align-items-center">
                                    <span class="badge bg-primary rounded-circle me-2" style="width:24px; height:24px; font-size:0.8rem;">2</span>
                                    Подтверждение выбора
                                </h2>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'game_category')->textInput([
                                            'readonly' => true,
                                            'id' => 'game-category',
                                            'class' => 'form-control-plaintext bg-light rounded-2 border'
                                        ]) ?>
                                    </div>
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'game_name')->textInput([
                                            'readonly' => true,
                                            'id' => 'game-name',
                                            'class' => 'form-control-plaintext bg-light rounded-2 border'
                                        ]) ?>
                                    </div>
                                </div>
                                <div class="row g-3 mt-1">
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'date')->textInput([
                                            'readonly' => true,
                                            'id' => 'game-date',
                                            'class' => 'form-control-plaintext bg-light rounded-2 border'
                                        ]) ?>
                                    </div>
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'start_time')->textInput([
                                            'readonly' => true,
                                            'id' => 'game-time',
                                            'class' => 'form-control-plaintext bg-light rounded-2 border'
                                        ]) ?>
                                    </div>
                                </div>
                                <div class="row g-3 mt-1">
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'address')->textInput([
                                            'readonly' => true,
                                            'id' => 'game-address',
                                            'class' => 'form-control-plaintext bg-light rounded-2 border'
                                        ]) ?>
                                    </div>
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'price')->textInput([
                                            'readonly' => true,
                                            'id' => 'game-price',
                                            'class' => 'form-control-plaintext bg-light rounded-2 border'
                                        ]) ?>
                                    </div>
                                </div>
                                <?= $form->field($model, 'schedule_id')->hiddenInput(['id' => 'schedule-id'])->label(false) ?>
                            </div>

                            <hr class="my-4">

                            <!-- Шаг 3: Ваши данные -->
                            <div class="mb-5">
                                <h2 class="h5 fw-bold text-dark mb-3 d-flex align-items-center">
                                    <span class="badge bg-primary rounded-circle me-2" style="width:24px; height:24px; font-size:0.8rem;">3</span>
                                    Ваши контактные данные
                                </h2>
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <?= $form->field($model, 'full_name')->textInput(['readonly' => true, 'class' => 'form-control-plaintext bg-light rounded-2 border']) ?>
                                    </div>
                                    <div class="col-md-4">
                                        <?= $form->field($model, 'email')->textInput(['readonly' => true, 'class' => 'form-control-plaintext bg-light rounded-2 border']) ?>
                                    </div>
                                    <div class="col-md-4">
                                        <?= $form->field($model, 'phone')->textInput(['readonly' => true, 'class' => 'form-control-plaintext bg-light rounded-2 border']) ?>
                                    </div>
                                </div>
                            </div>

                            <hr class="my-4">

                            <!-- Шаг 4: Доп. инфо -->
                            <div class="mb-4">
                                <h2 class="h5 fw-bold text-dark mb-3 d-flex align-items-center">
                                    <span class="badge bg-primary rounded-circle me-2" style="width:24px; height:24px; font-size:0.8rem;">4</span>
                                    Дополнительно
                                </h2>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'payment_method')->dropDownList(
                                            \app\models\Application::getPaymentMethods(),
                                            ['prompt' => 'Выберите способ оплаты', 'class' => 'form-select form-select-lg']
                                        ) ?>
                                    </div>
                                    <div class="col-md-6">
                                        <?= $form->field($model, 'player_level')->dropDownList(
                                            \app\models\Application::getPlayerLevels(),
                                            ['prompt' => 'Выберите ваш уровень', 'class' => 'form-select form-select-lg']
                                        ) ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Согласие -->
                            <div class="mb-4">
                                <?= $form->field($model, 'personal_data_agreement')->checkbox([
                                    'template' => "<div class=\"form-check form-switch\">\n{input} {label}\n{error}\n</div>",
                                    'labelOptions' => ['class' => 'form-check-label text-dark'],
                                    'class' => 'form-check-input'
                                ])->label('Согласен на обработку персональных данных') ?>
                                <p class="small text-muted mt-2">
                                    Нажимая «Забронировать место», вы подтверждаете согласие на обработку персональных данных в соответствии с политикой конфиденциальности.
                                </p>
                            </div>

                            <!-- Кнопка -->
                            <?= Html::submitButton('Забронировать место', [
                                'class' => 'btn btn-success btn-lg w-100 py-3 fw-bold fs-5',
                                'name' => 'application-button',
                                'disabled' => empty($schedules),
                                'id' => 'submit-btn'
                            ]) ?>

                            <?php ActiveForm::end(); ?>
                        </div>
                    </div>

                    <!-- Боковая панель -->
                    <div class="col-lg-4 bg-light border-start">
                        <div class="p-4 h-100 d-flex flex-column">
                            <!-- Информация -->
                            <div class="card border-0 shadow-sm mb-4 rounded-3">
                                <div class="card-header bg-gradient-primary text-white py-3 rounded-top-3">
                                    <h5 class="mb-0 fw-bold">Важная информация</h5>
                                </div>
                                <div class="card-body p-3">
                                    <div class="alert alert-warning mb-3 rounded-2 p-2">
                                        <i class="fas fa-clock me-1"></i>
                                        <strong>Обработка в течение 24 ч</strong>
                                    </div>
                                    <ul class="list-unstyled small">
                                        <li class="mb-2"><i class="fas fa-envelope text-success me-2"></i> Подтверждение пришлют на email</li>
                                        <li class="mb-2"><i class="fas fa-user-check text-success me-2"></i> Статус — в личном кабинете</li>
                                        <li><i class="fas fa-credit-card text-success me-2"></i> Оплата — на месте перед игрой</li>
                                    </ul>
                                </div>
                            </div>

                            <!-- Профиль -->
                            <div class="card border-0 shadow-sm mt-auto rounded-3">
                                <div class="card-header bg-gradient-primary text-white py-3 rounded-top-3">
                                    <h5 class="mb-0 fw-bold">Ваш профиль</h5>
                                </div>
                                <div class="card-body text-center p-3">
                                    <div class="mb-3">
                                        <div class="bg-primary bg-opacity-10 d-inline-flex align-items-center justify-content-center rounded-circle" style="width:72px; height:72px;">
                                            <i class="fas fa-user text-primary" style="font-size:28px;"></i>
                                        </div>
                                        <h5 class="mt-2 mb-1"><?= Html::encode($user->full_name) ?></h5>
                                    </div>
                                    <ul class="list-unstyled small text-dark mb-0">
                                        <li class="mb-1"><i class="fas fa-phone me-1 text-primary"></i> <?= Html::encode($user->phone) ?></li>
                                        <li class="mb-1"><i class="fas fa-envelope me-1 text-primary"></i> <?= Html::encode($user->email) ?></li>
                                        <li><i class="fas fa-calendar-alt me-1 text-primary"></i> С <?= Yii::$app->formatter->asDate($user->created_at) ?></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php
            $js = <<<JS
$(document).ready(function() {
    $('.select-schedule').on('click', function() {
        var \$btn = $(this);
        $('#schedule-id').val(\$btn.data('id'));
        $('#game-category').val(\$btn.data('category'));
        $('#game-name').val(\$btn.data('game'));
        $('#game-date').val(\$btn.data('date'));
        $('#game-time').val(\$btn.data('time'));
        $('#game-address').val(\$btn.data('address'));
        $('#game-price').val(\$btn.data('price'));
        $('#submit-btn').prop('disabled', false);
        $('.schedule-row').removeClass('table-primary');
        \$btn.closest('tr').addClass('table-primary');
        $('html, body').animate({ scrollTop: $('#application-form').offset().top - 100 }, 500);
    });

    $('#application-form').on('submit', function(e) {
        var isValid = true, errors = [];
        if (!$('#schedule-id').val()) errors.push('Выберите игру');
        if (!$('select[name="Application[payment_method]"]').val()) errors.push('Выберите способ оплаты');
        if (!$('select[name="Application[player_level]"]').val()) errors.push('Укажите ваш уровень');
        if (!$('#application-personal_data_agreement').is(':checked')) errors.push('Требуется согласие на обработку данных');
        if (!isValid || errors.length) {
            e.preventDefault();
            alert('Заполните обязательные поля:\\n' + errors.join('\\n'));
        } else if (!confirm('Подтвердите создание заявки?')) {
            e.preventDefault();
        }
    });

    if ($('.select-schedule').length === 0) {
        $('#submit-btn').prop('disabled', true).text('Нет доступных игр').removeClass('btn-success').addClass('btn-outline-secondary');
    }
});
JS;
            $this->registerJs($js);
            ?>
        </div>
    </div>
</div>

<style>
.bg-gradient-primary {
    background: linear-gradient(135deg, #0d6efd, #0b5ed7);
}
.form-control-plaintext {
    min-height: 2.5rem;
    padding: 0.6rem 0.75rem;
}
</style>