<?php
require_once __DIR__ . '/admin_header.php';

$error = '';
$success = '';
$logo_path = __DIR__ . '/../assets/images/logo.jpeg';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['logo']['tmp_name'];
        $file_name = $_FILES['logo']['name'];
        $file_size = $_FILES['logo']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        $allowed_exts = ['png', 'jpg', 'jpeg', 'webp'];
        
        if (!in_array($file_ext, $allowed_exts)) {
            $error = 'Invalid image format. Only PNG, JPG, JPEG, and WEBP uploads are accepted.';
        } elseif ($file_size > 8 * 1024 * 1024) { // 8MB limit
            $error = 'Image file size is too large. Please keep logo assets under 8 megabytes.';
        } else {
            $success_flag = false;

            // Attempt GD conversion to guarantee high-quality standard JPEG formatting
            if (extension_loaded('gd')) {
                $img = null;
                if ($file_ext === 'jpg' || $file_ext === 'jpeg') {
                    $img = @imagecreatefromjpeg($file_tmp);
                } elseif ($file_ext === 'png') {
                    $img = @imagecreatefrompng($file_tmp);
                } elseif ($file_ext === 'webp') {
                    $img = @imagecreatefromwebp($file_tmp);
                }

                if ($img) {
                    // Save as high-quality progressive JPEG (98% quality)
                    if (@imagejpeg($img, $logo_path, 98)) {
                        $success_flag = true;
                    }
                    @imagedestroy($img);
                }
            }

            // Fallback: direct move if GD is missing, disabled, or failed to process
            if (!$success_flag) {
                if (@copy($file_tmp, $logo_path) || @move_uploaded_file($file_tmp, $logo_path)) {
                    $success_flag = true;
                }
            }

            if ($success_flag) {
                $success = 'Logo updated successfully! The new branding will propagate across all pages immediately. (Note: You may need to hard refresh [Ctrl+F5] your browser to clear old cached logo versions.)';
            } else {
                $error = 'Failed to write new logo to assets/images/logo.jpeg. Please verify storage permissions.';
            }
        }
    } else {
        $error = 'Please select a valid image file to upload.';
    }
}
?>

<div class="row mb-4">
    <div class="col-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                <li class="breadcrumb-item active" aria-current="page">Logo Settings</li>
            </ol>
        </nav>
        <h2 class="text-white">Branding Logo Settings</h2>
        <p class="text-muted small">Update and customize the global store logo across all customer and backend viewpoints.</p>
    </div>
</div>

<div class="row justify-content-center">
    <div class="col-lg-8 col-xl-7">
        <div class="admin-card mb-4">
            <h4 class="text-white mb-4"><i class="fa-solid fa-image text-warning me-2"></i> Upload New Brand Logo</h4>
            
            <?php if (!empty($error)): ?>
                <div class="alert alert-danger border-danger bg-dark text-danger rounded-3 py-2 px-3 small mb-4" role="alert">
                    <i class="fa-solid fa-circle-exclamation me-2"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($success)): ?>
                <div class="alert alert-success border-success bg-dark text-success rounded-3 py-2 px-3 small mb-4" role="alert">
                    <i class="fa-solid fa-circle-check me-2"></i> <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <form action="change_logo.php" method="POST" enctype="multipart/form-data" class="mb-2">
                <div class="mb-4">
                    <label for="logo" class="form-label text-muted small text-uppercase fw-bold">Select New Logo Asset</label>
                    <input type="file" class="form-control" id="logo" name="logo" accept="image/*" required onchange="previewFile()">
                    <div class="form-text text-muted" style="font-size: 0.7rem;">Accepted types: PNG, JPG, JPEG, WEBP. Maximum file size: 8MB.</div>
                </div>

                <!-- Previews -->
                <div class="row g-4 mb-4">
                    <div class="col-sm-6">
                        <span class="d-block text-muted small mb-2 text-uppercase fw-bold" style="font-size: 0.65rem;">Active Image Asset:</span>
                        <div class="p-3 bg-dark border border-secondary rounded d-flex align-items-center justify-content-center" style="height: 120px;">
                            <img src="../assets/images/logo.jpeg?t=<?php echo time(); ?>" alt="Active Logo" class="navbar-logo" style="height: 32px; width: 82px;">
                        </div>
                        <span class="d-block text-muted small mt-1 text-center" style="font-size: 0.65rem;">Rendered Navbar Size (32x82)</span>
                    </div>

                    <div id="preview-container" class="col-sm-6 d-none">
                        <span class="d-block text-muted small mb-2 text-uppercase fw-bold" style="font-size: 0.65rem;">New Selected Preview:</span>
                        <div class="p-3 bg-dark border border-secondary rounded d-flex align-items-center justify-content-center" style="height: 120px;">
                            <img id="logo-preview" src="#" alt="New Preview" class="navbar-logo" style="height: 32px; width: 82px;">
                        </div>
                        <span class="d-block text-muted small mt-1 text-center" style="font-size: 0.65rem;">Simulated Navbar Rendering</span>
                    </div>
                </div>

                <div class="border-top border-dark pt-4 d-flex justify-content-end gap-3">
                    <button type="submit" class="btn-luxury px-4 py-2">
                        Overwrite Global Logo <i class="fa-solid fa-cloud-arrow-up ms-2"></i>
                    </button>
                </div>
            </form>
        </div>

        <!-- Typography & Layout Instructions Card -->
        <div class="admin-card" style="border-color: rgba(220, 199, 163, 0.15);">
            <h5 class="text-warning mb-3"><i class="fa-solid fa-circle-info me-2"></i> Layout Proportions Notice</h5>
            <p class="text-gray small mb-3">
                To maintain standard minimalist luxury design guidelines, the brand logo is displayed with a highly tailored aspect ratio in the sticky navigation headers:
            </p>
            <ul class="text-gray small ps-3 mb-0" style="line-height: 1.6;">
                <li>The rendered viewport logo dimensions are constrained to <strong class="text-white">32px height</strong> and <strong class="text-white">82px width</strong> (aspect ratio of <strong class="text-white">2.56</strong>).</li>
                <li>The display applies an <strong class="text-white">object-position: top</strong> setting. This means only the top 56% portion of the uploaded image will be framed.</li>
                <li>Ensure the brand conjoined name or letters are aligned at the <strong class="text-white">top center</strong> of your uploaded graphic file.</li>
            </ul>
        </div>
    </div>
</div>

<script>
function previewFile() {
    const preview = document.getElementById('logo-preview');
    const container = document.getElementById('preview-container');
    const file = document.getElementById('logo').files[0];
    const reader = new FileReader();

    reader.addEventListener("load", function () {
        preview.src = reader.result;
        container.classList.remove('d-none');
    }, false);

    if (file) {
        reader.readAsDataURL(file);
    }
}
</script>

<?php
require_once __DIR__ . '/admin_footer.php';
?>
