<?php include ADMIN_PATH . '/templates/header.php'; ?>

<style>
.app-content { overflow-x: hidden; }

.media-slot {
    width: 100%;
    height: 90px;
    border: 1px dashed #dee2e6;
    border-radius: .5rem;
    background: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.media-slot.square { height: 90px; }
.media-slot.large  { height: 100px; }

.media-slot img {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
}
</style>

<div class="container-fluid py-3">

    <!-- Header -->
    <div class="mb-4">
        <h3 class="mb-1">
            <i class="bi bi-brush-fill me-2"></i>
            <?= __('sidebar.manage_site', 'Manage Site') ?>
        </h3>
        <small class="text-muted">
            <?= __('sidebar.manage_site', 'Manage Site') ?> →
            <?= __('settings.site_identity', 'Site Identity') ?>
        </small>
    </div>

    <?php if (isset($_SESSION['settings_saved'])): unset($_SESSION['settings_saved']); ?>
        <div class="alert alert-success">
            <i class="bi bi-check-circle me-1"></i>
            <?= __('ui.success', 'Settings saved successfully!') ?>
        </div>
    <?php endif; ?>

    <!-- Single Form -->
    <form method="POST" action="/admin/settings/identity/save" enctype="multipart/form-data">

        <?= \Core\System\Csrf::field(); ?>

        <!-- Site Logos -->
        <div class="card mb-4">
            <div class="card-header">
                <strong><?= __('settings.logos', 'Logos') ?></strong>
            </div>

            <div class="card-body">
                <div class="row g-4">

                <?php
                if (!function_exists('mte_normalize_asset_url')) {
                    function mte_normalize_asset_url($path): string
                    {
                        $path = trim((string)$path);

                        if ($path === '') {
                            return '';
                        }

                        // absolute URL
                        if (preg_match('#^https?://#i', $path)) {
                            return $path;
                        }

                        // already root-based
                        if ($path[0] === '/') {
                            return $path;
                        }

                        // ensure root-based
                        return '/' . $path;
                    }
                }

                function imageBlock($key, $label, $placeholder, $size, $images, $type = 'large')
                {
                    $stored = $images[$key] ?? '';
                    $current = !empty($stored)
                        ? mte_normalize_asset_url($stored)
                        : $placeholder;

                    $class = $type === 'square' ? 'media-slot square' : 'media-slot large';
                ?>
                    <div class="col-lg-4 col-md-6">
                        <div class="card h-100 shadow-sm">
                            <div class="card-body">

                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <strong class="small"><?= $label ?></strong>

                                    <?php if (!empty($stored)): ?>
                                        <button type="submit"
                                                name="delete_key"
                                                value="<?= $key ?>"
                                                formaction="/admin/settings/identity/delete-image"
                                                formmethod="POST"
                                                onclick="return confirm('<?= __('settings.confirm_delete', 'Delete this image?') ?>');"
                                                class="btn btn-danger btn-sm"
                                                title="<?= __('settings.delete_image', 'Delete image') ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    <?php endif; ?>
                                </div>

                                <div class="<?= $class ?> mb-2">
                                    <img src="<?= htmlspecialchars($current, ENT_QUOTES, 'UTF-8') ?>"
                                         alt=""
                                         data-preview-img="<?= $key ?>">
                                </div>

                                <div class="text-muted small mb-2">
                                    <?= __('settings.recommended_size', 'Recommended size') ?>: <?= $size ?>
                                </div>

                                <input type="file"
                                       name="<?= $key ?>"
                                       accept="image/*"
                                       class="form-control form-control-sm"
                                       data-preview-input="<?= $key ?>">
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <?php
                // === Site Identity Images ===
                imageBlock('site_logo', __('settings.site_logo', 'Site Logo'), '/admin/assets/placeholders/site-logo.png', '200x60', $identityImages);
                imageBlock('favicon', __('settings.favicon', 'Favicon'), '/admin/assets/placeholders/favicon.png', '64x64', $identityImages, 'square');
                imageBlock('preloader', __('settings.preloader', 'Preloader'), '/admin/assets/placeholders/preloader.png', '120x120', $identityImages, 'square');
                imageBlock('dark_logo', __('settings.dark_logo', 'Dark Mode Logo'), '/admin/assets/placeholders/dark-logo.png', '200x60', $identityImages);
                imageBlock('mobile_logo', __('settings.mobile_logo', 'Mobile Logo'), '/admin/assets/placeholders/mobile-logo.png', '160x60', $identityImages);

                // === SEO / Social Share Default Image ===
                imageBlock(
                    'seo_default_image',
                    __('settings.seo_default_image', 'Default Share Image'),
                    '/admin/assets/placeholders/seo-default.png',
                    '1200x630',
                    $identityImages
                );
                ?>

                </div>
            </div>
        </div>

        <!-- Admin Logos -->
        <div class="card mb-4">
            <div class="card-header">
                <strong><?= __('settings.admin_logos', 'Admin Panel Logos') ?></strong>
            </div>

            <div class="card-body">
                <div class="row g-4">

                <?php
                imageBlock('admin_logo', __('settings.admin_logo', 'Admin Logo'), '/admin/assets/placeholders/admin-logo.png', '200x60', $identityImages);
                imageBlock('admin_small_logo', __('settings.admin_small_logo', 'Admin Small Logo'), '/admin/assets/placeholders/admin-small-logo.png', '80x80', $identityImages, 'square');
                imageBlock('footer_logo', __('settings.footer_logo', 'Footer Logo'), '/admin/assets/placeholders/footer-logo.png', '200x60', $identityImages);
                ?>

                </div>
            </div>
        </div>

        <!-- Save -->
        <div class="text-end">
            <button type="submit" class="btn btn-primary px-4">
                <i class="bi bi-save me-1"></i>
                <?= __('actions.save', 'Save') ?>
            </button>
        </div>

    </form>
</div>

<!-- Live Image Preview + Client-side Compression -->
<script>
(function () {

    /* ── ضغط الصورة قبل الرفع (max 4MB, max 1920px) ─────────────────── */
    function compressImage(file, cb) {
        var MAX = 4 * 1024 * 1024;
        if (file.size <= MAX) { cb(file); return; }
        var reader = new FileReader();
        reader.onload = function (e) {
            var img = new Image();
            img.onload = function () {
                var D = 1920, w = img.width, h = img.height;
                if (w > D || h > D) {
                    if (w > h) { h = Math.round(h * D / w); w = D; }
                    else       { w = Math.round(w * D / h); h = D; }
                }
                var c = document.createElement('canvas');
                c.width = w; c.height = h;
                c.getContext('2d').drawImage(img, 0, 0, w, h);
                (function tryQ(q) {
                    c.toBlob(function (blob) {
                        if (!blob) { cb(file); return; }
                        if (blob.size > MAX && q > 0.4) { tryQ(+(q - 0.08).toFixed(2)); return; }
                        cb(new File([blob], file.name, { type: blob.type, lastModified: Date.now() }));
                    }, 'image/jpeg', q);
                })(0.82);
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('input[data-preview-input]').forEach(function (input) {
            input.addEventListener('change', function () {
                var key = this.dataset.previewInput;
                var img = document.querySelector('img[data-preview-img="' + key + '"]');
                var file = this.files && this.files[0];
                if (!file || !img) return;

                compressImage(file, function (compressed) {
                    /* استبدال الملف بالمضغوط في الـ input */
                    if (compressed !== file) {
                        var dt = new DataTransfer();
                        dt.items.add(compressed);
                        input.files = dt.files;
                    }
                    /* معاينة فورية */
                    img.src = URL.createObjectURL(compressed);
                });
            });
        });
    });

})();
</script>

<?php include ADMIN_PATH . '/templates/footer.php'; ?>
