<?php
// Sistema de Gerenciamento de Links - Versão SEM Banco de Dados
// Arquivo: index.php

session_start();

// ========== CONFIGURAÇÕES ==========
define('DATA_FILE', 'dados.json');
define('CONFIG_FILE', 'config.json');

// ========== FUNÇÕES PARA MANIPULAR DADOS ==========
function lerDados() {
    if (file_exists(DATA_FILE)) {
        $json = file_get_contents(DATA_FILE);
        return json_decode($json, true) ?: ['links' => [], 'usuarios' => []];
    }
    // Dados iniciais
    $dados = [
        'links' => [],
        'usuarios' => [
            ['id' => 1, 'usuario' => 'admin', 'senha' => password_hash('admin123', PASSWORD_DEFAULT)]
        ]
    ];
    salvarDados($dados);
    return $dados;
}

function salvarDados($dados) {
    file_put_contents(DATA_FILE, json_encode($dados, JSON_PRETTY_PRINT));
}

function lerConfig() {
    if (file_exists(CONFIG_FILE)) {
        $json = file_get_contents(CONFIG_FILE);
        return json_decode($json, true) ?: ['logo' => 'logo.png'];
    }
    $config = ['logo' => 'logo.png'];
    salvarConfig($config);
    return $config;
}

function salvarConfig($config) {
    file_put_contents(CONFIG_FILE, json_encode($config, JSON_PRETTY_PRINT));
}

// ========== VERIFICAR LOGIN ==========
function verificarLogin() {
    if (!isset($_SESSION['usuario_id'])) {
        header('Location: ?action=login');
        exit();
    }
}

// ========== GERAR ID AUTOMÁTICO ==========
function gerarId($dados) {
    $maxId = 0;
    foreach ($dados['links'] as $link) {
        if ($link['id'] > $maxId) $maxId = $link['id'];
    }
    return $maxId + 1;
}

// ========== CARREGAR DADOS ==========
$dados = lerDados();
$config = lerConfig();

// ========== LOGIN ==========
if (isset($_GET['action']) && $_GET['action'] == 'login') {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $usuario = $_POST['usuario'] ?? '';
        $senha = $_POST['senha'] ?? '';
        
        foreach ($dados['usuarios'] as $user) {
            if ($user['usuario'] == $usuario && password_verify($senha, $user['senha'])) {
                $_SESSION['usuario_id'] = $user['id'];
                $_SESSION['usuario'] = $user['usuario'];
                header('Location: ?action=dashboard');
                exit();
            }
        }
        $erro_login = "Usuário ou senha inválidos!";
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login - Sistema de Links</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #4a90e2, #7eb8e0);
                height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .login-container {
                background: #d0e4f5;
                padding: 40px;
                border-radius: 15px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                width: 350px;
                border: 1px solid #b0cce0;
            }
            .login-container h1 {
                text-align: center;
                color: #2c5f8a;
                margin-bottom: 30px;
                font-weight: 300;
            }
            .login-container input {
                width: 100%;
                padding: 12px;
                margin: 10px 0;
                border: 1px solid #b0cce0;
                border-radius: 8px;
                background: #eaf2fa;
                font-size: 16px;
            }
            .login-container button {
                width: 100%;
                padding: 12px;
                background: #2c5f8a;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 16px;
                cursor: pointer;
                transition: background 0.3s;
            }
            .login-container button:hover {
                background: #1a3f5f;
            }
            .error {
                color: #c0392b;
                text-align: center;
                margin: 10px 0;
                background: #fde8e8;
                padding: 8px;
                border-radius: 5px;
            }
            .logo-login {
                text-align: center;
                margin-bottom: 20px;
            }
            .logo-login img {
                max-width: 100px;
                border-radius: 10px;
            }
            .info-login {
                text-align: center;
                margin-top: 15px;
                color: #2c5f8a;
                font-size: 12px;
                background: #eaf2fa;
                padding: 8px;
                border-radius: 5px;
            }
        </style>
    </head>
    <body>
        <div class="login-container">
            <div class="logo-login">
                <img src="<?php echo $config['logo']; ?>" alt="Logo" onerror="this.style.display='none'">
            </div>
            <h1>Sistema de Links</h1>
            <?php if (isset($erro_login)): ?>
                <div class="error"><?php echo $erro_login; ?></div>
            <?php endif; ?>
            <form method="POST">
                <input type="text" name="usuario" placeholder="Usuário" required>
                <input type="password" name="senha" placeholder="Senha" required>
                <button type="submit">Entrar</button>
            </form>
            <div class="info-login">
                Usuário: admin | Senha: admin123
            </div>
        </div>
    </body>
    </html>
    <?php
    exit();
}

