<?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 = "Sua Logotipo";

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

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

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

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

// Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['logo'])) {
    $file = $_FILES['logo'];
    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/gif')  $image = imagecreatefromgif($file['tmp_name']);
            else                                      $image = imagecreatefromjpeg($file['tmp_name']);

            if ($image) {
                $w = imagesx($image); $h = imagesy($image);
                $png = imagecreatetruecolor($w, $h);
                imagealphablending($png, false);
                imagesavealpha($png, true);
                imagefill($png, 0, 0, imagecolorallocatealpha($png, 0, 0, 0, 127));
                imagecopy($png, $image, 0, 0, 0, 0, $w, $h);
                if (imagepng($png, $targetFile, 9)) {
                    $success_message = "Logo atualizada com sucesso!";
                } else {
                    $error_message = "Erro ao gravar na pasta img/.";
                }
                imagedestroy($image);
                imagedestroy($png);
            }
        }
    }
}

$preview_exists = file_exists($targetFile);
$preview_url    = $preview_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(251,146,60,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(251,146,60,0.10);
    border: 1px solid rgba(251,146,60,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #fb923c;
    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(99,179,237,0.12); border: 1px solid rgba(99,179,237,0.2); color: #63b3ed; }
.ph-icon-preview { background: rgba(52,211,153,0.12); border: 1px solid rgba(52,211,153,0.2); color: #34d399; }
.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(99,179,237,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(99,179,237,0.5);
    background: rgba(99,179,237,0.04);
}
.upload-drop-area i {
    font-size: 36px;
    color: rgba(99,179,237,0.4);
    margin-bottom: 12px;
    display: block;
    transition: color 0.2s ease;
}
.upload-drop-area:hover i { color: #63b3ed; }
.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;
}
#logoInput { 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: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 16px;
    display: none;
}
.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, #1d4ed8, #63b3ed) !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(99,179,237,0.25) !important;
    cursor: pointer;
}
.btn-upload:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(99,179,237,0.35) !important;
}

/* 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 panel */
.preview-bg {
    background: repeating-conic-gradient(rgba(255,255,255,0.04) 0% 25%, transparent 0% 50%) 0 0 / 20px 20px;
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 12px;
    min-height: 220px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    padding: 24px;
    position: relative;
    overflow: hidden;
}
.preview-bg img {
    max-height: 160px;
    max-width: 100%;
    object-fit: contain;
    filter: drop-shadow(0 0 16px rgba(99,179,237,0.3));
    transition: all 0.3s ease;
}
.preview-empty {
    text-align: center;
    color: rgba(148,163,184,0.25);
}
.preview-empty i { font-size: 48px; display: block; 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;
}

/* 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-regular fa-image"></i></span>
            Sua Logotipo
        </h1>
        <p>Faça upload, visualize ou remova o logotipo exibido no sistema.</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 Logotipo</h5>
                    <p>Envie uma nova imagem para o sistema</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <form method="POST" enctype="multipart/form-data" id="uploadForm">
                    <input type="file" id="logoInput" name="logo" accept="image/png,image/jpeg,image/jpg,image/gif">

                    <div class="upload-drop-area" id="dropArea" onclick="document.getElementById(\'logoInput\').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 5 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> Enviar e Salvar Logo
                    </button>
                </form>

                <ul class="tip-list">
                    <li><i class="fa-solid fa-circle-check" style="color:#34d399;"></i> Use PNG com fundo transparente para melhor resultado</li>
                    <li><i class="fa-solid fa-desktop" style="color:#63b3ed;"></i> Resolução ideal: 500×500 px ou proporcional</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-eye"></i></div>
                <div class="logo-panel-header-text">
                    <h5>Visualização Atual</h5>
                    <p>Como a logo aparece no sistema</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <div class="preview-bg">
                    ' . ($preview_exists
                        ? '<img src="' . $preview_url . '" id="imgPreview" alt="Logo atual">'
                        : '<div class="preview-empty" id="previewEmpty">
                                <i class="fa-regular fa-image"></i>
                                <p>Nenhuma logo carregada</p>
                           </div>
                           <img src="" id="imgPreview" style="display:none;" alt="Preview">'
                    ) . '
                </div>

                ' . ($preview_exists ? '
                <div class="d-flex gap-3">
                    <a href="' . $targetFile . '" download class="btn-download">
                        <i class="fa-solid fa-download"></i> Baixar PNG
                    </a>
                    <button onclick="confirmDelete()" class="btn-remove">
                        <i class="fa-solid fa-trash"></i> Remover Logo
                    </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 a logo aqui.
                </div>') . '
            </div>
        </div>
    </div>

</div>
';

include 'includes/layout.php';
?>

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

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

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

    const img = document.getElementById("imgPreview");
    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("logoInput").files = dt.files;
        document.getElementById("logoInput").dispatchEvent(new Event("change"));
    }
});

// Confirmar remoção
function confirmDelete() {
    Swal.fire({
        title: "Remover logo?",
        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_logo";
    });
}
</script>