<?php
use EasyChat\View\HtmxFragmentRenderer;
use EasyChat\View\OperatorFragments;

$operator_fragments = new OperatorFragments();
?>
<?php echo easychat_style_tag('css/views/operator.css'); ?>

<div class="card border-0 shadow-sm rounded-4 p-4 operators-page" style="background: #ffffff;">
    <input type="hidden" id="operator-csrf" name="csrf_token" value="<?php echo OperatorFragments::e($easychat_csrf_token ?? ''); ?>">
    <div class="d-flex flex-column flex-sm-row justify-content-between align-items-start align-items-sm-center mb-4 gap-3">
        <div>
            <h4 class="fw-bold text-dark mb-1" style="font-family: 'Outfit', sans-serif;"><i class="fa fa-users me-2 text-primary"></i> Операторы</h4>
            <p class="text-muted small mb-0">Управление учетными записями менеджеров и их правами доступа</p>
        </div>
        <button type="button" class="btn btn-primary easychat-admin-primary-action px-4 py-2 d-flex align-items-center btn-add-operator">
            <i class="fa fa-plus me-2"></i> Добавить оператора
        </button>
    </div>

    <?php echo $operator_fragments->alert('success', 'Оператор сохранён.', true); ?>
    <?php echo $operator_fragments->alert('error', '', true); ?>

    <section class="android-update-admin-summary" data-android-update-admin-summary hidden aria-labelledby="android-update-admin-title">
        <div class="android-update-admin-icon" aria-hidden="true"><i class="fa fa-android"></i></div>
        <div>
            <h5 id="android-update-admin-title">Версии Android у операторов</h5>
            <p data-android-update-admin-text></p>
        </div>
        <a data-android-update-admin-link href="https://www.rustore.ru/catalog/app/ru.liveopencart.easychat" target="_blank" rel="noopener noreferrer">Открыть RuStore</a>
    </section>

    <!-- Operators Table -->
    <div class="table-responsive operators-table-wrap">
        <table class="table align-middle table-hover operators-table" style="border-color: #f1f5f9;">
            <thead class="table-light text-muted small uppercase" style="background: #f8fafc;">
                <tr>
                    <th class="ps-4 py-3" style="border-radius: 10px 0 0 10px;">Аватар</th>
                    <th class="py-3">Логин</th>
                    <th class="py-3">Имя</th>
                    <th class="py-3">Роль</th>
                    <th class="py-3">Активность</th>
                    <th class="py-3">Устройства</th>
                    <th class="py-3">AI</th>
                    <th class="py-3">IP адрес</th>
                    <th class="py-3">Аккаунт</th>
                    <th class="pe-4 py-3 text-end" style="border-radius: 0 10px 10px 0;">Действия</th>
                </tr>
            </thead>
            <tbody id="operators-table-body">
                <?php echo $operator_fragments->rows($operators); ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="deviceActionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered device-action-dialog">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header border-0">
                <div>
                    <span class="device-center-eyebrow"><i class="fa fa-mobile"></i> Устройство</span>
                    <h5 class="modal-title" id="device-action-title">Название устройства</h5>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="device-action-id" value="">
                <input type="hidden" id="device-action-kind" value="">
                <div id="device-rename-field">
                    <label for="device-action-name" class="form-label">Как показывать этот телефон</label>
                    <input type="text" class="form-control" id="device-action-name" maxlength="120" autocomplete="off">
                    <small>Например: «HONOR 50 — рабочий»</small>
                </div>
                <div id="device-revoke-copy" class="d-none">
                    <div class="device-revoke-warning"><i class="fa fa-shield"></i><p>Приложение сразу потеряет доступ к чатам и новым SMS-задачам. История отправок сохранится.</p></div>
                </div>
                <div class="device-action-error d-none" id="device-action-error" role="alert"></div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Отмена</button>
                <button type="button" class="btn btn-primary" id="device-action-confirm">Сохранить</button>
            </div>
        </div>
    </div>
</div>

<div class="offcanvas offcanvas-end device-center-panel" tabindex="-1" id="deviceCenterPanel" aria-labelledby="device-center-title">
    <div class="offcanvas-header">
        <div>
            <span class="device-center-eyebrow"><i class="fa fa-shield" aria-hidden="true"></i> Безопасные подключения</span>
            <h5 class="offcanvas-title" id="device-center-title">Устройства</h5>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>
    </div>
    <div class="offcanvas-body" id="device-center-content" aria-live="polite">
        <div class="device-center-loading"><i class="fa fa-circle-o-notch fa-spin"></i><span>Загружаем устройства…</span></div>
    </div>
