<?php
/**
 * Admin — Banner Manager (Unified: Mobile + Desktop images, shared text)
 * Path: admin/banner.php
 */
require_once 'layout-header.php';

ensure_banner_columns();

$msg_success = '';
$msg_error   = '';
$action      = isset($_GET['action']) ? $_GET['action'] : 'list';
$edit_id     = isset($_GET['id']) ? intval($_GET['id']) : 0;

function banner_admin_preview_url($url) {
    if (empty($url)) return '';
    return (strpos($url, 'uploads/') === 0) ? '../' . $url : $url;
}

if ($action === 'delete' && $edit_id > 0) {
    if (delete_banner($edit_id)) {
        $msg_success = 'ব্যানার সফলভাবে মুছে ফেলা হয়েছে।';
    } else {
        $msg_error = 'ব্যানার মুছতে সমস্যা হয়েছে।';
    }
    $action = 'list';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action'])) {
    $title       = trim($_POST['title'] ?? '');
    $subtitle    = trim($_POST['subtitle'] ?? '');
    $button_text = trim($_POST['button_text'] ?? '');
    $button_link = trim($_POST['button_link'] ?? '');
    $is_active   = isset($_POST['is_active']) ? 1 : 0;
    $sort_order  = intval($_POST['sort_order'] ?? 0);
    $banner_id   = intval($_POST['banner_id'] ?? 0);

    $desktop_url    = trim($_POST['desktop_image_url'] ?? '');
    $desktop_source = 'url';
    $mobile_url     = trim($_POST['mobile_image_url'] ?? '');
    $mobile_source  = 'url';

    $existing = ($banner_id > 0) ? get_banner_by_id($banner_id) : null;

    if (isset($_FILES['mobile_image_file']) && $_FILES['mobile_image_file']['error'] === UPLOAD_ERR_OK) {
        $upload = handle_banner_upload($_FILES['mobile_image_file']);
        if ($upload['success']) {
            if ($existing && ($existing['mobile_image_source'] ?? '') === 'upload') {
                delete_banner_upload_file($existing['mobile_image_url'] ?? '');
            }
            $mobile_url    = $upload['path'];
            $mobile_source = 'upload';
        } else {
            $msg_error = $upload['error'];
        }
    }

    if (empty($msg_error) && isset($_FILES['desktop_image_file']) && $_FILES['desktop_image_file']['error'] === UPLOAD_ERR_OK) {
        $upload = handle_banner_upload($_FILES['desktop_image_file']);
        if ($upload['success']) {
            if ($existing && ($existing['desktop_image_source'] ?? '') === 'upload') {
                delete_banner_upload_file($existing['desktop_image_url'] ?? '');
            }
            $desktop_url    = $upload['path'];
            $desktop_source = 'upload';
        } else {
            $msg_error = $upload['error'];
        }
    }

    if (empty($msg_error) && $existing) {
        if (empty($desktop_url)) {
            $desktop_url    = banner_get_desktop_image($existing);
            $desktop_source = !empty($existing['desktop_image_url'])
                ? ($existing['desktop_image_source'] ?? 'url')
                : ($existing['image_source'] ?? 'url');
        }
        if (empty($mobile_url)) {
            $mobile_url    = banner_get_mobile_image($existing);
            $mobile_source = !empty($existing['mobile_image_url'])
                ? ($existing['mobile_image_source'] ?? 'url')
                : ($existing['image_source'] ?? 'url');
        }
    }

    if (empty($msg_error) && empty($desktop_url) && empty($mobile_url)) {
        $msg_error = 'কমপক্ষে একটি ইমেজ দিন — Mobile অথবা Desktop।';
    }

    if (empty($msg_error)) {
        $data = [
            'title'                => $title,
            'subtitle'             => $subtitle,
            'button_text'          => $button_text,
            'button_link'          => $button_link,
            'desktop_image_url'    => $desktop_url,
            'desktop_image_source' => $desktop_source,
            'mobile_image_url'     => $mobile_url,
            'mobile_image_source'  => $mobile_source,
            'is_active'            => $is_active,
            'sort_order'           => $sort_order,
        ];
        if ($_POST['form_action'] === 'edit_banner' && $banner_id > 0) {
            $ok = save_banner($data, $banner_id);
        } else {
            $ok = save_banner($data);
        }
        if ($ok) {
            $msg_success = 'ব্যানার সফলভাবে সেভ হয়েছে!';
            $action = 'list';
        } else {
            $msg_error = 'সেভ করতে সমস্যা হয়েছে।';
        }
    }
}

