<?php
include "../includes/header2.php";

$id_revenda = $_SESSION['id'];
$user_type = 'revenda';

// ================================
// 🔹 BUSCAR DADOS DA REVENDA
// ================================
$res1 = $db->query("SELECT * FROM revenda WHERE id = '$id_revenda'");
while ($row1 = $res1->fetchArray()) {
    $name = $row1['nome'];
    $username = $row1['usuario'];
    $user = $username;
    $password = $row1['senha'];
}

// ================================
// 🔹 BUSCAR LOGO ATUAL
// ================================
$current_logo = 'img/ibo.gif';
try {
    $logos_db = new SQLite3('../a/.eggzielogos.db');
    $logos_db->exec("
        CREATE TABLE IF NOT EXISTS revenda_logos (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            revenda_id INTEGER NOT NULL,
            user_type TEXT NOT NULL,
            logo_path TEXT NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(revenda_id, user_type)
        )
    ");

    $stmt = $logos_db->prepare("SELECT logo_path FROM revenda_logos WHERE revenda_id = ? AND user_type = ?");
    $stmt->bindValue(1, $id_revenda, SQLITE3_INTEGER);
    $stmt->bindValue(2, $user_type, SQLITE3_TEXT);
    $result = $stmt->execute();

    if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $current_logo = $row['logo_path'];
    }
    $logos_db->close();
} catch (Exception $e) {
    error_log("Erro ao buscar logo: " . $e->getMessage());
}

// ================================
// 🔹 PROCESSAR UPLOAD DE LOGO (ATUALIZADO - SEM CACHE E COM AUTOREFRESH NO PAINEL)
// ================================
$logo_message = '';
if (isset($_POST['upload_logo'])) {
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['logo'];
        $fileType = $file['type'];
        $fileTemp = $file['tmp_name'];

        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (in_array($fileType, $allowedTypes)) {
            $uploadDir = "../rtx/logo/revendas/";

            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $fileName = "logo_{$id_revenda}_{$user_type}." . $fileExtension;
            $destination = $uploadDir . $fileName;

            if (move_uploaded_file($fileTemp, $destination)) {
                $logo_path = "rtx/logo/revendas/" . $fileName;

                try {
                    $logos_db = new SQLite3('../a/.eggzielogos.db');
                    $logos_db->exec("
                        CREATE TABLE IF NOT EXISTS revenda_logos (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            revenda_id INTEGER NOT NULL,
                            user_type TEXT NOT NULL,
                            logo_path TEXT NOT NULL,
                            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                            UNIQUE(revenda_id, user_type)
                        )
                    ");

                    $check = $logos_db->querySingle("SELECT COUNT(*) FROM revenda_logos WHERE revenda_id = '$id_revenda' AND user_type = '$user_type'");

                    if ($check > 0) {
                        // Atualizar logo existente
                        $stmt = $logos_db->prepare("UPDATE revenda_logos SET logo_path = ?, updated_at = CURRENT_TIMESTAMP WHERE revenda_id = ? AND user_type = ?");
                        $stmt->bindValue(1, $logo_path, SQLITE3_TEXT);
                        $stmt->bindValue(2, $id_revenda, SQLITE3_INTEGER);
                        $stmt->bindValue(3, $user_type, SQLITE3_TEXT);
                    } else {
                        // Inserir nova logo
                        $stmt = $logos_db->prepare("INSERT INTO revenda_logos (revenda_id, user_type, logo_path) VALUES (?, ?, ?)");
                        $stmt->bindValue(1, $id_revenda, SQLITE3_INTEGER);
                        $stmt->bindValue(2, $user_type, SQLITE3_TEXT);
                        $stmt->bindValue(3, $logo_path, SQLITE3_TEXT);
                    }

                    if (!$stmt) {
                        $logo_message = "error:❌ Erro ao preparar query: " . $logos_db->lastErrorMsg();
                    } else {
                        if ($stmt->execute()) {
                            $logo_message = "success:✅ Logo atualizada com sucesso!";
                            $current_logo = $logo_path;

                            // Atualiza imagem local, painel e esconde mensagem após 3s
                            echo "
                            <script>
                                // Oculta mensagem de sucesso após 3 segundos
                                setTimeout(() => {
                                    const msg = document.querySelector('.alert-success');
                                    if (msg) msg.style.display = 'none';
                                }, 3000);

                                // Atualiza imagem da logo na tela de perfil
                                const img = document.querySelector('.current-logo');
                                if (img) {
                                    img.src = '../$logo_path' + '?v=' + new Date().getTime();
                                }

                                // 🚀 Atualiza logo do painel lateral (header2.php)
                                localStorage.setItem('logo_updated', Math.floor(Date.now() / 1000));
                                localStorage.setItem('new_logo_path', '$logo_path');

                                // Dispara evento global para atualizar header2.php em tempo real
                                window.dispatchEvent(new Event('logoUpdated'));
                            </script>";
                        } else {
                            $logo_message = 'error:❌ Falha ao executar query: ' . $logos_db->lastErrorMsg();
                        }
                    }

                    $logos_db->close();
                } catch (Exception $e) {
                    $logo_message = "error:❌ Erro no banco de logos: " . $e->getMessage();
                }
            } else {
                $logo_message = "error:❌ Erro ao mover arquivo. Verifique permissões.";
            }
        } else {
            $logo_message = "error:❌ Tipo de arquivo inválido. Use JPG, PNG, GIF ou WEBP.";
        }
    } else {
        $logo_message = "error:❌ Nenhum arquivo selecionado ou erro no upload.";
    }
}



