<?php
ob_start();
require_once __DIR__ . '/includes/header.php';

$message = '';
$message_type = '';
$editing_id = null;
$editing_data = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update' && isset($_POST['id'])) {
        $id = (int)$_POST['id'];
        $name = str_in($_POST['name'] ?? '');
        $m3u_url = str_in($_POST['m3u_url'] ?? '');
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        $result = update_client($id, $name, $m3u_url, $is_active);

        if ($result['ok']) {
            ob_end_clean();
            header('Location: list_dns.php?success=updated');
            exit;
        } else {
            $message = $result['message'];
            $message_type = 'error';
        }
    }
}

if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $id = (int)($_GET['id'] ?? 0);

    switch ($action) {
        case 'deactivate':
            if (deactivate_client_by_id($id)) {
                ob_end_clean();
                header('Location: list_dns.php?success=deactivated');
                exit;
            }
            break;

        case 'activate':
            if (activate_client_by_id($id)) {
                ob_end_clean();
                header('Location: list_dns.php?success=activated');
                exit;
            }
            break;

        case 'delete':
            if (delete_client_by_id($id)) {
                ob_end_clean();
                header('Location: list_dns.php?success=deleted');
                exit;
            }
            break;

        case 'edit':
            $editing_data = get_client_by_id($id);
            if ($editing_data) {
                $editing_id = $id;
            } else {
                $message = 'Cliente não encontrado.';
                $message_type = 'error';
            }
            break;
    }
}

if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case 'updated':
            $message = 'Cliente atualizado com sucesso!';
            break;
        case 'deactivated':
            $message = 'Cliente desativado com sucesso!';
            break;
        case 'activated':
            $message = 'Cliente ativado com sucesso!';
            break;
        case 'deleted':
            $message = 'Cliente excluído permanentemente!';
            break;
    }
    $message_type = 'success';
}

if (!empty($_GET['cards_error'])) {
    $message = (string)$_GET['cards_error'];
    $message_type = 'error';
}

$clients = get_clients();
?>

