<?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
    )");
} 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;

        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]);
            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]);
            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]);
            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 = '
<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>
                </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>
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();
    });

    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;
        $('#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;
        $('#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();

        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);

        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>