<?php
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

use yii\helpers\Html;
use yii\helpers\Url;

$this->title = 'Управление расписанием';
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="admin-schedule">
    <!-- Хедер страницы -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex align-items-center justify-content-between mb-4">
                <div>
                    <h1 class="h2 mb-2"><?= Html::encode($this->title) ?></h1>
                    <p class="text-muted">Управление расписанием настольных игр</p>
                </div>
                <div>
                    <a href="<?= Url::to(['admin/create-schedule']) ?>" class="btn btn-primary rounded-pill px-4">
                        <i class="fas fa-plus me-2"></i>Добавить игру
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Карточки статистики -->
    <div class="row g-4 mb-4">
        <div class="col-xl-3 col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center">
                        <div class="icon-circle bg-primary-light text-primary me-3">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <div>
                            <div class="text-muted small mb-1">Игр на этой неделе</div>
                            <div class="h4 mb-0"><?= \app\models\Schedule::find()
                                ->where(['>=', 'date', date('Y-m-d')])
                                ->andWhere(['<=', 'date', date('Y-m-d', strtotime('+7 days'))])
                                ->count() ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center">
                        <div class="icon-circle bg-success-light text-success me-3">
                            <i class="fas fa-users"></i>
                        </div>
                        <div>
                            <div class="text-muted small mb-1">Свободных мест</div>
                            <div class="h4 mb-0"><?= \app\models\Schedule::find()
                                ->where(['>=', 'date', date('Y-m-d')])
                                ->sum('max_players - current_players') ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center">
                        <div class="icon-circle bg-info-light text-info me-3">
                            <i class="fas fa-gamepad"></i>
                        </div>
                        <div>
                            <div class="text-muted small mb-1">Уникальных игр</div>
                            <div class="h4 mb-0"><?= \app\models\Schedule::find()
                                ->select('game_id')
                                ->distinct()
                                ->count() ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center">
                        <div class="icon-circle bg-warning-light text-warning me-3">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <div>
                            <div class="text-muted small mb-1">Средняя цена</div>
                            <div class="h4 mb-0"><?= \app\models\Schedule::find()
                                ->where(['>=', 'date', date('Y-m-d')])
                                ->average('price') ?> ₽</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Таблица расписания -->
    <div class="card border-0 shadow-sm">
        <div class="card-header border-0 bg-transparent d-flex justify-content-between align-items-center py-4">
            <h5 class="mb-0 fw-medium">Расписание игр</h5>
            <div class="d-flex gap-2">
                <div class="dropdown">
                    <button class="btn btn-sm btn-outline-secondary rounded-pill dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="fas fa-filter me-1"></i> Фильтр
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="?date=<?= date('Y-m-d') ?>"><i class="far fa-calendar me-2"></i>Сегодня</a></li>
                        <li><a class="dropdown-item" href="?date=<?= date('Y-m-d', strtotime('+1 day')) ?>"><i class="far fa-calendar me-2"></i>Завтра</a></li>
                        <li><a class="dropdown-item" href="?date=<?= date('Y-m-d', strtotime('+7 days')) ?>"><i class="far fa-calendar me-2"></i>Неделя</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="?"><i class="fas fa-redo me-2"></i>Сбросить</a></li>
                    </ul>
                </div>
                <button class="btn btn-sm btn-outline-primary rounded-pill" id="calendar-view">
                    <i class="fas fa-calendar me-1"></i> Календарь
                </button>
            </div>
        </div>
        <div class="card-body pt-0">
            <div class="table-responsive">
                <table class="table table-hover table-borderless align-middle">
                    <thead class="table-light">
                    <tr>
                        <th class="small text-uppercase text-muted" width="80">ID</th>
                        <th class="small text-uppercase text-muted">Игра</th>
                        <th class="small text-uppercase text-muted" width="150">Дата и время</th>
                        <th class="small text-uppercase text-muted">Адрес</th>
                        <th class="small text-uppercase text-muted" width="120">Стоимость</th>
                        <th class="small text-uppercase text-muted" width="120">Участники</th>
                        <th class="small text-uppercase text-muted text-end" width="100">Действия</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($dataProvider->getModels() as $schedule): ?>
                        <?php 
                        $isUpcoming = strtotime($schedule->date) >= strtotime(date('Y-m-d'));
                        $isToday = $schedule->date == date('Y-m-d');
                        ?>
                        <tr class="border-bottom <?= $isToday ? 'bg-light' : '' ?>">
                            <td>
                                <span class="badge bg-light text-dark">#<?= $schedule->id ?></span>
                                <?php if ($isToday): ?>
                                    <span class="badge bg-primary-light text-primary rounded-pill mt-1 d-block">Сегодня</span>
                                <?php elseif ($isUpcoming): ?>
                                    <span class="badge bg-success-light text-success rounded-pill mt-1 d-block">Скоро</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="icon-circle-sm bg-light text-muted me-3">
                                        <i class="fas fa-gamepad"></i>
                                    </div>
                                    <div>
                                        <div class="fw-medium"><?= Html::encode($schedule->game->name) ?></div>
                                        <small class="text-muted">
                                            <span class="badge bg-secondary-light text-secondary rounded-pill">
                                                <?= $schedule->game->getCategoryLabel() ?>
                                            </span>
                                        </small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="small">
                                    <div class="fw-medium">
                                        <?= Yii::$app->formatter->asDate($schedule->date, 'dd.MM.yy') ?>
                                    </div>
                                    <small class="text-muted">
                                        <i class="far fa-clock me-1"></i>
                                        <?= $schedule->start_time ?>
                                    </small>
                                    <?php if ($isToday): ?>
                                        <div class="badge bg-primary-light text-primary rounded-pill mt-1">
                                            <?= Yii::$app->formatter->asRelativeTime($schedule->date . ' ' . $schedule->start_time) ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div class="text-truncate" style="max-width: 200px;">
                                    <?= Html::encode($schedule->address) ?>
                                </div>
                            </td>
                            <td>
                                <div class="fw-medium"><?= $schedule->price ?> ₽</div>
                            </td>
                            <td>
                                <div class="progress mb-2" style="height: 8px;">
                                    <?php 
                                    $percentage = $schedule->max_players > 0 ? 
                                        ($schedule->current_players / $schedule->max_players) * 100 : 0;
                                    $progressColor = $percentage >= 90 ? 'danger' : 
                                        ($percentage >= 70 ? 'warning' : 'success');
                                    ?>
                                    <div class="progress-bar bg-<?= $progressColor ?>" 
                                         role="progressbar" 
                                         style="width: <?= $percentage ?>%">
                                    </div>
                                </div>
                                <span class="badge rounded-pill bg-<?= $schedule->current_players < $schedule->max_players ? 'success' : 'danger' ?>-light text-<?= $schedule->current_players < $schedule->max_players ? 'success' : 'danger' ?>">
                                    <?= $schedule->current_players ?>/<?= $schedule->max_players ?>
                                </span>
                            </td>
                            <td class="text-end">
                                <div class="btn-group" role="group">
                                    <a href="<?= Url::to(['admin/update-schedule', 'id' => $schedule->id]) ?>"
                                       class="btn btn-sm btn-outline-primary rounded-circle" title="Редактировать">
                                        <i class="fas fa-edit fa-sm"></i>
                                    </a>
                                    <button type="button" class="btn btn-sm btn-outline-danger rounded-circle delete-schedule"
                                            data-id="<?= $schedule->id ?>" title="Удалить">
                                        <i class="fas fa-trash fa-sm"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Пагинация -->
            <?php if ($dataProvider->pagination->pageCount > 1): ?>
            <div class="mt-4 pt-3 border-top">
                <nav aria-label="Пагинация">
                    <?= \yii\widgets\LinkPager::widget([
                        'pagination' => $dataProvider->pagination,
                        'options' => [
                            'class' => 'pagination justify-content-center mb-0',
                        ],
                        'linkContainerOptions' => ['class' => 'page-item'],
                        'linkOptions' => ['class' => 'page-link'],
                        'disabledListItemSubTagOptions' => ['class' => 'page-link'],
                    ]) ?>
                </nav>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php
$js = <<<JS
$(document).ready(function() {
    // Удаление расписания
    $('.delete-schedule').on('click', function() {
        var id = $(this).data('id');
        
        if (confirm('Вы уверены, что хотите удалить это расписание?')) {
            $.ajax({
                url: '/admin/delete-schedule?id=' + id,
                type: 'POST',
                data: {
                    _csrf: yii.getCsrfToken()
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Ошибка при удалении: ' + response.message);
                    }
                }
            });
        }
    });
    
    // Переключение вида календаря
    $('#calendar-view').on('click', function() {
        window.location.href = '/admin/schedule-calendar';
    });
});
JS;
$this->registerJs($js);
?>