<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "Background App";

$uploadDir  = 'img/';
$targetFile = $uploadDir . 'bg.png';

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

$success_message = '';
$error_message   = '';

// Remover background
if (isset($_GET['action']) && $_GET['action'] === 'delete_bg') {
    if (file_exists($targetFile)) unlink($targetFile);
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?') . "?success=deleted");
    exit;
}
if (isset($_GET['success']) && $_GET['success'] === 'deleted') {
    $success_message = "Background removido com sucesso!";
}

// Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['background'])) {
    $file = $_FILES['background'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error_message = "Erro no upload: " . $file['error'];
    } else {
        $check = getimagesize($file['tmp_name']);
        if ($check === false) {
            $error_message = "O arquivo não é uma imagem válida.";
        } else {
            $image = null;
            if ($check['mime'] === 'image/png')       $image = imagecreatefrompng($file['tmp_name']);
            elseif ($check['mime'] === 'image/jpeg')  $image = imagecreatefromjpeg($file['tmp_name']);
            elseif ($check['mime'] === 'image/gif')   $image = imagecreatefromgif($file['tmp_name']);
            else $error_message = "Formato não suportado. Use PNG, JPG ou GIF.";

            if ($image) {
                $width = imagesx($image); $height = imagesy($image);
                $maxW = 1920; $maxH = 1080;

                if ($width > $maxW || $height > $maxH) {
                    $ratio = $width / $height;
                    if ($maxW / $maxH > $ratio) { $nw = $maxH * $ratio; $nh = $maxH; }
                    else                         { $nw = $maxW; $nh = $maxW / $ratio; }
                    $res = imagecreatetruecolor($nw, $nh);
                    imagealphablending($res, false); imagesavealpha($res, true);
                    imagecopyresampled($res, $image, 0, 0, 0, 0, $nw, $nh, $width, $height);
                    imagedestroy($image);
                    $image = $res; $width = $nw; $height = $nh;
                }

                $png = imagecreatetruecolor($width, $height);
                imagealphablending($png, false); imagesavealpha($png, true);
                imagefill($png, 0, 0, imagecolorallocatealpha($png, 0, 0, 0, 127));
                imagecopy($png, $image, 0, 0, 0, 0, $width, $height);

                if (imagepng($png, $targetFile, 9)) $success_message = "Background atualizado com sucesso!";
                else $error_message = "Erro ao gravar na pasta img/.";

                imagedestroy($image);
                imagedestroy($png);
            }
        }
    }
}

$bg_exists = file_exists($targetFile);
$bg_url    = $bg_exists ? $targetFile . '?t=' . time() : '';