// ========== LOGOUT ==========
if (isset($_GET['action']) && $_GET['action'] == 'sair') {
    session_destroy();
    header('Location: ?action=login');
    exit();
}

// ========== VERIFICAR AUTENTICAÇÃO ==========
verificarLogin();

// ========== PROCESSAR AÇÕES ==========

// CADASTRAR LINK
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cadastrar_link'])) {
    $novoLink = [
        'id' => gerarId($dados),
        'nome_cliente' => $_POST['nome_cliente'],
        'link' => $_POST['link'],
        'data_vencimento' => $_POST['data_vencimento'],
        'whatsapp' => $_POST['whatsapp'] ?? '',
        'status' => 'ativo',
        'created_at' => date('Y-m-d H:i:s')
    ];
    $dados['links'][] = $novoLink;
    salvarDados($dados);
    header('Location: ?action=cadastro&msg=sucesso');
    exit();
}

// EDITAR LINK
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['editar_link'])) {
    $id = $_POST['id'];
    foreach ($dados['links'] as &$link) {
        if ($link['id'] == $id) {
            $link['nome_cliente'] = $_POST['nome_cliente'];
            $link['link'] = $_POST['link'];
            $link['data_vencimento'] = $_POST['data_vencimento'];
            $link['whatsapp'] = $_POST['whatsapp'] ?? '';
            break;
        }
    }
    salvarDados($dados);
    header('Location: ?action=cadastro&msg=editado');
    exit();
}

// EXCLUIR LINK
if (isset($_GET['action']) && $_GET['action'] == 'excluir' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $dados['links'] = array_filter($dados['links'], function($link) use ($id) {
        return $link['id'] != $id;
    });
    $dados['links'] = array_values($dados['links']);
    salvarDados($dados);
    header('Location: ?action=cadastro&msg=excluido');
    exit();
}

// ALTERAR STATUS (Bloquear/Desbloquear)
if (isset($_GET['action']) && $_GET['action'] == 'toggle_status' && isset($_GET['id'])) {
    $id = $_GET['id'];
    foreach ($dados['links'] as &$link) {
        if ($link['id'] == $id) {
            $link['status'] = ($link['status'] == 'ativo') ? 'bloqueado' : 'ativo';
            break;
        }
    }
    salvarDados($dados);
    header('Location: ?action=cadastro');
    exit();
}

// ALTERAR SENHA
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['alterar_senha'])) {
    $senha_atual = $_POST['senha_atual'];
    $nova_senha = $_POST['nova_senha'];
    $confirmar_senha = $_POST['confirmar_senha'];
    
    foreach ($dados['usuarios'] as &$user) {
        if ($user['id'] == $_SESSION['usuario_id']) {
            if (password_verify($senha_atual, $user['senha'])) {
                if ($nova_senha == $confirmar_senha) {
                    $user['senha'] = password_hash($nova_senha, PASSWORD_DEFAULT);
                    salvarDados($dados);
                    $msg_senha = "Senha alterada com sucesso!";
                } else {
                    $msg_senha = "As senhas não coincidem!";
                }
            } else {
                $msg_senha = "Senha atual incorreta!";
            }
            break;
        }
    }
}

// ALTERAR LOGO
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['alterar_logo'])) {
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
        $extensao = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $nome_arquivo = 'logo.' . $extensao;
        move_uploaded_file($_FILES['logo']['tmp_name'], $nome_arquivo);
        $config['logo'] = $nome_arquivo;
        salvarConfig($config);
        $msg_logo = "Logo alterada com sucesso!";
    }
}

