<?php
use app\models\User;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\ActionColumn;
use yii\grid\GridView;
use yii\widgets\Pjax;

$this->title = 'Пользователи';
?>
<div class="user-index">
    <div class="mb-4">
        <h2 class="font-weight-bold text-dark">
            <b>Управление пользователями</b>
        </h2>
        <p class="text-muted mb-0" style="font-size: 14px;">Список всех пользователей системы</p>
    </div>

    <div class="bg-white rounded-3 mb-4">
        <div class="p-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h3 class="font-weight-bold mb-0" style="font-size: 18px;">
                    <b>Все пользователи</b>
                </h3>
            </div>

            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th scope="col" style="font-size: 13px; font-weight: 600; color: var(--text-secondary, rgba(0, 0, 0, 0.6)); padding: 12px 16px; border-bottom: 1px solid var(--border-color, rgba(224, 224, 224, 0.56));">Пользователь</th>
                            <th scope="col" style="font-size: 13px; font-weight: 600; color: var(--text-secondary, rgba(0, 0, 0, 0.6)); padding: 12px 16px; border-bottom: 1px solid var(--border-color, rgba(224, 224, 224, 0.56));">Контакты</th>
                            <th scope="col" style="font-size: 13px; font-weight: 600; color: var(--text-secondary, rgba(0, 0, 0, 0.6)); padding: 12px 16px; border-bottom: 1px solid var(--border-color, rgba(224, 224, 224, 0.56));">Роль и статус</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($dataProvider->getCount() > 0): ?>
                            <?php foreach ($dataProvider->getModels() as $index => $model): ?>
                                <tr style="border-bottom: 1px solid var(--border-color, rgba(224, 224, 224, 0.56));">
                                    <td style="padding: 16px;">
                                        <div style="font-size: 14px; color: var(--text-primary, #000000); font-weight: 500;">
                                            <?= Html::encode($model->name . ' ' . $model->last_name) ?>
                                        </div>
                                        <div style="font-size: 12px; color: var(--text-secondary, rgba(0, 0, 0, 0.6)); margin-top: 4px;">
                                            <?= Html::encode($model->email) ?>
                                        </div>
                                        <?php if ($model->address): ?>
                                            <div style="font-size: 12px; color: var(--text-secondary, rgba(0, 0, 0, 0.6)); margin-top: 4px;">
                                                <i class="fas fa-map-marker-alt mr-1" style="font-size: 11px;"></i>
                                                <?= Html::encode(mb_strimwidth($model->address, 0, 40, '...')) ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding: 16px;">
                                        <?php if ($model->phone): ?>
                                            <div style="font-size: 14px; color: var(--text-primary, #000000);">
                                                <i class="fas fa-phone mr-1" style="font-size: 12px; color: var(--text-secondary, rgba(0, 0, 0, 0.6));"></i>
                                                <?= Html::encode($model->phone) ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding: 16px; min-width: 220px;">
                                        <?php
                                        $roles = [
                                            0 => 'Пользователь',
                                            1 => 'Администратор',
                                        ];
                                        
                                        $currentRole = $roles[$model->role] ?? 'Неизвестно';
                                        $roleColors = [
                                            0 => '#e5e7eb',
                                            1 => '#588157',
                                        ];
                                        $color = $roleColors[$model->role] ?? '#e5e7eb';
                                        $textColor = $model->role == 1 ? '#ffffff' : '#374151';
                                        
                                        $html = '<div style="margin-bottom: 12px;">';
                                        $html .= '<span class="badge" style="background-color: '.$color.'; color: '.$textColor.'; padding: 4px 10px; font-size: 12px; font-weight: 500; border-radius: 4px;">'.$currentRole.'</span>';
                                        $html .= '</div>';
                                        
                                        $html .= '<div style="margin-bottom: 12px;">';
                                        $html .= '<form method="post" action="'.Url::to(['user/update-role']).'">';
                                        $html .= Html::hiddenInput('id', $model->id);
                                        $html .= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken);
                                        
                                        foreach ($roles as $key => $label) {
                                            $checked = $model->role == $key ? 'checked' : '';
                                            $radioId = 'role_'.$model->id.'_'.$key;
                                            $html .= '<div style="margin: 6px 0; display: flex; align-items: center;">';
                                            $html .= '<input type="radio" id="'.$radioId.'" name="role" value="'.$key.'" '.$checked.' 
                                                     onchange="this.form.submit()" style="margin-right: 8px; cursor: pointer; accent-color: #588157; width: 14px; height: 14px;">';
                                            $html .= '<label for="'.$radioId.'" style="font-size: 13px; cursor: pointer; color: var(--text-primary, #000000); margin: 0;">'.$label.'</label>';
                                            $html .= '</div>';
                                        }
                                        $html .= '</form>';
                                        $html .= '</div>';
                
                                        if (isset($model->status)) {
                                            $statuses = [
                                                0 => 'Неактивен',
                                                1 => 'Активен',
                                            ];
                                            
                                            $currentStatus = $statuses[$model->status] ?? 'Неизвестно';
                                            $statusColors = [
                                                0 => '#dc3545',
                                                1 => '#28a745',
                                            ];
                                            $statusColor = $statusColors[$model->status] ?? '#6c757d';
                                            $statusTextColor = $model->status == 0 ? '#ffffff' : '#ffffff';
                                            
                                            $html .= '<div style="margin-bottom: 12px;">';
                                            $html .= '<span class="badge" style="background-color: '.$statusColor.'; color: '.$statusTextColor.'; padding: 4px 10px; font-size: 12px; font-weight: 500; border-radius: 4px;">'.$currentStatus.'</span>';
                                            $html .= '</div>';
                                        }
                                        
                                        echo $html;
                                        ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($dataProvider->getCount() > 0): ?>
                <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top" style="border-color: var(--border-color, rgba(224, 224, 224, 0.56));">
                    <div class="text-muted" style="font-size: 14px; color: var(--text-secondary, rgba(0, 0, 0, 0.6));">
                        Показано <?= $dataProvider->getCount() ?> из <?= $dataProvider->getTotalCount() ?> пользователей
                    </div>
                    <?php
                    echo \yii\widgets\LinkPager::widget([
                        'pagination' => $dataProvider->pagination,
                        'options' => ['class' => 'pagination mb-0'],
                        'linkOptions' => [
                            'class' => 'page-link',
                            'style' => 'font-size: 14px; border: 1px solid var(--border-color, rgba(224, 224, 224, 0.56)); margin: 0 2px; border-radius: 6px; color: var(--text-primary, #000000);',
                        ],
                        'disabledPageCssClass' => 'page-link disabled',
                        'disabledListItemSubTagOptions' => [
                            'style' => 'color: var(--text-secondary, rgba(0, 0, 0, 0.6));'
                        ],
                        'activePageCssClass' => 'active',
                    ]);
                    ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const radioInputs = document.querySelectorAll('input[type="radio"]');
        radioInputs.forEach(radio => {
            radio.addEventListener('focus', function() {
                this.style.outline = '2px solid #588157';
                this.style.outlineOffset = '2px';
            });
            
            radio.addEventListener('blur', function() {
                this.style.outline = 'none';
            });
        });
        
        const adminRadios = document.querySelectorAll('input[value="1"]');
        adminRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                const userId = this.id.split('_')[1];
                if (this.checked && !confirm('Вы уверены, что хотите назначить этого пользователя администратором?')) {
                    const form = this.closest('form');
                    const previousChecked = form.querySelector('input[type="radio"]:checked');
                    if (previousChecked) {
                        previousChecked.checked = true;
                    }
                    this.checked = false;
                }
            });
        });
    });
</script>