<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\GridView;

$this->title = 'Управление заявками';
$this->params['breadcrumbs'][] = ['label' => 'Панель администратора', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="admin-requests">
    <h1><?= Html::encode($this->title) ?></h1>
    
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            
            [
                'attribute' => 'id',
                'label' => '№ заявки',
                'headerOptions' => ['style' => 'width:80px'],
            ],
            [
                'attribute' => 'user_id',
                'label' => 'Пользователь',
                'value' => function($model) {
                    return $model->user ? $model->user->full_name : 'Неизвестно';
                },
            ],
            [
                'attribute' => 'session_id',
                'label' => 'Игра',
                'value' => function($model) {
                    return $model->gameName;
                },
            ],
            [
                'attribute' => 'session.date',
                'label' => 'Дата игры',
                'value' => function($model) {
                    return $model->sessionDate;
                },
            ],
            [
                'attribute' => 'player_count',
                'label' => 'Кол-во',
                'headerOptions' => ['style' => 'width:80px'],
            ],
            [
                'attribute' => 'total_price',
                'label' => 'Сумма',
                'value' => function($model) {
                    return number_format($model->total_price, 0, '', ' ') . ' ₽';
                },
                'headerOptions' => ['style' => 'width:100px'],
            ],
            [
                'attribute' => 'status',
                'label' => 'Статус',
                'format' => 'raw',
                'value' => function($model) {
                    $statuses = [
                        'новая' => 'warning',
                        'одобрена' => 'success',
                        'завершена' => 'primary',
                        'отменена' => 'danger',
                    ];
                    $color = $statuses[$model->status] ?? 'light';
                    return '<span class="badge badge-' . $color . '">' . $model->statusLabel . '</span>';
                },
                'headerOptions' => ['style' => 'width:120px'],
            ],
            [
                'attribute' => 'created_at',
                'label' => 'Дата заявки',
                'value' => function($model) {
                    return date('d.m.Y H:i', $model->created_at);
                },
                'headerOptions' => ['style' => 'width:150px'],
            ],
            [
                'class' => 'yii\grid\ActionColumn',
                'template' => '{view} {update-status}',
                'headerOptions' => ['style' => 'width:100px'],
                'buttons' => [
                    'view' => function($url, $model) {
                        return Html::a('<i class="fas fa-eye"></i>', 
                            Url::to(['view-request', 'id' => $model->id]), 
                            ['title' => 'Просмотр', 'class' => 'btn btn-sm btn-info']
                        );
                    },
                    'update-status' => function($url, $model) {
                        return Html::a('<i class="fas fa-edit"></i>', 
                            '#', 
                            [
                                'title' => 'Изменить статус',
                                'class' => 'btn btn-sm btn-primary update-status-btn',
                                'data-id' => $model->id,
                                'data-status' => $model->status,
                            ]
                        );
                    },
                ],
            ],
        ],
    ]); ?>
</div>

<!-- Модальное окно для изменения статуса -->
<div id="status-modal" class="modal" style="display:none;">
    <div class="modal-content" style="max-width:500px;">
        <div class="modal-header">
            <h3>Изменить статус заявки</h3>
            <span class="close-modal">&times;</span>
        </div>
        <div class="modal-body">
            <form id="status-form">
                <input type="hidden" id="request-id" name="id">
                <div class="form-group">
                    <label for="request-status">Статус:</label>
                    <select id="request-status" name="status" class="form-control">
                        <option value="новая">Новая</option>
                        <option value="одобрена">Одобрена</option>
                        <option value="завершена">Завершена</option>
                        <option value="отменена">Отменена</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="admin-comment">Комментарий:</label>
                    <textarea id="admin-comment" name="comment" class="form-control" rows="3"></textarea>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary close-modal">Отмена</button>
            <button type="button" class="btn btn-primary" id="save-status">Сохранить</button>
        </div>
    </div>
</div>

<style>
.badge {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.badge-warning { background: #ffc107; color: #000; }
.badge-success { background: #28a745; color: #fff; }
.badge-primary { background: #007bff; color: #fff; }
.badge-danger { background: #dc3545; color: #fff; }

.btn-sm {
    padding: 5px 10px;
    font-size: 12px;
    border-radius: 5px;
    text-decoration: none;
    margin: 0 2px;
}

.btn-info { background: #17a2b8; color: white; }
.btn-primary { background: #007bff; color: white; }

.table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

.table th {
    background: #f8f9fa;
    padding: 12px;
    text-align: left;
    font-weight: 600;
}

.table td {
    padding: 12px;
    border-bottom: 1px solid #dee2e6;
}

.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-content {
    background: white;
    border-radius: 10px;
    width: 90%;
    max-width: 500px;
    animation: slideIn 0.3s;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Открытие модального окна
    document.querySelectorAll('.update-status-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const id = this.dataset.id;
            const status = this.dataset.status;
            
            document.getElementById('request-id').value = id;
            document.getElementById('request-status').value = status;
            document.getElementById('admin-comment').value = '';
            
            document.getElementById('status-modal').style.display = 'flex';
        });
    });
    
    // Закрытие модального окна
    document.querySelectorAll('.close-modal').forEach(el => {
        el.addEventListener('click', function() {
            document.getElementById('status-modal').style.display = 'none';
        });
    });
    
    // Сохранение статуса
    document.getElementById('save-status').addEventListener('click', function() {
        const id = document.getElementById('request-id').value;
        const status = document.getElementById('request-status').value;
        const comment = document.getElementById('admin-comment').value;
        
        fetch('<?= Url::to(['admin/update-request-status']) ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'id=' + id + '&status=' + status + '&comment=' + encodeURIComponent(comment)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert(data.message);
            }
        });
    });
    
    // Закрытие по клику вне модального окна
    window.addEventListener('click', function(e) {
        const modal = document.getElementById('status-modal');
        if (e.target == modal) {
            modal.style.display = 'none';
        }
    });
});
</script>