</div>

<div class="modal fade" id="smsDiagnosticsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable sms-diagnostics-dialog">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header border-0">
                <div>
                    <span class="sms-diagnostics-eyebrow"><i class="fa fa-shield" aria-hidden="true"></i> Контроль доставки</span>
                    <h5 class="modal-title">Диагностика SMS</h5>
                    <p>Путь сообщения от админки до оператора связи</p>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body" id="sms-diagnostics-content" aria-live="polite">
                <div class="sms-diagnostics-loading"><i class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></i><span>Загружаем события…</span></div>
            </div>
        </div>
    </div>
</div>

<!-- SMS DEVICE ACCESS MODAL -->
<div class="modal fade" id="smsPermissionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 420px;">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 16px; overflow: hidden;">
            <div style="height: 4px; background: linear-gradient(90deg, #ef4444, #f97316);"></div>
            <div class="modal-header border-0 bg-light p-4">
                <h5 class="modal-title fw-bold text-dark" style="font-family: 'Outfit', sans-serif;"><i class="fa fa-shield me-2 text-danger"></i>Отключить SMS-доступ?</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <p class="text-dark mb-2" id="sms-permission-modal-title">Отключить отправку SMS с этого телефона</p>
                <p class="text-muted small mb-0">EasyChat сразу перестанет выбирать этот телефон для новых SMS-задач. Android-разрешение на самом телефоне не меняется: при необходимости вы сможете запросить доступ повторно.</p>
            </div>
            <div class="modal-footer border-0 p-4 pt-0 d-flex justify-content-between">
                <button type="button" class="btn btn-outline-secondary px-4 py-2" data-bs-dismiss="modal" style="border-radius: 8px;">Оставить включенным</button>
                <button type="button" id="btn-confirm-sms-revoke" class="btn btn-danger px-4 py-2" style="border-radius: 8px;">
                    <i class="fa fa-power-off me-1"></i> Отключить
                </button>
            </div>
        </div>
    </div>
</div>

