<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include '../includes/header3.php';

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

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

// ================================
// 🔹 BUSCAR LOGO ATUAL - SUB REVENDA
// ================================
$current_logo = 'img/ibo.gif';
try {
    $logos_db = new SQLite3('../a/.eggziesublogos.db');
    $logos_db->exec("
        CREATE TABLE IF NOT EXISTS sub_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 sub_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 da sub-revenda: " . $e->getMessage());
}

// ================================
// 🔹 PROCESSAR UPLOAD DE LOGO - SUB REVENDA (ATUALIZADO)
// ================================
$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/sub_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/sub_revendas/" . $fileName;

                try {
                    $logos_db = new SQLite3('../a/.eggziesublogos.db');
                    $logos_db->exec("
                        CREATE TABLE IF NOT EXISTS sub_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 sub_revenda_logos WHERE revenda_id = '$id_revenda' AND user_type = '$user_type'");

                    if ($check > 0) {
                        // Atualizar logo existente
                        $stmt = $logos_db->prepare("UPDATE sub_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 sub_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 logo e oculta mensagem após 3s
                            echo "
                            <script>
                                // Oculta mensagens após 3 segundos
                                setTimeout(() => {
                                    document.querySelectorAll('.alert-success, .alert-error').forEach(msg => msg.style.display = 'none');
                                }, 3000);

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

                                // 🚀 Atualiza logo do painel (header3.php)
                                localStorage.setItem('sub_logo_updated', Math.floor(Date.now() / 1000));
                                localStorage.setItem('sub_new_logo_path', '$logo_path');
                                window.dispatchEvent(new Event('subLogoUpdated'));
                            </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 - SUB REVENDA
// ================================
$success_message = '';
$error_message = '';

if (isset($_POST['submit'])) {
    $username_new = $_POST['username'];
    $result = $db->query("SELECT COUNT(*) as count FROM sub_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'];
        
        // Buscar usuário atual para renomear arquivos
        $result_user = $db->query("SELECT usuario FROM sub_revenda WHERE id = '$id_revenda'");
        while ($row_user = $result_user->fetchArray()) {
            $user_old = $row_user['usuario'];
            break;
        }

        // Atualizar dados no banco
        $db->exec("UPDATE sub_revenda SET nome = '$name', usuario = '$username_new', senha = '$password' WHERE id = '$id_revenda'");
        
        // Atualizar seller nas outras tabelas
        $db->exec("UPDATE ibo SET seller = '$username_new' WHERE seller = '$user_old'");
        
        // Renomear arquivos
        if (file_exists("../a/rtx/Setting_$user_old.json")) {
            rename("../a/rtx/Setting_$user_old.json", "../a/rtx/Setting_$username_new.json");
        }
        if (file_exists("../a/rtx/logo_filenames_$user_old.json")) {
            rename("../a/rtx/logo_filenames_$user_old.json", "../a/rtx/logo_filenames_$username_new.json");
        }
        if (file_exists("../a/rtx/image_filenames_$user_old.json")) {
            rename("../a/rtx/image_filenames_$user_old.json", "../a/rtx/image_filenames_$username_new.json");
        }
        if (file_exists("../a/note_$user_old.json")) {
            rename("../a/note_$user_old.json", "../a/note_$username_new.json");
        }
        if (file_exists("../api/theme_$user_old.json")) {
            rename("../api/theme_$user_old.json", "../api/theme_$username_new.json");
        }
        
        // Atualizar outras tabelas
        $db2 = new SQLite3("../api/.adb.db");
        $db2->exec("UPDATE ads SET owner = '$username_new' WHERE owner = '$user_old'");
        $db3 = new SQLite3("../api/intro.db");
        $db3->exec("UPDATE intro SET owner = '$username_new' WHERE owner = '$user_old'");
        
        $_SESSION['reseller_name'] = $username_new;
        $username = $username_new;
        
        $success_message = "Perfil atualizado com sucesso!";
    }
}
?>

<style>
:root {
    --primary: #00D4FF;
    --primary-dark: #00A3CC;
    --secondary: #FF6B9D;
    --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;
}

.text-primary2 {
    color: var(--primary) !important;
}
</style>

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

    
 <!-- ✅ Mensagens (mostra só se existir conteúdo real) -->
<?php if (!empty($success_message)): ?>
    <div class="alert alert-success">✅ <?php echo htmlspecialchars($success_message); ?></div>
<?php endif; ?>

<?php if (!empty($error_message)): ?>
    <div class="alert alert-error">❌ <?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>

<?php if (!empty($logo_message)): ?>
    <?php 
        if (strpos($logo_message, ':') !== false) {
            list($type, $message) = explode(':', $logo_message, 2);
        } else {
            $type = 'error';
            $message = $logo_message;
        }
    ?>
    <div class="alert alert-<?php echo $type === 'success' ? 'success' : 'error'; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>


    <!-- Seção Logo Personalizada -->
    <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>

    <!-- Seção Dados do Perfil -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary2"><i class="fa fa-user"></i> Atualizar Perfil</h6>
        </div>
        <div class="card-body">
            <form method="post">
                <div class="form-group">
                    <label class="control-label"><strong>Nome Completo</strong></label>
                    <div class="input-group">
                        <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($name); ?>" placeholder="Digite o nome" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="control-label"><strong>Nome de Usuário</strong></label>
                    <div class="input-group">
                        <input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($username); ?>" placeholder="Digite o usuário" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="control-label"><strong>Senha</strong></label>
                    <div class="input-group">
                        <input type="password" class="form-control" name="password" value="<?php echo htmlspecialchars($password); ?>" id="passwordInput" placeholder="Digite a senha" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <input type="checkbox" onclick="togglePassword()">
                    <label class="control-label"><strong>Mostrar Senha</strong></label>
                </div>
                
                <div class="form-group">
                    <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                        <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                        <span class="text">Atualizar Perfil</span>
                    </button>
                </div>
            </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';
}

// Ocultar mensagens automáticas (caso apareçam no carregamento)
document.addEventListener('DOMContentLoaded', () => {
    setTimeout(() => {
        document.querySelectorAll('.alert-success, .alert-error').forEach(msg => msg.style.display = 'none');
    }, 3000);
});
</script>


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