$page_content = '
<style>
/* ═══════════════════════════
   PAGE HEADER
═══════════════════════════ */
.mac-page-header {
    background: linear-gradient(135deg, #0d1117 0%, #1a2744 50%, #0d1117 100%);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 16px;
    padding: 28px 32px;
    margin-bottom: 24px;
    margin-top: 24px;
    position: relative;
    overflow: hidden;
}
.mac-page-header::before {
    content: "";
    position: absolute;
    top: -60px; right: -60px;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(34,211,238,0.08) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header::after {
    content: "";
    position: absolute;
    bottom: -40px; left: 30%;
    width: 150px; height: 150px;
    background: radial-gradient(circle, rgba(99,179,237,0.07) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header h1 {
    color: #e2e8f0;
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 6px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.mac-page-header h1 .icon-wrap {
    width: 40px; height: 40px;
    background: rgba(34,211,238,0.10);
    border: 1px solid rgba(34,211,238,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #22d3ee;
    flex-shrink: 0;
}
.mac-page-header p {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    margin: 0;
}

/* ═══════════════════════════
   PANELS
═══════════════════════════ */
.logo-panel {
    background: #161b22;
    border: 1px solid rgba(99,179,237,0.08);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0,0,0,0.3);
    height: 100%;
}
.logo-panel-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
    padding: 18px 24px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.logo-panel-header .ph-icon {
    width: 36px; height: 36px;
    border-radius: 9px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px;
    flex-shrink: 0;
}
.ph-icon-upload  { background: rgba(34,211,238,0.12);  border: 1px solid rgba(34,211,238,0.2);  color: #22d3ee; }
.ph-icon-preview { background: rgba(52,211,153,0.12);  border: 1px solid rgba(52,211,153,0.2);  color: #34d399; }
.ph-icon-info    { background: rgba(99,179,237,0.12);  border: 1px solid rgba(99,179,237,0.2);  color: #63b3ed; }
.logo-panel-header-text h5 {
    color: #e2e8f0;
    font-size: 14px;
    font-weight: 700;
    margin: 0 0 2px;
}
.logo-panel-header-text p {
    color: rgba(148,163,184,0.5);
    font-size: 12px;
    margin: 0;
}
.logo-panel-body { padding: 24px; }

/* Upload area */
.upload-drop-area {
    background: rgba(255,255,255,0.02);
    border: 2px dashed rgba(34,211,238,0.2);
    border-radius: 12px;
    padding: 32px 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s ease;
    margin-bottom: 20px;
}
.upload-drop-area:hover,
.upload-drop-area.drag-over {
    border-color: rgba(34,211,238,0.5);
    background: rgba(34,211,238,0.04);
}
.upload-drop-area i {
    font-size: 36px;
    color: rgba(34,211,238,0.35);
    margin-bottom: 12px;
    display: block;
    transition: color 0.2s ease;
}
.upload-drop-area:hover i { color: #22d3ee; }
.upload-drop-area p {
    color: rgba(148,163,184,0.6);
    font-size: 13px;
    margin: 0 0 4px;
}
.upload-drop-area small {
    color: rgba(148,163,184,0.35);
    font-size: 11px;
}
#bgInput { display: none; }

.file-chosen {
    background: rgba(52,211,153,0.06);
    border: 1px solid rgba(52,211,153,0.15);
    border-radius: 10px;
    padding: 10px 14px;
    display: none;
    align-items: center;
    gap: 10px;
    margin-bottom: 16px;
}
.file-chosen i { color: #34d399; font-size: 14px; }
.file-chosen span { color: #e2e8f0; font-size: 13px; flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.btn-upload {
    background: linear-gradient(135deg, #0e7490, #22d3ee) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 11px 20px !important;
    width: 100%;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: all 0.2s ease !important;
    box-shadow: 0 4px 12px rgba(34,211,238,0.2) !important;
    cursor: pointer;
}
.btn-upload:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(34,211,238,0.3) !important;
}

/* Dim sizes */
.dim-badges { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
.dim-badge {
    background: rgba(34,211,238,0.08);
    border: 1px solid rgba(34,211,238,0.15);
    border-radius: 6px;
    padding: 4px 10px;
    font-size: 11px;
    font-weight: 700;
    color: #22d3ee;
}
.dim-badge small { color: rgba(148,163,184,0.5); font-weight: 400; display: block; }

/* Tips */
.tip-list { list-style: none; padding: 0; margin: 20px 0 0; }
.tip-list li {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 8px 0;
    border-bottom: 1px solid rgba(255,255,255,0.04);
    font-size: 12px;
    color: rgba(148,163,184,0.6);
}
.tip-list li:last-child { border-bottom: none; }
.tip-list li i { font-size: 12px; margin-top: 2px; flex-shrink: 0; }

/* Preview */
.preview-bg {
    width: 100%;
    height: 220px;
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid rgba(255,255,255,0.06);
    background: #0d1117;
    position: relative;
    margin-bottom: 20px;
}
.preview-bg img {
    width: 100%; height: 100%;
    object-fit: cover;
    transition: transform 0.4s ease;
}
.preview-bg img:hover { transform: scale(1.04); }
.preview-overlay {
    position: absolute;
    bottom: 0; left: 0; right: 0;
    background: linear-gradient(to top, rgba(0,0,0,0.75), transparent);
    padding: 12px 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.preview-overlay span {
    color: #e2e8f0;
    font-size: 12px;
    font-weight: 600;
}
.badge-active-bg {
    background: rgba(52,211,153,0.2);
    border: 1px solid rgba(52,211,153,0.3);
    border-radius: 50px;
    padding: 2px 10px;
    font-size: 11px;
    font-weight: 700;
    color: #34d399;
}
.preview-empty {
    width: 100%; height: 100%;
    display: flex; flex-direction: column;
    align-items: center; justify-content: center;
    color: rgba(148,163,184,0.2);
}
.preview-empty i { font-size: 48px; margin-bottom: 12px; }
.preview-empty p { font-size: 13px; margin: 0; }

.btn-download {
    background: rgba(52,211,153,0.1) !important;
    border: 1px solid rgba(52,211,153,0.2) !important;
    color: #34d399 !important;
    border-radius: 10px !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 16px !important;
    flex: 1;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: all 0.2s ease !important;
    text-decoration: none;
}
.btn-download:hover { background: rgba(52,211,153,0.2) !important; transform: translateY(-1px) !important; }
.btn-remove {
    background: rgba(248,113,113,0.1) !important;
    border: 1px solid rgba(248,113,113,0.2) !important;
    color: #f87171 !important;
    border-radius: 10px !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 16px !important;
    flex: 1;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: all 0.2s ease !important;
    cursor: pointer;
}
.btn-remove:hover { background: rgba(248,113,113,0.2) !important; transform: translateY(-1px) !important; }

/* Info grid */
.info-grid { display: grid; grid-template-columns: repeat(4,1fr); gap: 12px; margin-top: 24px; }
@media(max-width:768px){ .info-grid { grid-template-columns: repeat(2,1fr); } }
.info-tile {
    background: rgba(255,255,255,0.02);
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 12px;
    padding: 16px;
    text-align: center;
}
.info-tile i { font-size: 22px; margin-bottom: 8px; display: block; }
.info-tile .info-label { color: rgba(148,163,184,0.5); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; }
.info-tile .info-value { color: #e2e8f0; font-size: 13px; font-weight: 600; margin-top: 2px; }

/* Alerts */
.alert-mac {
    border-radius: 10px;
    padding: 12px 16px;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}
.alert-mac-success { background: rgba(52,211,153,0.08);  border: 1px solid rgba(52,211,153,0.2);  color: #34d399; }
.alert-mac-error   { background: rgba(248,113,113,0.08); border: 1px solid rgba(248,113,113,0.2); color: #f87171; }
</style>

<!-- PAGE HEADER -->
<div class="mac-page-header d-flex align-items-center justify-content-between flex-wrap gap-3">
    <div>
        <h1>
            <span class="icon-wrap"><i class="fa-solid fa-image"></i></span>
            Background App
        </h1>
        <p>Faça upload e personalize a imagem de fundo exibida no aplicativo.</p>
    </div>
</div>

' . (!empty($success_message) ? '
<div class="alert-mac alert-mac-success">
    <i class="fa-solid fa-circle-check"></i> ' . $success_message . '
</div>' : '') . '

' . (!empty($error_message) ? '
<div class="alert-mac alert-mac-error">
    <i class="fa-solid fa-circle-xmark"></i> ' . $error_message . '
</div>' : '') . '

<div class="row g-4">

    <!-- UPLOAD -->
    <div class="col-lg-6">
        <div class="logo-panel">
            <div class="logo-panel-header">
                <div class="ph-icon ph-icon-upload"><i class="fa-solid fa-cloud-arrow-up"></i></div>
                <div class="logo-panel-header-text">
                    <h5>Upload de Background</h5>
                    <p>Envie uma imagem para o plano de fundo</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <form method="POST" enctype="multipart/form-data" id="uploadForm">
                    <input type="file" id="bgInput" name="background" accept="image/png,image/jpeg,image/jpg,image/gif">

                    <div class="upload-drop-area" id="dropArea" onclick="document.getElementById(\'bgInput\').click()">
                        <i class="fa-solid fa-cloud-arrow-up"></i>
                        <p>Clique ou arraste a imagem aqui</p>
                        <small>PNG, JPG ou GIF · Máximo 10 MB</small>
                    </div>

                    <div class="file-chosen" id="fileChosen">
                        <i class="fa-solid fa-file-image"></i>
                        <span id="fileName">—</span>
                    </div>

                    <button type="submit" class="btn-upload">
                        <i class="fa-solid fa-upload"></i> Definir como Background
                    </button>
                </form>

                <div class="dim-badges">
                    <div class="dim-badge">1920×1080 <small>Full HD</small></div>
                    <div class="dim-badge">2560×1440 <small>2K QHD</small></div>
                </div>

                <ul class="tip-list">
                    <li><i class="fa-solid fa-circle-check" style="color:#34d399;"></i> Use imagens de alta resolução para melhor qualidade</li>
                    <li><i class="fa-solid fa-moon" style="color:#818cf8;"></i> Prefira cores escuras para melhor legibilidade</li>
                    <li><i class="fa-solid fa-crop-simple" style="color:#22d3ee;"></i> Imagens maiores que 1920×1080 são redimensionadas automaticamente</li>
                    <li><i class="fa-solid fa-bolt" style="color:#fbbf24;"></i> Mudanças aplicadas instantaneamente após o upload</li>
                </ul>
            </div>
        </div>
    </div>

    <!-- PREVIEW -->
    <div class="col-lg-6">
        <div class="logo-panel">
            <div class="logo-panel-header">
                <div class="ph-icon ph-icon-preview"><i class="fa-solid fa-desktop"></i></div>
                <div class="logo-panel-header-text">
                    <h5>Visualização Atual</h5>
                    <p>Como o background aparece no aplicativo</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <div class="preview-bg" id="previewBox">
                    ' . ($bg_exists ? '
                    <img src="' . $bg_url . '" id="bgPreview" alt="Background atual">
                    <div class="preview-overlay">
                        <span><i class="fa-solid fa-image me-1"></i> bg.png</span>
                        <span class="badge-active-bg">Ativo</span>
                    </div>' : '
                    <div class="preview-empty" id="previewEmpty">
                        <i class="fa-solid fa-image"></i>
                        <p>Nenhum background definido</p>
                    </div>
                    <img src="" id="bgPreview" style="display:none;" alt="Preview">') . '
                </div>

                ' . ($bg_exists ? '
                <div class="d-flex gap-3">
                    <a href="' . $targetFile . '" download class="btn-download">
                        <i class="fa-solid fa-download"></i> Baixar BG
                    </a>
                    <button onclick="confirmDelete()" class="btn-remove">
                        <i class="fa-solid fa-trash"></i> Remover
                    </button>
                </div>' : '
                <div class="alert-mac" style="background:rgba(99,179,237,0.06);border:1px solid rgba(99,179,237,0.15);color:rgba(148,163,184,0.6);">
                    <i class="fa-solid fa-circle-info" style="color:#63b3ed;"></i>
                    Após o upload, você poderá baixar ou remover o background aqui.
                </div>') . '
            </div>
        </div>
    </div>

</div>

<!-- INFO GRID -->
<div class="info-grid">
    <div class="info-tile">
        <i class="fa-solid ' . ($bg_exists ? 'fa-circle-check" style="color:#34d399;' : 'fa-circle-xmark" style="color:#f87171;') . '"></i>
        <div class="info-label">Status</div>
        <div class="info-value">' . ($bg_exists ? 'Ativo' : 'Não configurado') . '</div>
    </div>
    <div class="info-tile">
        <i class="fa-solid fa-file-image" style="color:#63b3ed;"></i>
        <div class="info-label">Arquivo</div>
        <div class="info-value">bg.png</div>
    </div>
    <div class="info-tile">
        <i class="fa-solid fa-folder" style="color:#fbbf24;"></i>
        <div class="info-label">Localização</div>
        <div class="info-value">/img/bg.png</div>
    </div>
    <div class="info-tile">
        <i class="fa-solid fa-bolt" style="color:#34d399;"></i>
        <div class="info-label">Atualização</div>
        <div class="info-value">Instantânea</div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
// Preview ao selecionar ficheiro
document.getElementById("bgInput").addEventListener("change", function () {
    const file = this.files[0];
    if (!file) return;

    if (file.size > 10 * 1024 * 1024) {
        Swal.fire("Erro", "Arquivo muito grande! Máximo: 10 MB.", "error");
        this.value = "";
        return;
    }

    document.getElementById("fileName").textContent = file.name;
    document.getElementById("fileChosen").style.display = "flex";

    const img = document.getElementById("bgPreview");
    const empty = document.getElementById("previewEmpty");
    img.src = URL.createObjectURL(file);
    img.style.display = "block";
    if (empty) empty.style.display = "none";
});

// Drag & drop visual
const drop = document.getElementById("dropArea");
["dragenter","dragover"].forEach(e => drop.addEventListener(e, ev => { ev.preventDefault(); drop.classList.add("drag-over"); }));
["dragleave","drop"].forEach(e => drop.addEventListener(e, ev => { ev.preventDefault(); drop.classList.remove("drag-over"); }));
drop.addEventListener("drop", function (ev) {
    const dt = ev.dataTransfer;
    if (dt.files.length) {
        document.getElementById("bgInput").files = dt.files;
        document.getElementById("bgInput").dispatchEvent(new Event("change"));
    }
});

// Confirmar remoção
function confirmDelete() {
    Swal.fire({
        title: "Remover background?",
        text: "Esta ação não pode ser revertida.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, remover!",
        cancelButtonText: "Cancelar"
    }).then(result => {
        if (result.isConfirmed) window.location.href = "?action=delete_bg";
    });
}
</script>