<!-- OPERATOR MODAL DIALOG -->
<div class="modal fade" id="operatorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable operator-profile-dialog">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 16px; overflow: hidden;">
            <!-- Glowing accent header -->
            <div style="height: 4px; background: linear-gradient(90deg, #6366f1, #a855f7);"></div>
            
            <div class="modal-header border-0 bg-light p-4">
                <h5 class="modal-title fw-bold text-dark" id="modal-title" style="font-family: 'Outfit', sans-serif;">Управление оператором</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            
            <div class="modal-body p-4">
                
                <!-- Avatar Upload Block (Instantly active for existing operators) -->
                <div id="avatar-upload-block" class="d-none text-center mb-4 p-3 bg-light rounded-3">
                    <label class="form-label text-muted small d-block">Фото профиля (аватар)</label>
                    <div class="position-relative d-inline-block">
                        <img id="modal-avatar-preview" src="" alt="Avatar" class="rounded-circle border shadow-sm" style="width: 80px; height: 80px; object-fit: cover;">
                        <div id="modal-avatar-placeholder" class="rounded-circle d-flex align-items-center justify-content-center border shadow-sm fw-semibold" style="width: 80px; height: 80px; font-size: 28px; background-color: #6366f1; color: #ffffff;"></div>
                        <div id="avatar-loader" class="position-absolute top-50 start-50 translate-middle d-none">
                            <i class="fa fa-circle-o-notch fa-spin text-white fa-lg"></i>
                        </div>
                    </div>
                    <div class="mt-2">
                        <input type="file" id="avatar-file-input" class="d-none" accept="image/*">
                        <button type="button" id="btn-avatar-pick" class="btn btn-outline-primary btn-sm px-3" style="border-radius: 6px;">
                            <i class="fa fa-camera me-1"></i> Сменить фото
                        </button>
                    </div>
                    <div id="avatar-upload-status" class="avatar-upload-status small mt-2 d-none" aria-live="polite"></div>
                </div>

                <!-- Fields Form -->
                <form id="operator-form" autocomplete="off" method="post" action="index.php?route=operator/save" hx-post="index.php?route=operator/save" hx-target="#operators-table-body" hx-swap="<?php echo OperatorFragments::e(HtmxFragmentRenderer::operatorListSwap()); ?>" hx-sync="this:replace" hx-indicator="#btn-save-operator">
                    <input type="hidden" name="id" id="op-id" value="0">
                    <input type="hidden" name="csrf_token" value="<?php echo OperatorFragments::e($easychat_csrf_token ?? ''); ?>">
                    
                    <div class="mb-3" id="username-group">
                        <label class="form-label text-muted small">Логин (для входа)</label>
                        <input type="text" name="username" id="op-username" class="form-control" placeholder="Например, ivan_operator" required style="border-radius: 8px;">
                    </div>

                    <div class="mb-3" id="name-group">
                        <label class="form-label text-muted small">Отображаемое имя (клиентам)</label>
                        <input type="text" name="name" id="op-name" class="form-control" placeholder="Например, Иван" required style="border-radius: 8px;">
                    </div>

                    <div class="mb-3" id="password-group">
                        <label class="form-label text-muted small" id="password-label">Пароль</label>
                        <input type="password" name="password" id="op-password" class="form-control" placeholder="Введите надежную парольную фразу" autocomplete="new-password" minlength="15" maxlength="128" style="border-radius: 8px;">
                        <span class="text-muted" style="font-size: 11px;" id="password-help">Не менее 15 символов.</span>
                    </div>

                    <div class="operator-permissions-card mb-3" id="permission-group">
                        <div class="operator-permissions-title">
                            <i class="fa fa-shield" aria-hidden="true"></i>
                            <span>
                                <strong>Права оператора</strong>
                                <small>Выдавайте только те действия, которые нужны сотруднику.</small>
                            </span>
                        </div>
                        <div class="form-check form-switch">
                            <input type="checkbox" name="permission_manage_chat_assignments" id="op-permission-assignments" class="form-check-input" value="1">
                            <label class="form-check-label" for="op-permission-assignments">
                                <strong>Назначать других операторов</strong>
                                <small>Сотрудник сможет добавлять и снимать коллег в карточке диалога.</small>
                            </label>
                        </div>
                        <div class="form-check form-switch">
                            <input type="checkbox" name="permission_delete_chats" id="op-permission-delete" class="form-check-input" value="1">
                            <label class="form-check-label" for="op-permission-delete">
                                <strong>Удалять диалоги</strong>
                                <small>Удаление остаётся необратимым действием с подтверждением.</small>
                            </label>
                        </div>
                    </div>

                    <div class="mb-3" id="ai-suggestions-group">
                        <label class="form-label text-muted small">AI-подсказки ответов</label>
                        <select name="ai_suggestions_mode" id="op-ai-suggestions-mode" class="form-select" style="border-radius: 8px;">
                            <option value="inherit">Наследовать общую настройку</option>
                            <option value="on">Включить для оператора</option>
                            <option value="off">Выключить для оператора</option>
                        </select>
                        <span class="text-muted" style="font-size: 11px;">ИИ только предлагает черновики. Отправка всегда остается за оператором.</span>
                    </div>

                    <div class="operator-widget-visibility mb-3" id="widget-visibility-group">
                        <input type="hidden" name="show_in_widget_header" value="0">
                        <div class="form-check form-switch">
                            <input type="checkbox" name="show_in_widget_header" id="op-show-in-widget-header" class="form-check-input" value="1" checked>
                            <label class="form-check-label" for="op-show-in-widget-header">
                                <span class="operator-widget-visibility-icon" aria-hidden="true"><i class="fa fa-eye"></i></span>
                                <span>
                                    <strong>Отображать в шапке виджета</strong>
                                    <small>Посетители увидят имя и аватар сотрудника, если общий показ операторов включён.</small>
                                </span>
                            </label>
                        </div>
                    </div>

                    <div class="mb-3" id="status-group">
                        <label class="form-label text-muted small">Статус</label>
                        <select name="status" id="op-status" class="form-select" style="border-radius: 8px;">
                            <option value="1">Активен</option>
                            <option value="0">Отключен</option>
                        </select>
                    </div>

                    <div class="modal-footer border-0 p-0 mt-4 d-flex justify-content-between">
                        <button type="button" class="btn btn-outline-secondary px-4 py-2" data-bs-dismiss="modal" style="border-radius: 8px;">Отмена</button>
                        <button type="submit" id="btn-save-operator" class="btn btn-primary px-4 py-2" style="border-radius: 8px; background: linear-gradient(135deg, #6366f1, #a855f7) !important; border: none;">Сохранить</button>
                    </div>
                </form>
                
                <?php echo $operator_fragments->modalAlert('', true); ?>
            </div>
        </div>
    </div>