$banners = get_banners(null, false);
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">Banner Manager</h1>
            <p class="text-xs text-slate-400 mt-1">এক ফর্মে Mobile (4:3) ও Desktop (16:9) ইমেজ — টেক্সট একই থাকবে</p>
        </div>
        <?php if ($action === 'list'): ?>
        <a href="?action=add" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-plus-circle mr-2"></i> Add Banner
        </a>
        <?php else: ?>
        <a href="banner.php" class="bg-slate-800 hover:bg-slate-700 text-slate-300 px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-arrow-left mr-2"></i> Back
        </a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-circle-check mr-3"></i> <?php echo $msg_success; ?>
    </div>
    <?php endif; ?>
    <?php if ($msg_error): ?>
    <div class="p-4 bg-red-950/40 border border-red-800 text-red-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-triangle-exclamation mr-3"></i> <?php echo $msg_error; ?>
    </div>
    <?php endif; ?>

    <?php if ($action === 'add' || $action === 'edit'):
        $form_action = 'add_banner';
        $val = [
            'title' => '', 'subtitle' => '', 'button_text' => '', 'button_link' => '',
            'mobile_image_url' => '', 'desktop_image_url' => '',
            'is_active' => 1, 'sort_order' => 0,
        ];
        if ($action === 'edit' && $edit_id > 0) {
            $form_action = 'edit_banner';
            $existing = get_banner_by_id($edit_id);
            if ($existing) {
                $val = array_merge($val, $existing);
                $val['mobile_image_url']  = banner_get_mobile_image($existing);
                $val['desktop_image_url'] = banner_get_desktop_image($existing);
            }
        }
        $mob_preview  = banner_admin_preview_url($val['mobile_image_url']);
        $desk_preview = banner_admin_preview_url($val['desktop_image_url']);
    ?>
    <div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
        <form method="post" action="" enctype="multipart/form-data" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5">
            <input type="hidden" name="form_action" value="<?php echo $form_action; ?>">
            <?php if ($action === 'edit'): ?><input type="hidden" name="banner_id" value="<?php echo $edit_id; ?>"><?php endif; ?>

            <h2 class="text-sm font-bold uppercase text-sky-400 tracking-wider border-b border-slate-800/80 pb-3">
                <i class="fa-solid fa-image mr-2"></i> Banner Images
            </h2>

            <!-- Mobile Image -->
            <div class="space-y-3 p-4 bg-slate-950/50 border border-slate-800 rounded-xl">
                <label class="block text-xs font-bold uppercase text-emerald-400">
                    <i class="fa-solid fa-mobile-screen mr-1"></i> Mobile — 4:3
                </label>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                        <span class="text-[10px] text-slate-500 font-bold uppercase block mb-1">লোকালি সিলেক্ট</span>
                        <input type="file" name="mobile_image_file" id="mobile-file" accept="image/*"
                            class="w-full bg-slate-950 border border-slate-800 rounded-xl px-2 py-2 text-xs text-slate-400">
                    </div>
                    <div>
                        <span class="text-[10px] text-slate-500 font-bold uppercase block mb-1">অথবা URL</span>
                        <input type="url" name="mobile_image_url" id="mobile-url" value="<?php echo htmlspecialchars($val['mobile_image_url']); ?>"
                            placeholder="https://..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-xs text-slate-100">
                    </div>
                </div>
            </div>

            <!-- Desktop Image -->
            <div class="space-y-3 p-4 bg-slate-950/50 border border-slate-800 rounded-xl">
                <label class="block text-xs font-bold uppercase text-sky-400">
                    <i class="fa-solid fa-desktop mr-1"></i> Desktop — 16:9 Wide
                </label>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                        <span class="text-[10px] text-slate-500 font-bold uppercase block mb-1">লোকালি সিলেক্ট</span>
                        <input type="file" name="desktop_image_file" id="desktop-file" accept="image/*"
                            class="w-full bg-slate-950 border border-slate-800 rounded-xl px-2 py-2 text-xs text-slate-400">
                    </div>
                    <div>
                        <span class="text-[10px] text-slate-500 font-bold uppercase block mb-1">অথবা URL</span>
                        <input type="url" name="desktop_image_url" id="desktop-url" value="<?php echo htmlspecialchars($val['desktop_image_url']); ?>"
                            placeholder="https://..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-xs text-slate-100">
                    </div>
                </div>
            </div>

            <p class="text-[11px] text-slate-500 leading-relaxed">
                <i class="fa-solid fa-circle-info mr-1 text-sky-500"></i>
                Desktop খালি রাখলে সাইটে Mobile ইমেজ দেখাবে। Mobile খালি রাখলে Desktop দেখাবে।
            </p>

            <h2 class="text-sm font-bold uppercase text-sky-400 tracking-wider border-b border-slate-800/80 pb-3 pt-2">
                <i class="fa-solid fa-font mr-2"></i> Banner Text (Shared)
            </h2>

            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Title <span class="text-slate-600 normal-case">(optional)</span></label>
                <input type="text" name="title" id="banner-title" value="<?php echo htmlspecialchars($val['title']); ?>"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Subtitle <span class="text-slate-600 normal-case">(optional)</span></label>
                <textarea name="subtitle" id="banner-subtitle" rows="2"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100"><?php echo htmlspecialchars($val['subtitle']); ?></textarea>
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Button Text <span class="text-slate-600 normal-case">(optional)</span></label>
                    <input type="text" name="button_text" id="banner-btn-text" value="<?php echo htmlspecialchars($val['button_text']); ?>"
                        class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                </div>
                <div>
                    <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Button Link</label>
                    <input type="text" name="button_link" value="<?php echo htmlspecialchars($val['button_link']); ?>"
                        placeholder="#contact বা URL" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                </div>
            </div>

            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Sort Order</label>
                <input type="number" name="sort_order" value="<?php echo (int)$val['sort_order']; ?>" min="0"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>

            <label class="flex items-center gap-3 cursor-pointer">
                <input type="checkbox" name="is_active" value="1" <?php echo $val['is_active'] ? 'checked' : ''; ?> class="accent-sky-500 w-4 h-4">
                <span class="text-sm font-semibold text-slate-300">Active (সাইটে দেখান)</span>
            </label>

            <button type="submit" class="w-full bg-sky-500 hover:bg-sky-600 text-slate-950 font-black py-3.5 rounded-xl text-xs uppercase">
                <i class="fa-solid fa-floppy-disk mr-2"></i> Save Banner
            </button>
        </form>

        <!-- Live Preview -->
        <div class="space-y-4">
            <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-5">
                <h3 class="text-xs font-bold uppercase text-sky-400 mb-3"><i class="fa-solid fa-desktop mr-2"></i> Desktop Preview (16:9)</h3>
                <div id="preview-desktop" class="relative rounded-xl overflow-hidden aspect-video bg-slate-950">
                    <?php if ($desk_preview): ?>
                    <img id="desk-img" src="<?php echo htmlspecialchars($desk_preview); ?>" class="w-full h-full object-cover" alt="">
                    <?php else: ?>
                    <div id="desk-placeholder" class="w-full h-full flex items-center justify-center text-slate-600 text-xs">Desktop ইমেজ সিলেক্ট করুন</div>
                    <img id="desk-img" src="" class="w-full h-full object-cover hidden" alt="">
                    <?php endif; ?>
                    <div class="absolute inset-0 bg-gradient-to-r from-black/70 to-transparent flex items-center p-6">
                        <div id="desk-text">
                            <?php if ($val['title']): ?><h4 class="text-white font-black text-lg uppercase"><?php echo htmlspecialchars($val['title']); ?></h4><?php endif; ?>
                            <?php if ($val['subtitle']): ?><p class="text-slate-300 text-xs mt-1"><?php echo htmlspecialchars($val['subtitle']); ?></p><?php endif; ?>
                            <?php if ($val['button_text']): ?><span class="inline-block mt-3 bg-sky-500 text-slate-950 text-xs font-bold px-4 py-2 rounded-lg"><?php echo htmlspecialchars($val['button_text']); ?></span><?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-5">
                <h3 class="text-xs font-bold uppercase text-emerald-400 mb-3"><i class="fa-solid fa-mobile-screen mr-2"></i> Mobile Preview (4:3)</h3>
                <div id="preview-mobile" class="relative rounded-xl overflow-hidden aspect-[4/3] bg-slate-950 max-w-xs mx-auto">
                    <?php if ($mob_preview): ?>
                    <img id="mob-img" src="<?php echo htmlspecialchars($mob_preview); ?>" class="w-full h-full object-cover" alt="">
                    <?php else: ?>
                    <div id="mob-placeholder" class="w-full h-full flex items-center justify-center text-slate-600 text-xs">Mobile ইমেজ সিলেক্ট করুন</div>
                    <img id="mob-img" src="" class="w-full h-full object-cover hidden" alt="">
                    <?php endif; ?>
                    <div class="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent flex items-end p-4">
                        <div id="mob-text">
                            <?php if ($val['title']): ?><h4 class="text-white font-black text-sm uppercase"><?php echo htmlspecialchars($val['title']); ?></h4><?php endif; ?>
                            <?php if ($val['button_text']): ?><span class="inline-block mt-2 bg-sky-500 text-slate-950 text-[10px] font-bold px-3 py-1.5 rounded"><?php echo htmlspecialchars($val['button_text']); ?></span><?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const mobileUrl  = document.getElementById('mobile-url');
        const desktopUrl = document.getElementById('desktop-url');
        const mobileFile = document.getElementById('mobile-file');
        const desktopFile= document.getElementById('desktop-file');
        const titleInput = document.getElementById('banner-title');
        const subInput   = document.getElementById('banner-subtitle');
        const btnInput   = document.getElementById('banner-btn-text');

        function resolveUrl(url) {
            if (!url) return '';
            return url.startsWith('uploads/') ? '../' + url : url;
        }

        function setPreviewImg(imgId, placeholderId, src) {
            const img = document.getElementById(imgId);
            const ph  = document.getElementById(placeholderId);
            if (!img) return;
            if (src) {
                img.src = src;
                img.classList.remove('hidden');
                if (ph) ph.classList.add('hidden');
            } else {
                img.src = '';
                img.classList.add('hidden');
                if (ph) ph.classList.remove('hidden');
            }
        }

        function updateTextPreview() {
            const title = titleInput.value;
            const sub   = subInput.value;
            const btn   = btnInput.value;
            const deskText = document.getElementById('desk-text');
            const mobText  = document.getElementById('mob-text');
            if (deskText) deskText.innerHTML =
                (title ? `<h4 class="text-white font-black text-lg uppercase">${title}</h4>` : '') +
                (sub   ? `<p class="text-slate-300 text-xs mt-1">${sub}</p>` : '') +
                (btn   ? `<span class="inline-block mt-3 bg-sky-500 text-slate-950 text-xs font-bold px-4 py-2 rounded-lg">${btn}</span>` : '');
            if (mobText) mobText.innerHTML =
                (title ? `<h4 class="text-white font-black text-sm uppercase">${title}</h4>` : '') +
                (btn   ? `<span class="inline-block mt-2 bg-sky-500 text-slate-950 text-[10px] font-bold px-3 py-1.5 rounded">${btn}</span>` : '');
        }

        function updatePreview() {
            setPreviewImg('mob-img', 'mob-placeholder', resolveUrl(mobileUrl.value));
            setPreviewImg('desk-img', 'desk-placeholder', resolveUrl(desktopUrl.value));
            updateTextPreview();
        }

        [mobileUrl, desktopUrl, titleInput, subInput, btnInput].forEach(el => el && el.addEventListener('input', updatePreview));

        function previewFile(input, imgId, placeholderId) {
            input.addEventListener('change', () => {
                const file = input.files && input.files[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = e => setPreviewImg(imgId, placeholderId, e.target.result);
                reader.readAsDataURL(file);
            });
        }
        previewFile(mobileFile, 'mob-img', 'mob-placeholder');
        previewFile(desktopFile, 'desk-img', 'desk-placeholder');
    </script>

    <?php else: ?>
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        <?php if (empty($banners)): ?>
        <div class="col-span-full text-center py-16 text-slate-500">
            <i class="fa-solid fa-image text-3xl mb-3 block opacity-30"></i>
            <p class="text-sm">কোনো ব্যানার নেই। Add Banner ক্লিক করুন।</p>
        </div>
        <?php else: foreach ($banners as $b):
            $mob_img  = banner_admin_preview_url(banner_get_mobile_image($b));
            $desk_img = banner_admin_preview_url(banner_get_desktop_image($b));
        ?>
        <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden group hover:border-sky-500/30 transition-all relative">
            <div class="grid grid-cols-2 gap-0.5 bg-slate-950">
                <div class="aspect-[4/3] relative overflow-hidden">
                    <?php if ($mob_img): ?>
                    <img src="<?php echo htmlspecialchars($mob_img); ?>" class="w-full h-full object-cover" alt="Mobile">
                    <?php else: ?>
                    <div class="w-full h-full flex items-center justify-center text-[9px] text-slate-600">No Mobile</div>
                    <?php endif; ?>
                    <span class="absolute bottom-1 left-1 text-[8px] font-bold uppercase px-1.5 py-0.5 rounded bg-emerald-500/80 text-slate-950">Mobile</span>
                </div>
                <div class="aspect-video relative overflow-hidden">
                    <?php if ($desk_img): ?>
                    <img src="<?php echo htmlspecialchars($desk_img); ?>" class="w-full h-full object-cover" alt="Desktop">
                    <?php else: ?>
                    <div class="w-full h-full flex items-center justify-center text-[9px] text-slate-600">No Desktop</div>
                    <?php endif; ?>
                    <span class="absolute bottom-1 left-1 text-[8px] font-bold uppercase px-1.5 py-0.5 rounded bg-sky-500/80 text-slate-950">Desktop</span>
                </div>
            </div>
            <span class="absolute top-2 right-2 text-[9px] font-bold uppercase px-2 py-0.5 rounded-full <?php echo $b['is_active'] ? 'bg-emerald-500/80 text-white' : 'bg-slate-700 text-slate-400'; ?>">
                <?php echo $b['is_active'] ? 'Active' : 'Inactive'; ?>
            </span>
            <div class="p-4 space-y-2">
                <h3 class="font-bold text-white text-sm truncate"><?php echo htmlspecialchars($b['title'] ?: '(No Title)'); ?></h3>
                <p class="text-[10px] text-slate-500 truncate"><?php echo htmlspecialchars($b['subtitle'] ?: '—'); ?></p>
                <div class="flex gap-2 pt-2">
                    <a href="?action=edit&id=<?php echo $b['id']; ?>" class="flex-1 text-center bg-slate-800 hover:bg-sky-500 hover:text-slate-950 text-sky-400 py-2 rounded-lg text-xs font-bold transition-all">
                        <i class="fa-solid fa-pen mr-1"></i> Edit
                    </a>
                    <a href="?action=delete&id=<?php echo $b['id']; ?>" onclick="return confirm('ব্যানার মুছে ফেলবেন?');"
                        class="px-3 bg-slate-800 hover:bg-red-500 hover:text-white text-red-400 py-2 rounded-lg text-xs transition-all">
                        <i class="fa-solid fa-trash"></i>
                    </a>
                </div>
            </div>
        </div>
        <?php endforeach; endif; ?>
    </div>
    <?php endif; ?>

</main>

<?php require_once 'layout-footer.php'; ?>