<style>
    .page-header {
        margin-bottom: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
    }
    
    .page-header h1 {
        font-size: 28px;
        margin: 0;
        background: var(--primary-bg);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .add-btn {
        background: var(--primary-bg);
        color: #fff;
        padding: 10px 20px;
        border-radius: 6px;
        text-decoration: none;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.2s ease;
        display: inline-block;
    }
    
    .add-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }

    .page-header-actions {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .add-btn-outline {
        background: rgba(168, 85, 247, 0.12);
        border: 1px solid rgba(168, 85, 247, 0.55);
        color: #d7c7f6;
    }

    .add-btn-outline:hover {
        background: rgba(168, 85, 247, 0.22);
        color: #fff;
    }
    
    .alert {
        padding: 15px 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        animation: slideIn 0.3s ease;
    }
    
    .alert-success {
        background: rgba(46, 204, 113, 0.2);
        border: 1px solid #2ecc71;
        color: #2ecc71;
    }
    
    .alert-error {
        background: rgba(231, 76, 60, 0.2);
        border: 1px solid #e74c3c;
        color: #e74c3c;
    }
    
    .edit-form {
        background: #1a1a1a;
        padding: 25px;
        border-radius: 12px;
        border: 2px solid var(--primary-bg);
        margin-bottom: 25px;
        animation: slideDown 0.3s ease;
    }
    
    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .edit-form h2 {
        font-size: 18px;
        margin-bottom: 20px;
        color: #fff;
    }
    
    .form-grid {
        display: grid;
        grid-template-columns: 2fr 3fr 100px 100px;
        gap: 15px;
        margin-bottom: 15px;
    }
    
    .form-group {
        display: flex;
        flex-direction: column;
    }
    
    .form-group label {
        margin-bottom: 6px;
        color: #fff;
        font-weight: 500;
        font-size: 13px;
    }
    
    .form-group input {
        padding: 10px 12px;
        background: #111;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
    }
    
    .form-group input:focus {
        outline: none;
        border-color: var(--primary-bg);
    }
    
    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: 28px;
    }
    
    .checkbox-group input[type="checkbox"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }
    
    .form-actions {
        display: flex;
        gap: 10px;
    }
    
    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-block;
    }
    
    .btn-primary {
        background: var(--primary-bg);
        color: #fff;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
    
    .btn-secondary {
        background: #555;
        color: #fff;
    }
    
    .btn-secondary:hover {
        background: #666;
    }
    
    .table-container {
        background: var(--card-bg);
        border-radius: 12px;
        border: 1px solid var(--border-color);
        overflow-x: auto;
        overflow-y: hidden;
        max-width: 100%;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: thin;
        scrollbar-color: rgba(168, 85, 247, 0.85) rgba(255, 255, 255, 0.06);
        box-shadow: inset -18px 0 24px rgba(115, 48, 255, 0.10);
    }

    .table-container::-webkit-scrollbar {
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.06);
        border-radius: 50px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-bg);
        border-radius: 50px;
    }

    .code-cell {
        font-family: 'Courier New', monospace;
        font-weight: 700;
        letter-spacing: 2px;
        color: #d7c7f6;
        white-space: nowrap;
    }

    .plan-badge-table {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 999px;
        font-size: 11px;
        font-weight: 700;
        background: rgba(168, 85, 247, 0.16);
        border: 1px solid rgba(168, 85, 247, 0.35);
        color: #e9ddff;
        white-space: nowrap;
    }

    .mobile-scroll-tip {
        display: none;
        margin: 0 0 10px;
        padding: 10px 14px;
        border-radius: 12px;
        color: #e9ddff;
        font-size: 13px;
        border: 1px solid rgba(168, 85, 247, 0.35);
        background: rgba(76, 29, 149, 0.32);
    }
    
    .dns-table {
        width: 100%;
        min-width: 980px;
        border-collapse: collapse;
    }
    
    .dns-table thead {
        background: #0a0a0a;
    }
    
    .dns-table th {
        padding: 15px;
        text-align: left;
        font-size: 14px;
        font-weight: 600;
        color: #fff;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .dns-table td {
        padding: 15px;
        font-size: 14px;
        color: #ccc;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    }
    
    .dns-table tbody tr {
        transition: background 0.2s ease;
    }
    
    .dns-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02);
    }
    
    .dns-table tbody tr.inactive {
        opacity: 0.6;
    }
    
    .dns-table tbody tr.editing {
        background: rgba(192, 57, 43, 0.1);
        border-left: 3px solid var(--primary-bg);
    }
    
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }
    
    .status-active {
        background: rgba(46, 204, 113, 0.2);
        color: #2ecc71;
    }
    
    .status-inactive {
        background: rgba(231, 76, 60, 0.2);
        color: #e74c3c;
    }
    
    .action-btns {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
    }
    
    .action-btn {
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 12px;
        text-decoration: none;
        display: inline-block;
        transition: all 0.2s ease;
        border: 1px solid;
        white-space: nowrap;
    }
    
    .btn-edit {
        background: rgba(52, 152, 219, 0.1);
        color: #3498db;
        border-color: #3498db;
    }
    
    .btn-edit:hover {
        background: #3498db;
        color: #fff;
    }
    
    .btn-activate {
        background: rgba(46, 204, 113, 0.1);
        color: #2ecc71;
        border-color: #2ecc71;
    }
    
    .btn-activate:hover {
        background: #2ecc71;
        color: #fff;
    }
    
    .btn-deactivate {
        background: rgba(243, 156, 18, 0.1);
        color: #f39c12;
        border-color: #f39c12;
    }
    
    .btn-deactivate:hover {
        background: #f39c12;
        color: #fff;
    }
    
    .btn-delete {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
        border-color: #e74c3c;
    }
    
    .btn-delete:hover {
        background: #e74c3c;
        color: #fff;
    }

    .btn-card {
        background: rgba(168, 85, 247, 0.12);
        color: #c084fc;
        border-color: #a855f7;
        cursor: pointer;
        font-family: inherit;
    }

    .btn-card:hover {
        background: #a855f7;
        color: #fff;
    }

    .card-modal {
        display: none;
        position: fixed;
        inset: 0;
        z-index: 9999;
        align-items: center;
        justify-content: center;
        padding: 20px;
    }

    .card-modal.open {
        display: flex;
    }

    .card-modal-backdrop {
        position: absolute;
        inset: 0;
        background: rgba(0, 0, 0, 0.72);
        backdrop-filter: blur(4px);
    }

    .card-modal-dialog {
        position: relative;
        z-index: 1;
        width: min(100%, 420px);
        background: #1a1a1a;
        border: 1px solid rgba(168, 85, 247, 0.45);
        border-radius: 16px;
        padding: 24px 22px 22px;
        box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
        animation: slideDown 0.25s ease;
    }

    .card-modal-close {
        position: absolute;
        top: 12px;
        right: 14px;
        width: 32px;
        height: 32px;
        border: none;
        border-radius: 8px;
        background: rgba(255, 255, 255, 0.08);
        color: #ccc;
        font-size: 22px;
        line-height: 1;
        cursor: pointer;
    }

    .card-modal-close:hover {
        background: rgba(255, 255, 255, 0.15);
        color: #fff;
    }

    .card-modal-dialog h3 {
        margin: 0 0 8px;
        color: #fff;
        font-size: 18px;
    }

    .card-modal-code {
        margin: 0 0 18px;
        text-align: center;
        font-size: 15px;
    }

    .card-modal-image-wrap {
        display: flex;
        justify-content: center;
        margin-bottom: 18px;
    }

    .card-modal-image-wrap img {
        width: min(100%, 320px);
        border-radius: 14px;
        box-shadow: 0 14px 36px rgba(0, 0, 0, 0.45);
        border: 1px solid rgba(255, 255, 255, 0.1);
    }

    .card-modal-actions {
        display: flex;
        gap: 10px;
        justify-content: center;
        flex-wrap: wrap;
    }
    
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #999;
    }
    
    .empty-state h3 {
        color: #fff;
        margin: 15px 0 10px;
    }
    
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .form-grid {
            grid-template-columns: 1fr;
        }
        
        .mobile-scroll-tip {
            display: block;
        }

        .table-container {
            border-radius: 14px;
            margin-left: -4px;
            margin-right: -4px;
        }
        
        .dns-table {
            min-width: 1000px;
            font-size: 12px;
        }
        
        .dns-table th,
        .dns-table td {
            padding: 10px 9px;
            white-space: nowrap;
        }

        .dns-table td:nth-child(2) a {
            display: inline-block;
            max-width: 330px;
            overflow: hidden;
            text-overflow: ellipsis;
            vertical-align: middle;
        }
        
        .action-btns {
            flex-direction: row;
            flex-wrap: nowrap;
            min-width: max-content;
        }
        
        .action-btn {
            width: auto;
            min-width: 78px;
            text-align: center;
            padding: 7px 10px;
        }
    }