// ================================
// 🔹 ATUALIZAÇÃO DE PERFIL
// ================================
if (isset($_POST['submit'])) {
    $username_new = $_POST['username'];

    $result = $db->query("SELECT COUNT(*) as count FROM revenda WHERE usuario = '$username_new' AND id != '$id_revenda'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count = $row['count'];

    if ($count || $username_new == "ADM") {
        $error_message = "Usuário já existe ou 'ADM' não é permitido!";
    } else {
        $password = $_POST['password'];
        $name = $_POST['name'];

        $db->exec("UPDATE revenda SET nome = '$name', usuario = '$username_new', senha = '$password' WHERE id = '$id_revenda'");
        $_SESSION['seller_name'] = $username_new;
        $success_message = "Perfil atualizado com sucesso!";
        $username = $username_new;
    }
}
?>


<!-- O RESTANTE DO SEU CÓDIGO HTML AQUI -->

<style>
:root {
    --primary: #FF6B9D;
    --primary-dark: #D94A7E;
    --secondary: #00D4FF;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --border: rgba(255,255,255,0.1);
}

body {
    background: var(--surface);
    color: var(--text-primary);
    font-family: 'Inter', sans-serif;
}

.container-fluid {
    padding: 20px;
}

.card {
    background: var(--surface-light);
    border-radius: 16px;
    border: 1px solid var(--border);
    margin-bottom: 20px;
    padding: 0;
}

.card-header {
    background: var(--surface-lighter);
    padding: 20px;
    border-bottom: 1px solid var(--border);
    border-radius: 16px 16px 0 0;
}

.card-body {
    padding: 30px;
}

.form-group {
    margin-bottom: 20px;
}

.form-control {
    background: var(--surface-lighter);
    border: 2px solid var(--border);
    border-radius: 10px;
    color: var(--text-primary);
    padding: 12px 16px;
    width: 100%;
}

.form-control:focus {
    border-color: var(--primary);
    outline: none;
}

.btn-success {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    border: none;
    border-radius: 10px;
    color: white;
    padding: 12px 24px;
    font-weight: 600;
}

.logo-section {
    background: var(--surface-lighter);
    border: 2px dashed var(--border);
    border-radius: 12px;
    padding: 25px;
    text-align: center;
    margin-bottom: 25px;
}

.current-logo {
    max-width: 200px;
    max-height: 100px;
    border-radius: 10px;
    border: 2px solid var(--border);
    margin: 15px 0;
}

.logo-preview {
    max-width: 150px;
    max-height: 80px;
    border-radius: 8px;
    margin: 10px 0;
}

.alert {
    padding: 12px 16px;
    border-radius: 8px;
    margin: 10px 0;
    border-left: 4px solid;
}

.alert-success {
    background: rgba(0, 212, 255, 0.1);
    border-color: #00D4FF;
}

.alert-error {
    background: rgba(255, 71, 87, 0.1);
    border-color: #FF4757;
}
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4">
        <i class="fas fa-user-cog"></i> Configurações do Perfil
    </h1>

    <!-- Mensagens -->
    <?php if (isset($success_message)): ?>
        <div class="alert alert-success">✅ <?php echo $success_message; ?></div>
    <?php endif; ?>
    
    <?php if (isset($error_message)): ?>
        <div class="alert alert-error">❌ <?php echo $error_message; ?></div>
    <?php endif; ?>
    
    <?php if ($logo_message): ?>
        <?php list($type, $message) = explode(':', $logo_message, 2); ?>
        <div class="alert alert-<?php echo $type === 'success' ? 'success' : 'error'; ?>">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header">
            <h5 class="m-0"><i class="fas fa-image"></i> Logo Personalizada</h5>
        </div>
        <div class="card-body">
            <div class="logo-section">
                <div style="margin-bottom: 15px;">
                    <strong>Logo Atual:</strong><br>
                    <img src="../<?php echo $current_logo; ?>" class="current-logo" 
                         alt="Logo" onerror="this.src='../img/ibo.gif'">
                </div>
                
                <form method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <input type="file" class="form-control" name="logo" 
                               accept="image/jpeg,image/png,image/gif,image/webp"
                               onchange="previewLogo(this)">
                        <small style="color: #6B7280; display: block; margin-top: 8px;">
                            Formatos: JPG, PNG, GIF, WEBP
                        </small>
                    </div>
                    
                    <div id="logoPreview"></div>
                    
                    <button type="submit" class="btn-success" name="upload_logo">
                        <i class="fas fa-upload"></i> Upload da Logo
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h5 class="m-0"><i class="fas fa-user-edit"></i> Dados do Perfil</h5>
        </div>
        <div class="card-body">
            <form method="post">
                <div class="form-group">
                    <label>Nome Completo</label>
                    <input type="text" class="form-control" name="name" 
                           value="<?php echo htmlspecialchars($name); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Nome de Usuário</label>
                    <input type="text" class="form-control" name="username" 
                           value="<?php echo htmlspecialchars($username); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Senha</label>
                    <input type="password" class="form-control" name="password" 
                           value="<?php echo htmlspecialchars($password); ?>" 
                           id="passwordInput" required>
                    <small style="color: #6B7280; margin-top: 8px; display: block;">
                        <input type="checkbox" onclick="togglePassword()"> Mostrar senha
                    </small>
                </div>

                <button type="submit" class="btn-success" name="submit">
                    <i class="fas fa-save"></i> Atualizar Perfil
                </button>
            </form>
        </div>
    </div>
</div>

<script>
function previewLogo(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('logoPreview').innerHTML = 
                '<img src="' + e.target.result + '" class="logo-preview" alt="Preview">';
        }
        reader.readAsDataURL(input.files[0]);
    }
}

function togglePassword() {
    const input = document.getElementById('passwordInput');
    input.type = input.type === 'password' ? 'text' : 'password';
}
</script>

<?php include '../includes/footer.php'; ?>