<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use app\models\CounterReadings;

$this->title = 'Админ-панель - Управление показаниями';
$this->params['breadcrumbs'][] = $this->title;

$serviceIcons = [
    'electricity' => '⚡',
    'gas' => '🔥', 
    'water' => '💧'
];

$statusColors = [
    CounterReadings::STATUS_NEW => 'status-new',
    CounterReadings::STATUS_ACCEPTED => 'status-accepted',
    CounterReadings::STATUS_REJECTED => 'status-rejected',
];

$statusIcons = [
    CounterReadings::STATUS_NEW => '⏳',
    CounterReadings::STATUS_ACCEPTED => '✅',
    CounterReadings::STATUS_REJECTED => '❌'
];
?>

<div class="admin-index">
    <div class="admin-header">
        <div class="header-content">
            <h1 class="admin-title">🛠️ Админ-панель</h1>
            <div class="admin-subtitle">Управление показаниями и пользователями</div>
        </div>
    </div>

    <!-- Статистика -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">📊</div>
            <div class="stat-info">
                <div class="stat-value"><?= $stats['total'] ?></div>
                <div class="stat-label">Всего показаний</div>
            </div>
        </div>
        
        <div class="stat-card new">
            <div class="stat-icon">⏳</div>
            <div class="stat-info">
                <div class="stat-value"><?= $stats['new'] ?></div>
                <div class="stat-label">Новые</div>
            </div>
        </div>
        
        <div class="stat-card accepted">
            <div class="stat-icon">✅</div>
            <div class="stat-info">
                <div class="stat-value"><?= $stats['accepted'] ?></div>
                <div class="stat-label">Принято</div>
            </div>
        </div>
        
        <div class="stat-card rejected">
            <div class="stat-icon">❌</div>
            <div class="stat-info">
                <div class="stat-value"><?= $stats['rejected'] ?></div>
                <div class="stat-label">Отклонено</div>
            </div>
        </div>
        
        <div class="stat-card users">
            <div class="stat-icon">👥</div>
            <div class="stat-info">
                <div class="stat-value"><?= $stats['users'] ?></div>
                <div class="stat-label">Пользователи</div>
            </div>
        </div>
    </div>

    <!-- Быстрые действия -->
    <div class="quick-actions">
        <h3 class="actions-title">Быстрые действия</h3>
        <div class="actions-grid">
            <?= Html::a('👥 Управление пользователями', ['users'], ['class' => 'action-btn users']) ?>
            <?= Html::a('💰 Управление тарифами', ['tariffs'], ['class' => 'action-btn tariffs']) ?>
            <?= Html::a('📊 Статистика системы', ['statistics'], ['class' => 'action-btn stats']) ?>
        </div>
    </div>

    <?php Pjax::begin(['timeout' => 5000]); ?>
    
    <div class="readings-table-container">
        <div class="table-header-section">
            <h3 class="table-title">📋 Все переданные показания</h3>
            <div class="table-actions">
                <div class="filter-info">
                    Показано <?= $dataProvider->getCount() ?> из <?= $dataProvider->getTotalCount() ?> записей
                </div>
            </div>
        </div>

        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'tableOptions' => ['class' => 'table admin-table'],
            'layout' => "{items}\n<div class='table-footer'>{summary}\n{pager}</div>",
            'summary' => 'Показано <b>{begin}-{end}</b> из <b>{totalCount}</b> записей',
            'summaryOptions' => ['class' => 'summary'],
            'pager' => [
                'options' => ['class' => 'pagination'],
                'linkOptions' => ['class' => 'page-link'],
                'activePageCssClass' => 'active',
                'disabledPageCssClass' => 'disabled',
            ],
            'columns' => [
                [
                    'attribute' => 'id',
                    'label' => 'ID',
                    'headerOptions' => ['class' => 'table-header id-header'],
                    'contentOptions' => ['class' => 'table-cell id-cell'],
                    'headerOptions' => ['class' => 'table-header'],
                ],
                [
                    'attribute' => 'user.full_name',
                    'label' => '👤 Пользователь',
                    'headerOptions' => ['class' => 'table-header user-header'],
                    'contentOptions' => ['class' => 'table-cell user-cell'],
                ],
                [
                    'attribute' => 'date',
                    'label' => '📅 Дата',
                    'format' => 'date',
                    'headerOptions' => ['class' => 'table-header date-header'],
                    'contentOptions' => ['class' => 'table-cell date-cell'],
                ],
                [
                    'attribute' => 'service_type',
                    'label' => 'Услуга',
                    'value' => function($model) use ($serviceIcons) {
                        return $serviceIcons[$model->service_type] . ' ' . $model->getServiceTypeLabel();
                    },
                    'format' => 'raw',
                    'headerOptions' => ['class' => 'table-header service-header'],
                    'contentOptions' => ['class' => 'table-cell service-cell'],
                ],
                [
                    'attribute' => 'current_readings',
                    'label' => '📈 Текущие',
                    'value' => function($model) {
                        return Yii::$app->formatter->asDecimal($model->current_readings, 2);
                    },
                    'headerOptions' => ['class' => 'table-header readings-header'],
                    'contentOptions' => ['class' => 'table-cell readings-cell'],
                ],
                [
                    'attribute' => 'consumption',
                    'label' => '📉 Расход',
                    'value' => function($model) {
                        return Yii::$app->formatter->asDecimal($model->consumption, 2);
                    },
                    'headerOptions' => ['class' => 'table-header consumption-header'],
                    'contentOptions' => ['class' => 'table-cell consumption-cell'],
                ],
                [
                    'attribute' => 'sum',
                    'label' => '💳 Сумма',
                    'value' => function($model) {
                        return Yii::$app->formatter->asDecimal($model->sum, 2) . ' руб';
                    },
                    'headerOptions' => ['class' => 'table-header sum-header'],
                    'contentOptions' => ['class' => 'table-cell sum-cell'],
                ],
                [
                    'attribute' => 'status',
                    'label' => '📋 Статус',
                    'value' => function($model) use ($statusIcons, $statusColors) {
                        return Html::tag('span', 
                            $statusIcons[$model->status] . ' ' . $model->getStatusLabel(), 
                            ['class' => "status {$statusColors[$model->status]}"]
                        );
                    },
                    'format' => 'raw',
                    'headerOptions' => ['class' => 'table-header status-header'],
                    'contentOptions' => ['class' => 'table-cell status-cell'],
                ],
                [
                    'attribute' => 'created_at',
                    'label' => '⏰ Создано',
                    'format' => 'datetime',
                    'headerOptions' => ['class' => 'table-header created-header'],
                    'contentOptions' => ['class' => 'table-cell created-cell'],
                ],
                [
                    'class' => 'yii\grid\ActionColumn',
                    'header' => 'Действия',
                    'template' => '{view} {accept} {reject}',
                    'headerOptions' => ['class' => 'table-header actions-header'],
                    'contentOptions' => ['class' => 'table-cell actions-cell'],
                    'buttons' => [
                        'view' => function ($url, $model, $key) {
                            return Html::a('👁️', ['reading-detail', 'id' => $model->id], [
                                'class' => 'btn-action view',
                                'title' => 'Просмотр деталей',
                                'data-pjax' => 0,
                            ]);
                        },
                        'accept' => function ($url, $model, $key) {
                            if ($model->status === CounterReadings::STATUS_NEW) {
                                return Html::a('✅', ['update-status', 'id' => $model->id, 'status' => CounterReadings::STATUS_ACCEPTED], [
                                    'class' => 'btn-action accept',
                                    'title' => 'Принять показания',
                                    'data' => [
                                        'confirm' => 'Вы уверены, что хотите принять эти показания?',
                                        'method' => 'post',
                                    ],
                                ]);
                            }
                            return '';
                        },
                        'reject' => function ($url, $model, $key) {
                            if ($model->status === CounterReadings::STATUS_NEW) {
                                return Html::a('❌', ['update-status', 'id' => $model->id, 'status' => CounterReadings::STATUS_REJECTED], [
                                    'class' => 'btn-action reject',
                                    'title' => 'Отклонить показания',
                                    'data' => [
                                        'confirm' => 'Вы уверены, что хотите отклонить эти показания?',
                                        'method' => 'post',
                                    ],
                                ]);
                            }
                            return '';
                        },
                    ],
                ],
            ],
            'rowOptions' => function($model) use ($statusColors) {
                return [
                    'class' => 'table-row ' . $statusColors[$model->status],
                    'data-id' => $model->id
                ];
            },
        ]); ?>
    </div>
    
    <?php Pjax::end(); ?>
</div>