</div>

<!-- QR CODE MODAL FOR MOBILE APP LOGIN -->
<div class="modal fade" id="qrModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 380px;">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 16px; overflow: hidden;">
            <div style="height: 4px; background: linear-gradient(90deg, #6366f1, #a855f7);"></div>
            <div class="modal-header border-0 bg-light p-4">
                <h5 class="modal-title fw-bold text-dark" style="font-family: 'Outfit', sans-serif;"><i class="fa fa-qrcode me-2 text-indigo"></i>Вход по QR-коду</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4 text-center">
                <p class="text-muted small mb-3">Сканируйте код из приложения, чтобы подключить телефон для: <br><b id="qr-manager-name" class="text-dark"></b></p>
                <div id="qr-code-frame" class="d-inline-flex align-items-center justify-content-center p-3 border rounded-4 bg-white shadow-sm mb-3" style="width: 254px; height: 254px;">
                    <div id="qr-code-loading" class="text-muted small"><i class="fa fa-circle-o-notch fa-spin me-1"></i> Создаём защищённый QR…</div>
                    <img id="qr-code-img" src="" alt="QR для подключения устройства" class="img-fluid d-none" style="width: 220px; height: 220px;">
                </div>
                <div id="qr-code-status" class="small text-muted mb-3" role="status"><i class="fa fa-shield me-1"></i> Одноразовый код действует 10 минут</div>
                <button type="button" class="btn btn-light w-100" data-bs-dismiss="modal" style="border-radius: 8px;">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<!-- CROP MODAL DIALOG -->
<div class="modal fade" id="cropModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 380px;">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 16px; overflow: hidden;">
            <div style="height: 4px; background: linear-gradient(90deg, #6366f1, #a855f7);"></div>
            <div class="modal-header border-0 bg-light p-4">
                <h5 class="modal-title fw-bold text-dark" style="font-family: 'Outfit', sans-serif;"><i class="fa fa-crop me-2 text-indigo"></i>Обрезка аватарки</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4 text-center">
                <p class="text-muted small mb-3">Перетаскивайте изображение внутри круга и настраивайте масштаб ползунком снизу</p>
                
                <!-- Окно просмотра кроппера -->
                <div class="position-relative overflow-hidden mx-auto bg-light border rounded-circle shadow-sm" 
                     id="crop-container"
                     style="width: 200px; height: 200px; cursor: move; user-select: none; touch-action: none;">
                    <img id="crop-image" src="" style="position: absolute; top: 0; left: 0; transform-origin: top left; pointer-events: none;">
                </div>
                
                <!-- Ползунок масштабирования -->
                <div class="mt-4 px-2">
                    <div class="d-flex align-items-center gap-2">
                        <i class="fa fa-picture-o text-muted small"></i>
                        <input type="range" id="crop-zoom" class="form-range" min="1" max="3" step="0.01" value="1">
                        <i class="fa fa-picture-o text-muted fa-lg"></i>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 p-4 pt-0 d-flex justify-content-between">
                <button type="button" class="btn btn-outline-secondary px-4 py-2" data-bs-dismiss="modal" style="border-radius: 8px;">Отмена</button>
                <button type="button" id="btn-crop-apply" class="btn btn-primary px-4 py-2" style="border-radius: 8px; background: linear-gradient(135deg, #6366f1, #a855f7) !important; border: none;">Применить</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
window.EasyChatOperatorConfig = {
    httpAvatars: '<?php echo HTTP_AVATARS; ?>',
    focusAdminPassword: <?php echo (!empty(\EasyChat\Library\RequestContext::get()['focus_admin_password'])) ? 'true' : 'false'; ?>
};
</script>
<?php echo easychat_script_tag('js/qrcode-generator.js'); ?>
<?php echo easychat_script_tag('js/views/operator.js'); ?>
