<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$dbPath = __DIR__ . '/api/max.db';
try {
    $db = new PDO('sqlite:' . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("CREATE TABLE IF NOT EXISTS activations (
        code TEXT PRIMARY KEY,
        user TEXT,
        whatsapp TEXT,
        status TEXT,
        expiration_date TEXT,
        id_dispositivo TEXT
    )");
    
    // Criar diretório para os JSONs de aplicativos individuais se não existir
    $appsIndividualDir = __DIR__ . '/api/apps_individual';
    if (!file_exists($appsIndividualDir)) {
        mkdir($appsIndividualDir, 0755, true);
    }
} catch (PDOException $e) {
    error_log("Database connection error: " . $e->getMessage());
    die("❌ Erro ao conectar ao banco de dados: " . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');

    try {
        $action = $_POST['action'] ?? null;
        $code = isset($_POST['code']) ? trim($_POST['code']) : null;
        $user = isset($_POST['user']) ? trim($_POST['user']) : null;
        $whatsapp = isset($_POST['whatsapp']) ? trim($_POST['whatsapp']) : null;
        $status = isset($_POST['status']) ? trim($_POST['status']) : null;
        $expiration_date = isset($_POST['expiration_date']) ? trim($_POST['expiration_date']) : null;
        $id_dispositivo = isset($_POST['id_dispositivo']) ? trim($_POST['id_dispositivo']) : null;
        $original_code = isset($_POST['original_code']) ? trim($_POST['original_code']) : null;
        $apps = isset($_POST['apps']) ? json_decode($_POST['apps'], true) : [];

        if ($action === 'add') {
            $stmt_check = $db->prepare("SELECT COUNT(*) FROM activations WHERE code = ?");
            $stmt_check->execute([$code]);
            if ($stmt_check->fetchColumn() > 0) {
                echo json_encode(['status' => 'error', 'message' => '❌ Erro: Código de ativação já existe! Escolha um código diferente.']);
                exit;
            }

            $stmt = $db->prepare("INSERT INTO activations (code, user, whatsapp, status, expiration_date, id_dispositivo) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$code, $user, $whatsapp, $status, $expiration_date, $id_dispositivo]);
            
            // Salvar arquivo JSON com os aplicativos (mesmo se for array vazio)
            $jsonFile = __DIR__ . '/api/apps_individual/' . $code . '.json';
            file_put_contents($jsonFile, json_encode($apps, JSON_PRETTY_PRINT));
            
            echo json_encode(['status' => 'success', 'message' => '✅ Ativação adicionada com sucesso!']);
            exit;
            
        } elseif ($action === 'edit') {
            $stmt = $db->prepare("UPDATE activations SET code = ?, user = ?, whatsapp = ?, status = ?, expiration_date = ?, id_dispositivo = ? WHERE code = ?");
            $stmt->execute([$code, $user, $whatsapp, $status, $expiration_date, $id_dispositivo, $original_code]);
            
            // Salvar arquivo JSON com os aplicativos (mesmo se for array vazio)
            $jsonFile = __DIR__ . '/api/apps_individual/' . $code . '.json';
            file_put_contents($jsonFile, json_encode($apps, JSON_PRETTY_PRINT));
            
            // Se o código foi alterado, renomear o arquivo antigo
            if ($original_code !== $code) {
                $oldJsonFile = __DIR__ . '/api/apps_individual/' . $original_code . '.json';
                if (file_exists($oldJsonFile)) {
                    rename($oldJsonFile, $jsonFile);
                }
            }
            
            echo json_encode(['status' => 'success', 'message' => '🔄 Ativação atualizada com sucesso!']);
            exit;
            
        } elseif ($action === 'delete') {
            $stmt = $db->prepare("DELETE FROM activations WHERE code = ?");
            $stmt->execute([$code]);
            
            // Remover arquivo JSON associado
            $jsonFile = __DIR__ . '/api/apps_individual/' . $code . '.json';
            if (file_exists($jsonFile)) {
                unlink($jsonFile);
            }
            
            echo json_encode(['status' => 'success', 'message' => '🗑️ Ativação deletada com sucesso!']);
            exit;
            
        } elseif ($action === 'toggle_status') {
            $newStatus = $status === 'active' ? 'blocked' : 'active';
            $stmt = $db->prepare("UPDATE activations SET status = ? WHERE code = ?");
            $stmt->execute([$newStatus, $code]);

            echo json_encode([
                'status' => 'success',
                'message' => $newStatus === 'active' ? '✅ Ativação reativada com sucesso!' : '🚫 Ativação bloqueada com sucesso!',
                'newStatus' => $newStatus
            ]);
            exit;
        }

        echo json_encode(['status' => 'error', 'message' => '❌ Ação desconhecida.']);
        exit;

    } catch (Exception $e) {
        http_response_code(500);
        error_log("Erro no processamento AJAX: " . $e->getMessage());
        echo json_encode(['status' => 'error', 'message' => '❌ Erro no servidor: ' . $e->getMessage()]);
        exit;
    }
}

$activations = $db->query("SELECT * FROM activations ORDER BY expiration_date DESC")->fetchAll(PDO::FETCH_ASSOC);

$page_title = "🔑 Gerenciamento de Ativações";

$page_content = '
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .app-select-option {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 8px 12px;
    }
    .app-select-option img {
        width: 24px;
        height: 24px;
        border-radius: 4px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice {
        display: flex;
        align-items: center;
        gap: 6px;
        padding-left: 5px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
        position: relative;
        left: auto;
        margin-left: 5px;
    }
    .select2-container .select2-selection--multiple {
        min-height: 38px;
        max-height: 200px;
        overflow-y: auto;
    }
</style>

<div class="card">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="search_activations" class="form-control form-control-solid w-250px ps-12" placeholder="🔍 Pesquisar Ativações" />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-primary" onclick="openAddModal()">➕ Adicionar Ativação</button>
            </div>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="activations_table">
            <thead>
                <tr class="text-start text-gray-500 fw-bold fs-7 text-uppercase gs-0">
                    <th class="min-w-100px">🔑 Código</th>
                    <th class="min-w-100px">👤 Usuário</th>
                    <th class="min-w-100px">📞 WhatsApp</th>
                    <th class="min-w-100px">🔘 Status</th>
                    <th class="min-w-100px">📅 Data Expiração</th>
                    <th class="min-w-100px">📱 Dispositivo</th>
                    <th class="min-w-100px">🛠️ Ações</th>
                </tr>
            </thead>
            <tbody id="activations_table_body" class="fw-semibold text-gray-600">
';

foreach ($activations as $activation) {
    $statusClass = $activation['status'] === 'active' ? 'badge-light-success' : 'badge-light-danger';
    $statusText = $activation['status'] === 'active' ? '✅ Ativo' : '🚫 Bloqueado';
    $expirationDateDisplay = $activation['expiration_date'] ? date('d/m/Y', strtotime($activation['expiration_date'])) : 'N/A';
    $expirationDateForEdit = $activation['expiration_date'] ? date('Y-m-d', strtotime($activation['expiration_date'])) : '';
    $actionText = $activation['status'] === 'active' ? '🚫 Bloquear' : '✅ Reativar';

    $page_content .= "<tr data-code='{$activation['code']}'>
        <td>{$activation['code']}</td>
        <td>{$activation['user']}</td>
        <td>{$activation['whatsapp']}</td>
        <td>
            <span class='badge {$statusClass}'>{$statusText}</span>
        </td>
        <td>{$expirationDateDisplay}</td>
        <td>{$activation['id_dispositivo']}</td>
        <td>
            <button class='btn btn-sm btn-light-primary' onclick=\"editActivation('{$activation['code']}', '{$activation['user']}', '{$activation['whatsapp']}', '{$activation['status']}', '{$expirationDateForEdit}', '{$activation['id_dispositivo']}')\">✏️ Editar</button>
            <button class='btn btn-sm " . ($activation['status'] === 'active' ? 'btn-light-danger' : 'btn-light-success') . "' onclick=\"toggleStatus('{$activation['code']}', '{$activation['status']}', this)\">{$actionText}</button>
            <button class='btn btn-sm btn-light-danger' onclick=\"deleteActivation('{$activation['code']}', '{$activation['user']}')\">🗑️ Excluir</button>
        </td>
    </tr>";
}

$page_content .= '
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="activation_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-650px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title" class="fw-bold">➕ Adicionar Ativação</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="activation_form">
                    <input type="hidden" id="activation_original_code">
                    <div class="mb-7">
                        <label for="activation_code_input" class="fs-6 fw-semibold mb-2">🔑 Código de Ativação</label>
                        <input type="text" class="form-control" id="activation_code_input" placeholder="Digite o código" required>
                    </div>
                    <div class="mb-7">
                        <label for="activation_user" class="fs-6 fw-semibold mb-2">👤 Usuário</label>
                        <input type="text" class="form-control" id="activation_user" placeholder="Digite o nome do usuário">
                    </div>
                    <div class="mb-7">
                        <label for="activation_whatsapp" class="fs-6 fw-semibold mb-2">📱 WhatsApp</label>
                        <input type="text" class="form-control" id="activation_whatsapp" placeholder="Digite o número com DDD (ex: 11987654321)">
                    </div>
                    <div class="mb-7">
                        <label for="activation_status" class="fs-6 fw-semibold mb-2">🔘 Status</label>
                        <select class="form-select" id="activation_status">
                            <option value="active">✅ Ativo</option>
                            <option value="blocked">🚫 Bloqueado</option>
                        </select>
                    </div>
                    <div class="mb-7">
                        <label for="activation_expiration" class="fs-6 fw-semibold mb-2">📅 Data de Expiração</label>
                        <input type="date" class="form-control" id="activation_expiration">
                    </div>
                    <div class="mb-7">
                        <label for="activation_device" class="fs-6 fw-semibold mb-2">📱 ID do Dispositivo</label>
                        <input type="text" class="form-control" id="activation_device" placeholder="Digite o ID do dispositivo">
                    </div>
                    <div class="mb-7">
                        <label for="activation_apps" class="fs-6 fw-semibold mb-2">📱 Aplicativos Permitidos</label>
                        <select class="form-select" id="activation_apps" multiple="multiple">
';

// Buscar aplicativos ativos do banco de dados
$apps = $db->query("SELECT * FROM apps WHERE active = 1")->fetchAll(PDO::FETCH_ASSOC);
foreach ($apps as $app) {
    $page_content .= '<option value="' . htmlspecialchars(json_encode([
        'name' => $app['name'],
        'package' => $app['package'],
        'apk_url' => $app['apk_url'],
        'icon_url' => $app['icon_url'],
        'active' => $app['active']
    ]), ENT_QUOTES) . '">' . htmlspecialchars($app['name'], ENT_QUOTES) . '</option>';
}

$page_content .= '
                        </select>
                        <div class="d-flex gap-2 mt-2">
                            <button type="button" class="btn btn-sm btn-secondary" onclick="deselectAllApps()">🗑️ Limpar Seleção</button>
                            <button type="button" class="btn btn-sm btn-primary" onclick="selectAllApps()">✅ Selecionar Todos</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">❌ Cancelar</button>
                <button type="button" class="btn btn-primary" onclick="saveActivation()">💾 Salvar</button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    let activationsTable = $('#activations_table').DataTable({
        searching: true,
        paging: true,
        ordering: true,
        info: true,
        responsive: false,
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/pt-BR.json'
        }
    });

    document.getElementById("search_activations").addEventListener("input", function() {
        activationsTable.search(this.value).draw();
    });

    // Função para formatar os itens no select
    function formatAppOption(app) {
        if (!app.id) return app.text;
        
        try {
            const appData = JSON.parse(app.id);
            const $option = $(
                `<div class="app-select-option">
                    <img src="${appData.icon_url || ''}" onerror="this.style.display='none'" />
                    <span>${appData.name || app.text}</span>
                </div>`
            );
            return $option;
        } catch (e) {
            console.error('Error parsing app data:', e);
            return app.text;
        }
    }

    // Inicializar o select2 com ícones
    function initAppSelect() {
        $('#activation_apps').select2({
            templateResult: formatAppOption,
            templateSelection: formatAppOption,
            escapeMarkup: function(m) { return m; },
            width: '100%'
        });
        
        // Forçar redesenho para exibir os ícones
        $('#activation_apps').trigger('change.select2');
    }

    // Funções para selecionar/deselecionar todos
    window.selectAllApps = function() {
        $('#activation_apps option').prop('selected', true);
        $('#activation_apps').trigger('change');
    };

    window.deselectAllApps = function() {
        $('#activation_apps option').prop('selected', false);
        $('#activation_apps').trigger('change');
    };

    // Carregar aplicativos selecionados
    window.loadSelectedApps = function(code) {
        fetch(`api/apps_individual/${code}.json`)
            .then(response => {
                if (!response.ok) return [];
                return response.json();
            })
            .then(apps => {
                const select = $('#activation_apps');
                select.val(null).trigger('change');
                
                if (apps && apps.length > 0) {
                    const selectedValues = [];
                    select.find('option').each(function() {
                        try {
                            const optionData = JSON.parse(this.value);
                            if (apps.some(app => app.package === optionData.package)) {
                                selectedValues.push(this.value);
                            }
                        } catch (e) {}
                    });
                    select.val(selectedValues).trigger('change');
                }
            })
            .catch(error => {
                console.error('Erro ao carregar aplicativos:', error);
            });
    };

    // Inicializar quando o modal abrir
    document.getElementById('activation_modal').addEventListener('shown.bs.modal', function() {
        initAppSelect();
    });

    window.openAddModal = function() {
        document.getElementById('modal_title').textContent = '➕ Adicionar Ativação';
        document.getElementById('activation_original_code').value = '';
        document.getElementById('activation_code_input').value = '';
        document.getElementById('activation_user').value = '';
        document.getElementById('activation_whatsapp').value = '';
        document.getElementById('activation_status').value = 'active';
        document.getElementById('activation_expiration').value = '';
        document.getElementById('activation_device').value = '';
        document.getElementById('activation_code_input').disabled = false;
        
        // Limpar seleções de aplicativos
        $('#activation_apps').val(null).trigger('change');
        
        $('#activation_modal').modal('show');
    };

    window.editActivation = function(code, user, whatsapp, status, expiration_date, id_dispositivo) {
        document.getElementById('modal_title').textContent = '✏️ Editar Ativação';
        document.getElementById('activation_original_code').value = code;
        document.getElementById('activation_code_input').value = code;
        document.getElementById('activation_user').value = user;
        document.getElementById('activation_whatsapp').value = whatsapp;
        document.getElementById('activation_status').value = status;
        document.getElementById('activation_expiration').value = expiration_date;
        document.getElementById('activation_device').value = id_dispositivo;
        document.getElementById('activation_code_input').disabled = false;
        
        // Carregar aplicativos selecionados
        loadSelectedApps(code);
        
        $('#activation_modal').modal('show');
    };

    window.saveActivation = function() {
        const originalCode = document.getElementById('activation_original_code').value;
        const newCode = document.getElementById('activation_code_input').value.trim();
        const user = document.getElementById('activation_user').value.trim();
        const whatsapp = document.getElementById('activation_whatsapp').value.trim();
        const status = document.getElementById('activation_status').value;
        const expiration_date = document.getElementById('activation_expiration').value;
        const id_dispositivo = document.getElementById('activation_device').value.trim();
        
        // Obter aplicativos selecionados
        const selectedApps = [];
        const selectedOptions = $('#activation_apps').select2('data');
        selectedOptions.forEach(option => {
            try {
                selectedApps.push(JSON.parse(option.id));
            } catch (e) {
                console.error('Erro ao parsear app:', e);
            }
        });

        if (!newCode) {
            Swal.fire({
                icon: 'error',
                title: '❌ Erro',
                text: 'Código de ativação é obrigatório!',
            });
            return;
        }

        const saveBtn = document.querySelector('#activation_modal .btn-primary');
        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Salvando...';
        saveBtn.disabled = true;

        const action = originalCode ? 'edit' : 'add';
        const formData = new FormData();
        formData.append('action', action);
        formData.append('code', newCode);
        formData.append('user', user);
        formData.append('whatsapp', whatsapp);
        formData.append('status', status);
        formData.append('expiration_date', expiration_date);
        formData.append('id_dispositivo', id_dispositivo);
        formData.append('apps', JSON.stringify(selectedApps));

        if (originalCode) {
            formData.append('original_code', originalCode);
        }

        fetch('mac.php', {
            method: 'POST',
            body: formData,
        })
        .then(response => {
            if (!response.ok) {
                return response.json().catch(() => {
                    throw new Error(`Erro HTTP! Status: ${response.status}`);
                }).then(errorData => {
                    throw new Error(errorData.message || `Erro HTTP! Status: ${response.status}`);
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                Swal.fire({
                    icon: 'success',
                    title: '✅ Sucesso!',
                    text: data.message,
                }).then(() => {
                    $('#activation_modal').modal('hide');
                    location.reload();
                });
            } else {
                throw new Error(data.message || 'Erro desconhecido');
            }
        })
        .catch(error => {
            console.error('Erro na requisição:', error);
            Swal.fire({
                icon: 'error',
                title: '❌ Erro',
                text: error.message || 'Falha ao salvar. Verifique o console para detalhes.',
            });
        })
        .finally(() => {
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
        });
    };

    window.deleteActivation = function(code, user) {
        Swal.fire({
            title: '⚠️ Tem certeza?',
            text: `Você está prestes a excluir a ativação: ${code} (${user})`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: '🗑️ Sim, excluir!',
            cancelButtonText: '❌ Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('mac.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'delete',
                        code: code,
                    }),
                })
                .then(response => {
                    if (!response.ok) {
                         return response.json().catch(() => {
                            throw new Error(`Erro HTTP! Status: ${response.status}`);
                        }).then(errorData => {
                            throw new Error(errorData.message || `Erro HTTP! Status: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: '🗑️ Excluído!',
                            text: data.message,
                        }).then(() => location.reload());
                    } else {
                        throw new Error(data.message || 'Erro ao excluir');
                    }
                })
                .catch(error => {
                    console.error('Erro na requisição de exclusão:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '❌ Erro',
                        text: error.message || 'Falha ao excluir. Verifique o console para detalhes.',
                    });
                });
            }
        });
    };

    window.toggleStatus = function(code, currentStatus, button) {
        const newStatus = currentStatus === 'active' ? 'blocked' : 'active';
        const buttonText = newStatus === 'active' ? '✅ Reativar' : '🚫 Bloquear';
        const buttonClass = newStatus === 'active' ? 'btn-light-success' : 'btn-light-danger';

        button.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
        button.disabled = true;

        fetch('mac.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'toggle_status',
                code: code,
                status: currentStatus
            }),
        })
        .then(response => {
            if (!response.ok) {
                return response.json().catch(() => {
                    throw new Error(`Erro HTTP! Status: ${response.status}`);
                }).then(errorData => {
                    throw new Error(errorData.message || `Erro HTTP! Status: ${response.status}`);
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.status !== 'success') {
                throw new Error(data.message || 'Falha ao alterar status');
            }
            location.reload();
        })
        .catch(error => {
            console.error('Erro na requisição de toggle status:', error);
            Swal.fire({
                icon: 'error',
                title: '❌ Erro',
                text: error.message || 'Falha ao alterar status',
            });
            button.disabled = false;
            button.innerHTML = buttonText;
            button.className = `btn btn-sm ${buttonClass}`;
        });
    };
});
</script>