</style>

<div class="page-header">
    <h1>📋 Lista de Clientes</h1>
    <div class="page-header-actions">
        <a href="download_all_cards.php" class="add-btn add-btn-outline">📦 Baixar todos cards</a>
        <a href="dns.php?novo=1" class="add-btn">➕ Novo Cliente</a>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<?php if ($editing_id && $editing_data): ?>
    <div class="edit-form">
        <h2>✏️ Editando cliente: <?php echo htmlspecialchars($editing_data['name']); ?></h2>
        <form method="POST">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" value="<?php echo $editing_id; ?>">

            <div class="form-grid" style="grid-template-columns: 1fr 2fr 100px;">
                <div class="form-group">
                    <label>🏷️ Nome</label>
                    <input type="text"
                           name="name"
                           value="<?php echo htmlspecialchars($editing_data['name']); ?>"
                           required>
                </div>

                <div class="form-group">
                    <label>📺 URL M3U</label>
                    <input type="text"
                           name="m3u_url"
                           value="<?php echo htmlspecialchars($editing_data['m3u_url']); ?>"
                           required>
                </div>

                <div class="checkbox-group">
                    <input type="checkbox"
                           name="is_active"
                           id="is_active"
                           <?php echo $editing_data['is_active'] ? 'checked' : ''; ?>>
                    <label for="is_active">Ativo</label>
                </div>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">💾 Salvar Alterações</button>
                <a href="list_dns.php" class="btn btn-secondary">✖️ Cancelar</a>
            </div>
        </form>
    </div>
<?php endif; ?>

<div class="mobile-scroll-tip">📱 Arraste a tabela para o lado para ver código, M3U, status e ações.</div>

