<?php
include "../includes/header3.php";
require_once "../includes/LogoManager.php";

$reseller_name = $_SESSION['reseller_name'];
$logoManager = new LogoManager('sub_revenda', $reseller_name);
$current_logo = $logoManager->getLogo();

// Função para gerar URL absoluta
function getAbsoluteUrl($relativePath) {
    $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
    $domain = $_SERVER['HTTP_HOST'];
    return $protocol . $domain . '/' . ltrim($relativePath, '/');
}
?>

<style>
.custom-button {
    padding: 10px 20px;
}
#url-form {
    display: none;
}
.preview-logo {
    border: 2px solid #4e73df;
    padding: 15px;
    border-radius: 8px;
    margin: 20px 0;
    background: #f8f9fc;
    text-align: center;
}
.preview-logo img {
    max-width: 100%;
    max-height: 200px;
    margin: 10px 0;
    border-radius: 5px;
}
</style>

<div class="container-fluid">
    <h1 class="h3 mb-1 text-gray-800">Alterar Logotipo</h1>
    
    <div class="row">
        <div class="col-lg-12">
            <div class="card border-left-primary shadow h-100 card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><i class="fa fa-camera"></i> Configuração de Logotipo - Sub Revenda</h6>
                </div>
                <div class="card-body">
                    
                    <!-- Preview da Logo Atual -->
                    <div class="preview-logo">
                        <h5>Logotipo Atual:</h5>
                        <img src="<?php echo $current_logo; ?>" alt="Logotipo Atual">
                        <p><small class="text-muted">Esta logo será exibida no seu painel e no aplicativo dos seus clientes.</small></p>
                    </div>
                    
                    <hr>
                    
                    <div class="form-group">
                        <label><strong>Método de Upload:</strong></label><br>
                        <input type="radio" name="upload-type" id="upload-radio" checked> Enviar arquivo de imagem &nbsp;&nbsp;
                        <input type="radio" name="upload-type" id="url-radio"> Usar URL da imagem
                    </div>
                    
                    <!-- Formulário de Upload por Arquivo -->
                    <form method="post" enctype="multipart/form-data" id="upload-form">
                        <div class="form-group">
                            <label for="image">Selecione uma imagem:</label>
                            <input type="file" name="image" id="image" accept="image/jpeg, image/png, image/gif, image/webp" class="form-control-file">
                            <small class="text-muted">Formatos aceitos: JPEG, PNG, GIF, WEBP</small>
                        </div>
                        <button class="btn btn-success" type="submit" name="upload">
                            <i class="fas fa-upload"></i> Atualizar Logotipo
                        </button>
                    </form>
                    
                    <!-- Formulário de Upload por URL -->
                    <form method="post" id="url-form">
                        <div class="form-group">
                            <label for="image-url">URL da imagem:</label>
                            <input type="text" class="form-control" name="image-url" id="image-url" placeholder="https://exemplo.com/imagem.jpg">
                        </div>
                        <button class="btn btn-success" type="submit" name="url-submit">
                            <i class="fas fa-link"></i> Aplicar URL
                        </button>
                    </form>
                    
                    <?php
                    // Criar diretório específico para a sub revenda
                    $upload_dir = '../rtx/logo/sub_revenda_' . $reseller_name . '/';
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    // Processar upload por arquivo
                    if (isset($_POST['upload'])) {
                        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                            $file = $_FILES['image'];
                            $fileType = $file['type'];
                            $fileTemp = $file['tmp_name'];
                            
                            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                            if (in_array($fileType, $allowedTypes)) {
                                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                                $fileName = 'logo_' . time() . '.' . $extension;
                                $destination = $upload_dir . $fileName;
                                $relative_path = 'rtx/logo/sub_revenda_' . $reseller_name . '/' . $fileName;
                                
                                if (move_uploaded_file($fileTemp, $destination)) {
                                    $absolute_url = getAbsoluteUrl($relative_path);
                                    $logoManager->saveAppLogo(['ImageName' => $absolute_url, 'Upload_type' => 'by_file']);
                                    $logoManager->updateLogo($absolute_url, 'by_file');
                                    echo "<script>alert('Logotipo atualizado com sucesso!'); window.location.href='logo.php';</script>";
                                } else {
                                    echo '<div class="alert alert-danger mt-3">Erro ao fazer upload do arquivo.</div>';
                                }
                            } else {
                                echo '<div class="alert alert-danger mt-3">Formato inválido. Use JPEG, PNG, GIF ou WEBP.</div>';
                            }
                        } else {
                            echo '<div class="alert alert-warning mt-3">Nenhum arquivo selecionado.</div>';
                        }
                    }
                    
                    // Processar upload por URL
                    if (isset($_POST['url-submit'])) {
                        $imageUrl = $_POST['image-url'];
                        
                        if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
                            $logoManager->saveAppLogo(['ImageName' => $imageUrl, 'Upload_type' => 'by_url']);
                            $logoManager->updateLogo($imageUrl, 'by_url');
                            echo "<script>alert('Logotipo atualizado com sucesso!'); window.location.href='logo.php';</script>";
                        } else {
                            echo '<div class="alert alert-danger mt-3">URL inválida. Por favor, insira uma URL válida.</div>';
                        }
                    }
                    ?>
                    
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const uploadRadio = document.getElementById('upload-radio');
    const urlRadio = document.getElementById('url-radio');
    const uploadForm = document.getElementById('upload-form');
    const urlForm = document.getElementById('url-form');
    
    uploadRadio.addEventListener('change', () => {
        uploadForm.style.display = 'block';
        urlForm.style.display = 'none';
    });
    
    urlRadio.addEventListener('change', () => {
        uploadForm.style.display = 'none';
        urlForm.style.display = 'block';
    });
    
    uploadForm.style.display = 'block';
    urlForm.style.display = 'none';
</script>

<?php
$logoManager->close();
include "../includes/footer3.php";
?>