// ========== DADOS PARA DASHBOARD ==========
$total_links = count($dados['links']);
$links_bloqueados = 0;
$links_vencidos = 0;
$hoje = date('Y-m-d');

foreach ($dados['links'] as $link) {
    if ($link['status'] == 'bloqueado') $links_bloqueados++;
    if ($link['data_vencimento'] < $hoje && $link['status'] != 'bloqueado') {
        $links_vencidos++;
        // Atualizar status para vencido
        foreach ($dados['links'] as &$l) {
            if ($l['id'] == $link['id']) {
                $l['status'] = 'vencido';
            }
        }
    }
}
salvarDados($dados);

// ========== HTML DO SISTEMA ==========
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema de Links</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #eaf2fa;
        }
        
        /* ===== CORES ===== */
        :root {
            --azul-metalico: #2c5f8a;
            --azul-claro: #4a90e2;
            --cinza-metalico: #b0cce0;
            --cinza-claro: #d0e4f5;
            --fundo: #eaf2fa;
            --branco: #ffffff;
        }
        
        /* ===== HEADER ===== */
        .header {
            background: var(--azul-metalico);
            color: white;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .header-left img {
            max-height: 40px;
            border-radius: 5px;
        }
        .header h1 {
            font-size: 20px;
            font-weight: 300;
        }
        .header-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        .header-right span {
            color: var(--cinza-claro);
        }
        .btn-sair {
            background: #1a3f5f;
            color: white;
            padding: 8px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            transition: background 0.3s;
        }
        .btn-sair:hover {
            background: #0f2a40;
        }
        
        /* ===== SIDEBAR ===== */
        .sidebar {
            position: fixed;
            top: 70px;
            left: 0;
            width: 200px;
            height: calc(100% - 70px);
            background: var(--azul-metalico);
            padding: 20px 0;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        .sidebar a {
            display: block;
            color: var(--cinza-claro);
            padding: 12px 25px;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }
        .sidebar a:hover {
            background: #1a3f5f;
            color: white;
            border-left-color: var(--cinza-claro);
        }
        .sidebar a.active {
            background: #1a3f5f;
            color: white;
            border-left-color: white;
        }
        
        /* ===== MAIN CONTENT ===== */
        .main {
            margin-left: 200px;
            margin-top: 70px;
            padding: 30px;
        }
        
        /* ===== CARDS ===== */
        .cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .card {
            background: var(--branco);
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-top: 4px solid var(--azul-metalico);
        }
        .card h3 {
            color: var(--azul-metalico);
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 10px;
        }
        .card .numero {
            font-size: 32px;
            font-weight: bold;
            color: var(--azul-metalico);
        }
        .card.bloqueado { border-top-color: #e74c3c; }
        .card.vencido { border-top-color: #f39c12; }
        
        /* ===== TABELAS ===== */
        .table-container {
            background: var(--branco);
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th {
            background: var(--azul-metalico);
            color: white;
            padding: 12px;
            text-align: left;
        }
        td {
            padding: 12px;
            border-bottom: 1px solid var(--cinza-claro);
        }
        tr:hover {
            background: var(--cinza-claro);
        }
        
        /* ===== BOTÕES ===== */
        .btn {
            padding: 6px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }
        .btn-primary {
            background: var(--azul-metalico);
            color: white;
        }
        .btn-primary:hover {
            background: #1a3f5f;
        }
        .btn-success {
            background: #27ae60;
            color: white;
        }
        .btn-success:hover {
            background: #1e8449;
        }
        .btn-danger {
            background: #e74c3c;
            color: white;
        }
        .btn-danger:hover {
            background: #c0392b;
        }
        .btn-warning {
            background: #f39c12;
            color: white;
        }
        .btn-warning:hover {
            background: #d68910;
        }
        .btn-sm {
            padding: 4px 10px;
            font-size: 12px;
        }
        
        /* ===== FORMULÁRIOS ===== */
        .form-container {
            background: var(--branco);
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: var(--azul-metalico);
            font-weight: 500;
        }
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--cinza-metalico);
            border-radius: 5px;
            background: var(--fundo);
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        .form-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        
        /* ===== MENSAGENS ===== */
        .msg {
            padding: 12px 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .msg-success {
            background: #d5f5e3;
            color: #1e8449;
            border-left: 4px solid #27ae60;
        }
        .msg-error {
            background: #fde8e8;
            color: #c0392b;
            border-left: 4px solid #e74c3c;
        }
        
        /* ===== STATUS BADGE ===== */
        .badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .badge-ativo { background: #d5f5e3; color: #1e8449; }
        .badge-bloqueado { background: #fde8e8; color: #c0392b; }
        .badge-vencido { background: #fdebd0; color: #d68910; }
        
        /* ===== MODAL ===== */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            justify-content: center;
            align-items: center;
        }
        .modal.active {
            display: flex;
        }
        .modal-content {
            background: var(--branco);
            padding: 30px;
            border-radius: 10px;
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--azul-metalico);
        }
        
        /* ===== RESPONSIVO ===== */
        @media (max-width: 768px) {
            .sidebar {
                width: 60px;
            }
            .sidebar a {
                padding: 12px 15px;
                font-size: 12px;
                text-align: center;
            }
            .main {
                margin-left: 60px;
                padding: 15px;
            }
            .form-row {
                grid-template-columns: 1fr;
            }
            .header h1 {
                font-size: 16px;
            }
            .cards {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>

<!-- ===== HEADER ===== -->
<div class="header">
    <div class="header-left">
        <img src="<?php echo $config['logo']; ?>" alt="Logo" onerror="this.style.display='none'">
        <h1>Sistema de Links</h1>
    </div>
    <div class="header-right">
        <span>Olá, <?php echo $_SESSION['usuario']; ?></span>
        <a href="?action=sair" class="btn-sair">Sair</a>
    </div>
</div>

<!-- ===== SIDEBAR ===== -->
<div class="sidebar">
    <a href="?action=dashboard" class="<?php echo (!isset($_GET['action']) || $_GET['action'] == 'dashboard') ? 'active' : ''; ?>">📊 Dashboard</a>
    <a href="?action=cadastro" class="<?php echo (isset($_GET['action']) && $_GET['action'] == 'cadastro') ? 'active' : ''; ?>">📝 Cadastro</a>
    <a href="?action=perfil" class="<?php echo (isset($_GET['action']) && $_GET['action'] == 'perfil') ? 'active' : ''; ?>">👤 Perfil</a>
    <a href="?action=logo" class="<?php echo (isset($_GET['action']) && $_GET['action'] == 'logo') ? 'active' : ''; ?>">🖼️ Logo</a>
</div>

<!-- ===== CONTEÚDO PRINCIPAL ===== -->
<div class="main">

<?php
// ==========================================
// DASHBOARD
// ==========================================
if (!isset($_GET['action']) || $_GET['action'] == 'dashboard'):
?>
    <h2 style="color: var(--azul-metalico); margin-bottom: 20px;">Dashboard</h2>
    
    <div class="cards">
        <div class="card">
            <h3>Total de Links</h3>
            <div class="numero"><?php echo $total_links; ?></div>
        </div>
        <div class="card bloqueado">
            <h3>Links Bloqueados</h3>
            <div class="numero"><?php echo $links_bloqueados; ?></div>
        </div>
        <div class="card vencido">
            <h3>Links Vencidos</h3>
            <div class="numero"><?php echo $links_vencidos; ?></div>
        </div>
    </div>

    <div class="table-container">
        <h3 style="margin-bottom: 15px; color: var(--azul-metalico);">Últimos Links Cadastrados</h3>
        <table>
            <thead>
                <tr>
                    <th>Cliente</th>
                    <th>Link</th>
                    <th>Vencimento</th>
                    <th>WhatsApp</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $ultimos = array_slice(array_reverse($dados['links']), 0, 10);
                foreach ($ultimos as $link): 
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($link['nome_cliente']); ?></td>
                    <td><a href="<?php echo htmlspecialchars($link['link']); ?>" target="_blank" style="color: var(--azul-metalico);"><?php echo htmlspecialchars($link['link']); ?></a></td>
                    <td><?php echo date('d/m/Y', strtotime($link['data_vencimento'])); ?></td>
                    <td><?php echo htmlspecialchars($link['whatsapp']); ?></td>
                    <td>
                        <span class="badge badge-<?php echo $link['status']; ?>">
                            <?php echo ucfirst($link['status']); ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($ultimos)): ?>
                <tr>
                    <td colspan="5" style="text-align: center; color: #999;">Nenhum link cadastrado</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

<?php
// ==========================================
// CADASTRO
// ==========================================
elseif (isset($_GET['action']) && $_GET['action'] == 'cadastro'):
    
    // Mensagens
    if (isset($_GET['msg'])) {
        if ($_GET['msg'] == 'sucesso') echo '<div class="msg msg-success">✅ Link cadastrado com sucesso!</div>';
        if ($_GET['msg'] == 'editado') echo '<div class="msg msg-success">✅ Link editado com sucesso!</div>';
        if ($_GET['msg'] == 'excluido') echo '<div class="msg msg-success">✅ Link excluído com sucesso!</div>';
    }
    
    // Dados para edição
    $editar = null;
    if (isset($_GET['editar']) && isset($_GET['id'])) {
        foreach ($dados['links'] as $link) {
            if ($link['id'] == $_GET['id']) {
                $editar = $link;
                break;
            }
        }
    }
?>
    <h2 style="color: var(--azul-metalico); margin-bottom: 20px;">📝 Cadastro de Links</h2>
    
    <div class="form-container">
        <h3 style="color: var(--azul-metalico); margin-bottom: 15px;"><?php echo $editar ? 'Editar Link' : 'Novo Link'; ?></h3>
        <form method="POST">
            <input type="hidden" name="<?php echo $editar ? 'editar_link' : 'cadastrar_link'; ?>" value="1">
            <?php if ($editar): ?>
                <input type="hidden" name="id" value="<?php echo $editar['id']; ?>">
            <?php endif; ?>
            
            <div class="form-row">
                <div class="form-group">
                    <label>Nome do Cliente *</label>
                    <input type="text" name="nome_cliente" value="<?php echo $editar ? htmlspecialchars($editar['nome_cliente']) : ''; ?>" required>
                </div>
                <div class="form-group">
                    <label>WhatsApp</label>
                    <input type="text" name="whatsapp" value="<?php echo $editar ? htmlspecialchars($editar['whatsapp']) : ''; ?>" placeholder="(11) 99999-9999">
                </div>
            </div>
            <div class="form-group">
                <label>Link *</label>
                <input type="url" name="link" value="<?php echo $editar ? htmlspecialchars($editar['link']) : ''; ?>" required>
            </div>
            <div class="form-group">
                <label>Data de Vencimento *</label>
                <input type="date" name="data_vencimento" value="<?php echo $editar ? $editar['data_vencimento'] : ''; ?>" required>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-success"><?php echo $editar ? 'Atualizar' : 'Cadastrar'; ?></button>
                <?php if ($editar): ?>
                    <a href="?action=cadastro" class="btn btn-danger">Cancelar</a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <div class="table-container">
        <h3 style="margin-bottom: 15px; color: var(--azul-metalico);">Lista de Links</h3>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Cliente</th>
                    <th>Link</th>
                    <th>Vencimento</th>
                    <th>WhatsApp</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($dados['links'] as $link): ?>
                <tr>
                    <td><?php echo $link['id']; ?></td>
                    <td><?php echo htmlspecialchars($link['nome_cliente']); ?></td>
                    <td><a href="<?php echo htmlspecialchars($link['link']); ?>" target="_blank" style="color: var(--azul-metalico);"><?php echo htmlspecialchars($link['link']); ?></a></td>
                    <td><?php echo date('d/m/Y', strtotime($link['data_vencimento'])); ?></td>
                    <td><?php echo htmlspecialchars($link['whatsapp']); ?></td>
                    <td>
                        <span class="badge badge-<?php echo $link['status']; ?>">
                            <?php echo ucfirst($link['status']); ?>
                        </span>
                    </td>
                    <td>
                        <a href="?action=cadastro&editar=1&id=<?php echo $link['id']; ?>" class="btn btn-primary btn-sm">✏️</a>
                        <a href="?action=excluir&id=<?php echo $link['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Tem certeza que deseja excluir?')">🗑️</a>
                        <a href="?action=toggle_status&id=<?php echo $link['id']; ?>" class="btn btn-warning btn-sm">
                            <?php echo $link['status'] == 'ativo' ? '🔒' : '🔓'; ?>
                        </a>
                        <?php if ($link['whatsapp']): ?>
                            <a href="https://wa.me/55<?php echo preg_replace('/[^0-9]/', '', $link['whatsapp']); ?>" target="_blank" class="btn btn-success btn-sm">💬</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($dados['links'])): ?>
                <tr>
                    <td colspan="7" style="text-align: center; color: #999;">Nenhum link cadastrado</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

<?php
// ==========================================
// PERFIL
// ==========================================
elseif (isset($_GET['action']) && $_GET['action'] == 'perfil'):
?>
    <h2 style="color: var(--azul-metalico); margin-bottom: 20px;">👤 Meu Perfil</h2>
    
    <?php if (isset($msg_senha)): ?>
        <div class="msg <?php echo strpos($msg_senha, 'sucesso') !== false ? 'msg-success' : 'msg-error'; ?>">
            <?php echo $msg_senha; ?>
        </div>
    <?php endif; ?>
    
    <div class="form-container">
        <h3 style="color: var(--azul-metalico); margin-bottom: 15px;">Alterar Senha</h3>
        <form method="POST">
            <input type="hidden" name="alterar_senha" value="1">
            <div class="form-group">
                <label>Senha Atual</label>
                <input type="password" name="senha_atual" required>
            </div>
            <div class="form-group">
                <label>Nova Senha</label>
                <input type="password" name="nova_senha" required>
            </div>
            <div class="form-group">
                <label>Confirmar Nova Senha</label>
                <input type="password" name="confirmar_senha" required>
            </div>
            <button type="submit" class="btn btn-primary">Alterar Senha</button>
        </form>
    </div>
    
    <div class="form-container">
        <h3 style="color: var(--azul-metalico); margin-bottom: 15px;">Informações</h3>
        <p><strong>Usuário:</strong> <?php echo $_SESSION['usuario']; ?></p>
        <p><strong>ID:</strong> <?php echo $_SESSION['usuario_id']; ?></p>
    </div>

<?php
// ==========================================
// LOGO
// ==========================================
elseif (isset($_GET['action']) && $_GET['action'] == 'logo'):
?>
    <h2 style="color: var(--azul-metalico); margin-bottom: 20px;">🖼️ Logo do Sistema</h2>
    
    <?php if (isset($msg_logo)): ?>
        <div class="msg msg-success"><?php echo $msg_logo; ?></div>
    <?php endif; ?>
    
    <div class="form-container">
        <h3 style="color: var(--azul-metalico); margin-bottom: 15px;">Logo Atual</h3>
        <div style="text-align: center; padding: 20px; background: var(--fundo); border-radius: 10px; margin-bottom: 20px;">
            <img src="<?php echo $config['logo']; ?>" alt="Logo" style="max-height: 150px; border-radius: 10px;" onerror="this.style.display='none'">
        </div>
        
        <h3 style="color: var(--azul-metalico); margin-bottom: 15px;">Alterar Logo</h3>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="alterar_logo" value="1">
            <div class="form-group">
                <label>Selecionar imagem (PNG, JPG)</label>
                <input type="file" name="logo" accept="image/*" required>
            </div>
            <button type="submit" class="btn btn-primary">Alterar Logo</button>
        </form>
        <p style="margin-top: 10px; color: #999; font-size: 12px;">* Recomendado: 200x200 pixels</p>
    </div>

<?php endif; ?>

</div>

<!-- ===== SCRIPTS ===== -->
<script>
// Fechar modal
document.querySelectorAll('.modal-close').forEach(btn => {
    btn.addEventListener('click', function() {
        this.closest('.modal').classList.remove('active');
    });
});
// Fechar modal ao clicar fora
document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.remove('active');
        }
    });
});
</script>

</body>
</html>