<div class="table-container">
    <?php if (empty($clients)): ?>
        <div class="empty-state">
            <div style="font-size: 64px;">📭</div>
            <h3>Nenhum cliente cadastrado</h3>
            <p>Comece adicionando um novo cliente com lista M3U.</p>
            <a href="dns.php?novo=1" class="add-btn" style="margin-top:15px; display:inline-block;">➕ Novo Cliente</a>
        </div>
    <?php else: ?>
        <table class="dns-table">
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>Plano</th>
                    <th>Código</th>
                    <th>Servidor</th>
                    <th>Usuário</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($clients as $client): ?>
                    <tr class="<?php echo !$client['is_active'] ? 'inactive' : ''; ?> <?php echo $editing_id == $client['id'] ? 'editing' : ''; ?>">
                        <td><?php echo htmlspecialchars($client['name']); ?></td>
                        <td>
                            <span class="plan-badge-table"><?php echo htmlspecialchars(card_plan_label($client['card_plan'] ?? 'mensal')); ?></span>
                        </td>
                        <td class="code-cell"><?php echo htmlspecialchars(format_activation_code($client['activation_code'] ?? '')); ?></td>
                        <td><?php echo htmlspecialchars($client['server_url']); ?></td>
                        <td><?php echo htmlspecialchars($client['username']); ?></td>
                        <td>
                            <span class="status-badge <?php echo $client['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                <?php echo $client['is_active'] ? 'Ativo' : 'Inativo'; ?>
                            </span>
                        </td>
                        <td>
                            <div class="action-btns">
                                <a href="?action=edit&id=<?php echo $client['id']; ?>"
                                   class="action-btn btn-edit"
                                   title="Editar">
                                    ✏️ Editar
                                </a>

                                <?php if ($client['is_active']): ?>
                                    <a href="?action=deactivate&id=<?php echo $client['id']; ?>"
                                       class="action-btn btn-deactivate"
                                       onclick="return confirm('Desativar este cliente?')"
                                       title="Desativar">
                                        ⏸️ Desativar
                                    </a>
                                <?php else: ?>
                                    <a href="?action=activate&id=<?php echo $client['id']; ?>"
                                       class="action-btn btn-activate"
                                       title="Ativar">
                                        ▶️ Ativar
                                    </a>
                                <?php endif; ?>

                                <a href="?action=delete&id=<?php echo $client['id']; ?>"
                                   class="action-btn btn-delete"
                                   onclick="return confirm('⚠️ ATENÇÃO! Excluir permanentemente este cliente?\n\nEsta ação NÃO pode ser desfeita!')"
                                   title="Excluir permanentemente">
                                    🗑️ Excluir
                                </a>

                                <button type="button"
                                        class="action-btn btn-card"
                                        onclick="showClientCard(<?php echo (int)$client['id']; ?>, '<?php echo htmlspecialchars(format_activation_code($client['activation_code'] ?? ''), ENT_QUOTES); ?>', '<?php echo htmlspecialchars(card_plan_label($client['card_plan'] ?? 'mensal'), ENT_QUOTES); ?>')"
                                        title="Exibir card">
                                    🎴 Exibir card
                                </button>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<div id="cardModal" class="card-modal" aria-hidden="true">
    <div class="card-modal-backdrop" onclick="closeClientCard()"></div>
    <div class="card-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="cardModalTitle">
        <button type="button" class="card-modal-close" onclick="closeClientCard()" aria-label="Fechar">&times;</button>
        <h3 id="cardModalTitle">🎴 Card de recarga</h3>
        <p id="cardModalPlan" class="card-modal-code" style="margin-bottom:6px;"></p>
        <p id="cardModalCode" class="card-modal-code code-cell"></p>
        <div class="card-modal-image-wrap">
            <img id="cardModalImage" alt="Card de recarga do cliente">
        </div>
        <div class="card-modal-actions">
            <a id="cardModalDownload" href="#" class="btn btn-primary">⬇️ Baixar card PNG</a>
            <button type="button" class="btn btn-secondary" onclick="closeClientCard()">Fechar</button>
        </div>
    </div>
</div>

<script>
function showClientCard(id, code, plan) {
    var modal = document.getElementById('cardModal');
    var img = document.getElementById('cardModalImage');
    var download = document.getElementById('cardModalDownload');
    var codeEl = document.getElementById('cardModalCode');
    var planEl = document.getElementById('cardModalPlan');

    planEl.textContent = 'Plano: ' + (plan || 'Mensal');
    codeEl.textContent = code;
    img.src = 'client_card.php?id=' + id + '&v=' + Date.now();
    download.href = 'client_card.php?id=' + id + '&download=1';

    modal.classList.add('open');
    modal.setAttribute('aria-hidden', 'false');
    document.body.style.overflow = 'hidden';
}

function closeClientCard() {
    var modal = document.getElementById('cardModal');
    modal.classList.remove('open');
    modal.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
    document.getElementById('cardModalImage').src = '';
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeClientCard();
    }
});
</script>

</main>
</body>
</html>
