<?php
$db = new SQLite3("./api/.ansdb.db");

// Cria a tabela caso não exista para evitar erros de execução
$db->exec("CREATE TABLE IF NOT EXISTS theme (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    url TEXT,
    logo_url TEXT,
    is_active INTEGER DEFAULT 0
)");

// Função para detectar a URL base do servidor automaticamente
function getBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    $currentPath = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
    return $protocol . $host . $currentPath;
}

function uploadImage($file) {
    if (!isset($file) || $file['error'] !== 0) return null;

    $allowed = ['image/png', 'image/jpeg', 'image/jpg'];
    if (!in_array($file['type'], $allowed)) {
        return null;
    }

    if ($file['size'] > 2 * 1024 * 1024) {
        return null;
    }

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $name = "theme_" . uniqid() . "." . $ext;
    $dir = "uploads/themes/";

    if (!is_dir($dir)) mkdir($dir, 0755, true);

    $path = $dir . $name;

    if (move_uploaded_file($file['tmp_name'], $path)) {
        return getBaseUrl() . $path;
    }
    
    return null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? trim($_POST['name']) : 'Sem Nome';

    $bg   = uploadImage($_FILES['background']);
    $logo = uploadImage($_FILES['logo']);

    if ($bg) {
        $stmt = $db->prepare("INSERT INTO theme(name, url, logo_url, is_active) VALUES (:name, :url, :logo, 0)");
        $stmt->bindValue(':name', $name, SQLITE3_TEXT);
        $stmt->bindValue(':url', $bg, SQLITE3_TEXT);
        $stmt->bindValue(':logo', $logo, SQLITE3_TEXT);
        $stmt->execute();

        header("Location: theme.php?success=1");
        exit();
    } else {
        $error = "Erro ao enviar a imagem de fundo.";
    }
}
?>

<?php include "includes/header.php"; ?>

<style>
    /* Estilo para manter o padrão Glassmorphism e responsividade */
    body {
        background: #020617; /* Fallback */
        color: #fff;
    }
    .main-container {
        min-height: 80vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px;
    }
    .theme-card {
        background: rgba(8, 17, 51, 0.75);
        backdrop-filter: blur(15px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 20px;
        padding: 30px;
        width: 100%;
        max-width: 500px;
        box-shadow: 0 20px 40px rgba(0,0,0,0.4);
    }
    .form-control {
        background: rgba(255, 255, 255, 0.05) !important;
        border: 1px solid rgba(255, 255, 255, 0.1) !important;
        color: #fff !important;
        border-radius: 12px !important;
        padding: 12px;
    }
    .form-control:focus {
        border-color: #2563eb !important;
        box-shadow: 0 0 0 0.25 margin rgba(37, 99, 235, 0.25);
    }
    .btn-save {
        background: linear-gradient(90deg, #2563eb, #7c3aed);
        border: none;
        border-radius: 12px;
        padding: 12px;
        font-weight: 700;
        text-transform: uppercase;
        width: 100%;
        margin-top: 10px;
        transition: 0.3s;
    }
    .btn-save:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 20px rgba(124, 58, 237, 0.3);
    }
    label {
        font-weight: 600;
        margin-bottom: 8px;
        color: #a9b3d4;
    }
    @media (max-width: 768px) {
        .theme-card { padding: 20px; }
    }
</style>

<div class="main-container">
    <div class="theme-card">
        <div class="text-center mb-4">
            <h3 class="fw-bold">Criar Novo Tema</h3>
            <p style="color: #a9b3d4; font-size: 0.9rem;">Configure o visual do seu aplicativo</p>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger" style="border-radius: 12px; background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #fff;">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data">
            <div class="mb-3">
                <label>Nome do Tema</label>
                <input class="form-control" name="name" placeholder="Ex: Ultra Neon Blue" required>
            </div>

            <div class="mb-3">
                <label>Imagem de Background (Papel de Parede)</label>
                <input class="form-control" type="file" name="background" accept="image/png,image/jpeg" required>
                <small class="text-muted">Recomendado: 1920x1080px (Máx 2MB)</small>
            </div>

            <div class="mb-4">
                <label>Logo do Aplicativo (Opcional)</label>
                <input class="form-control" type="file" name="logo" accept="image/png,image/jpeg">
                <small class="text-muted">PNG Transparente preferencialmente.</small>
            </div>

            <button type="submit" class="btn btn-save">
                <i class="fas fa-save me-2"></i> Salvar Tema
            </button>
            
            <a href="theme.php" class="btn btn-link w-100 text-center mt-3" style="color: #a9b3d4; text-decoration: none;">
                <i class="fas fa-arrow-left me-1"></i> Voltar
            </a>
        </form>
    </div>
</div>

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