<?php
// ============================================================
//  Admin — edit / add listing
//  POST processing happens before _guard.php for header redirects
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
auth_require_admin();

$listing_id = (int)($_GET['id'] ?? 0);
$action     = $_GET['action'] ?? 'edit';
$is_add     = ($action === 'add');

$listing = null;
$errors  = [];

if (!$is_add) {
    $listing = db_row('SELECT * FROM listings WHERE id=:id', ['id'=>$listing_id]);
    if (!$listing) { http_response_code(404); echo 'Listing not found.'; exit; }

    // Load all categories this listing belongs to
    $listing_cats = db_all(
        'SELECT category_slug, is_primary FROM listing_categories WHERE listing_id=:id',
        ['id'=>$listing_id]
    );
    $selected_cats = array_column($listing_cats, 'category_slug');
    $primary_cat   = null;
    foreach ($listing_cats as $lc) if ($lc['is_primary']) { $primary_cat = $lc['category_slug']; break; }
} else {
    $selected_cats = [];
    $primary_cat   = null;
}

// Slug helper
function listing_slug_unique(string $name, ?int $exclude_id = null): string {
    $base = preg_replace('/[^a-z0-9]+/', '-', strtolower($name));
    $base = trim($base, '-') ?: 'listing';
    $slug = $base; $n = 2;
    while (true) {
        $existing = db_row('SELECT id FROM listings WHERE slug=:s', ['s'=>$slug]);
        if (!$existing || (int)$existing['id'] === (int)$exclude_id) break;
        $slug = $base . '-' . $n++;
    }
    return $slug;
}

// ── Handle POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $name         = trim($_POST['name']         ?? '');
    $cats_posted  = $_POST['categories']        ?? [];  // array of slugs
    $primary      = trim($_POST['primary_category'] ?? '');
    $tier         = trim($_POST['tier']         ?? 'Bronze');
    $tagline      = trim($_POST['tagline']      ?? '');
    $description  = trim($_POST['description']  ?? '');
    $phone        = trim($_POST['phone']        ?? '');
    $email        = trim($_POST['email']        ?? '');
    $website      = trim($_POST['website']      ?? '');
    $address      = trim($_POST['address']      ?? '');
    $member_id    = (int)($_POST['member_id']   ?? 0) ?: null;
    $custom_slug  = trim($_POST['slug']         ?? '');
    $featured     = !empty($_POST['featured']) ? 1 : 0;
    $published    = !empty($_POST['published']) ? 1 : 0;

    if (!is_array($cats_posted)) $cats_posted = [];
    // Dedupe + filter to valid slug format
    $cats_posted = array_values(array_unique(array_filter($cats_posted, fn($s) =>
        is_string($s) && preg_match('/^[a-z0-9\-]+$/', $s)
    )));

    if (!$name)              $errors[] = 'Business name is required.';
    if (empty($cats_posted)) $errors[] = 'At least one category is required.';
    if (!$description)       $errors[] = 'Description is required.';
    if (!in_array($tier, ['Bronze','Silver','Gold','Platinum','Diamond'], true)) {
        $errors[] = 'Invalid tier.';
    }
    if ($custom_slug && !preg_match('/^[a-z0-9\-]+$/', $custom_slug)) {
        $errors[] = 'Slug may only contain lowercase letters, numbers, and hyphens.';
    }
    // If a primary was selected, it must be one of the checked categories
    if ($primary && !in_array($primary, $cats_posted, true)) {
        $primary = $cats_posted[0] ?? '';
    }
    // If none picked as primary, default to first
    if (!$primary && !empty($cats_posted)) $primary = $cats_posted[0];

    // Logo upload
    $logo_path = $listing['logo_path'] ?? null;
    if (!empty($_FILES['logo']['name'])) {
        $file    = $_FILES['logo'];
        $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
        if (!in_array($file['type'], $allowed, true)) {
            $errors[] = 'Logo must be JPG, PNG, GIF or WebP.';
        } elseif ($file['size'] > 2*1024*1024) {
            $errors[] = 'Logo must be under 2MB.';
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Logo upload failed (error '.$file['error'].').';
        } else {
            $dir = __DIR__ . '/../assets/uploads/logos/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name_safe = 'listing-' . ($listing_id ?: time()) . '-' . bin2hex(random_bytes(2)) . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], $dir . $name_safe)) {
                if ($logo_path) {
                    $old = __DIR__ . '/../' . ltrim($logo_path, '/');
                    if (file_exists($old)) @unlink($old);
                }
                $logo_path = 'assets/uploads/logos/' . $name_safe;
            } else {
                $errors[] = 'Could not save logo. Check folder permissions.';
            }
        }
    }
    if (!empty($_POST['remove_logo']) && $logo_path) {
        $old = __DIR__ . '/../' . ltrim($logo_path, '/');
        if (file_exists($old)) @unlink($old);
        $logo_path = null;
    }

    // Banner upload (business photo shown on directory card)
    $banner_path = $listing['banner_path'] ?? null;
    if (!empty($_FILES['banner']['name'])) {
        $file    = $_FILES['banner'];
        $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
        if (!in_array($file['type'], $allowed, true)) {
            $errors[] = 'Banner must be JPG, PNG, GIF or WebP.';
        } elseif ($file['size'] > 5*1024*1024) {
            $errors[] = 'Banner must be under 5MB.';
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Banner upload failed (error '.$file['error'].').';
        } else {
            $dir = __DIR__ . '/../assets/uploads/banners/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name_safe = 'listing-' . ($listing_id ?: time()) . '-' . bin2hex(random_bytes(2)) . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], $dir . $name_safe)) {
                if ($banner_path) {
                    $old = __DIR__ . '/../' . ltrim($banner_path, '/');
                    if (file_exists($old)) @unlink($old);
                }
                $banner_path = 'assets/uploads/banners/' . $name_safe;
            } else {
                $errors[] = 'Could not save banner. Check folder permissions.';
            }
        }
    }
    if (!empty($_POST['remove_banner']) && $banner_path) {
        $old = __DIR__ . '/../' . ltrim($banner_path, '/');
        if (file_exists($old)) @unlink($old);
        $banner_path = null;
    }

    if (empty($errors)) {
        $slug = $custom_slug ?: listing_slug_unique($name, $listing_id ?: null);
        $data = [
            'slug'          => $slug,
            'name'          => $name,
            'category_slug' => $primary,     // kept as the primary category
            'tier'          => $tier,
            'featured'      => $featured,
            'description'   => $description,
            'tagline'       => $tagline ?: null,
            'phone'         => $phone   ?: null,
            'email'         => $email   ?: null,
            'website'       => $website ?: null,
            'address'       => $address ?: null,
            'logo_path'     => $logo_path,
            'banner_path'   => $banner_path,
            'published'     => $published,
            'member_id'     => $member_id,
            'profile_complete' => 1,
        ];

        if ($is_add) {
            $new_id = db_insert('listings', $data);
            // Write category junctions
            foreach ($cats_posted as $c) {
                db_exec(
                    'INSERT IGNORE INTO listing_categories (listing_id, category_slug, is_primary)
                     VALUES (:l, :c, :p)',
                    ['l'=>$new_id, 'c'=>$c, 'p'=>$c === $primary ? 1 : 0]
                );
            }
            header('Location: listings.php?msg=created'); exit;
        } else {
            db_update('listings', $listing_id, $data);
            // Reset junctions
            db_exec('DELETE FROM listing_categories WHERE listing_id=:id', ['id'=>$listing_id]);
            foreach ($cats_posted as $c) {
                db_exec(
                    'INSERT IGNORE INTO listing_categories (listing_id, category_slug, is_primary)
                     VALUES (:l, :c, :p)',
                    ['l'=>$listing_id, 'c'=>$c, 'p'=>$c === $primary ? 1 : 0]
                );
            }
            header('Location: listing-edit.php?id='.$listing_id.'&msg=saved'); exit;
        }
    }

    // Repopulate on error
    $listing = array_merge($listing ?? [], [
        'name'=>$name,'slug'=>$custom_slug,'tier'=>$tier,
        'tagline'=>$tagline,'description'=>$description,'phone'=>$phone,'email'=>$email,
        'website'=>$website,'address'=>$address,'member_id'=>$member_id,
        'featured'=>$featured,'published'=>$published,'logo_path'=>$logo_path,
        'banner_path'=>$banner_path,
    ]);
    $selected_cats = $cats_posted;
    $primary_cat   = $primary;
}

if ($is_add && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $listing = [
        'name'=>'','slug'=>'','tier'=>'Bronze',
        'tagline'=>'','description'=>'','phone'=>'','email'=>'','website'=>'',
        'address'=>'','member_id'=>null,'featured'=>0,'published'=>1,
        'logo_path'=>null,'banner_path'=>null,
    ];
    $selected_cats = [];
    $primary_cat   = null;
}

$categories = db_all('SELECT slug, name FROM categories ORDER BY sort_order, name');
$members    = db_all("SELECT id, email, business_name FROM members ORDER BY business_name");

// Metrics for this listing (only in edit mode)
$metrics = null;
if (!$is_add) {
    try {
        $metrics = [
            'views_30d' => (int)db_value(
                "SELECT COUNT(*) FROM metrics_pageviews WHERE listing_id=:id AND viewed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)",
                ['id'=>$listing_id]
            ),
            'views_all' => (int)db_value(
                "SELECT COUNT(*) FROM metrics_pageviews WHERE listing_id=:id",
                ['id'=>$listing_id]
            ),
            'uniques_30d' => (int)db_value(
                "SELECT COUNT(DISTINCT ip_hash) FROM metrics_pageviews WHERE listing_id=:id AND viewed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)",
                ['id'=>$listing_id]
            ),
        ];
    } catch (Throwable $e) { $metrics = null; }
}

$page_title = $is_add ? 'New listing' : 'Edit — ' . ($listing['name'] ?? '');
require __DIR__ . '/_guard.php';
?>

<style>
.l-layout{display:grid;grid-template-columns:1fr 320px;gap:1.25rem;align-items:start;}
@media(max-width:900px){.l-layout{grid-template-columns:1fr;}}
.b-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.25rem;margin-bottom:1.25rem;}
.b-card h2{margin:0 0 1rem;font-size:.95rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);}
.form-2col{display:grid;grid-template-columns:1fr 1fr;gap:0 1.25rem;}
@media(max-width:600px){.form-2col{grid-template-columns:1fr;}}

.upload-zone{border:2px dashed var(--line);border-radius:var(--radius);padding:1.25rem;text-align:center;cursor:pointer;position:relative;transition:border-color .2s,background .2s;}
.upload-zone:hover,.upload-zone.dragover{border-color:var(--brand-primary);background:rgba(122,157,71,.05);}
.upload-zone input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%;}
.logo-preview-wrap{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1rem;margin-bottom:.75rem;text-align:center;}
.logo-preview-wrap img{max-width:140px;max-height:140px;object-fit:contain;margin:0 auto;display:block;}

.banner-preview-wrap{border-radius:var(--radius);margin-bottom:.75rem;overflow:hidden;background:var(--surface-alt);border:1px solid var(--line);}
.banner-preview-wrap img{width:100%;height:auto;display:block;aspect-ratio:16/9;object-fit:cover;}

.cat-picker{
    border:1px solid var(--line);
    border-radius:var(--radius);
    max-height:280px;
    overflow-y:auto;
    background:#fff;
    margin-bottom:1rem;
}
.cat-row{
    display:flex;
    align-items:center;
    gap:.65rem;
    padding:.45rem .8rem;
    border-bottom:1px solid var(--line);
    cursor:pointer;
    font-size:.88rem;
    font-weight:400;
    margin:0;
}
.cat-row:last-child{border-bottom:none;}
.cat-row:hover{background:#fafafa;}
.cat-row .cat-check{margin:0;}
.cat-row .cat-label{flex:1;}
.cat-row .cat-primary-wrap{display:flex;align-items:center;gap:.3rem;opacity:.3;transition:opacity .15s;}
.cat-row .cat-primary{margin:0;}
.cat-row .cat-primary-lbl{font-size:.7rem;text-transform:uppercase;letter-spacing:.04em;color:var(--ink-muted);}
.cat-row.has-check .cat-primary-wrap{opacity:1;}

.m-stat-mini{background:var(--surface-alt);border-radius:var(--radius);padding:.75rem 1rem;text-align:center;}
.m-stat-mini .lbl{font-size:.7rem;text-transform:uppercase;color:var(--ink-muted);margin:0;}
.m-stat-mini .val{font-size:1.4rem;font-weight:800;margin:.25rem 0 0;}
</style>

<section class="section">
<div class="container">

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.1rem;">
    <div>
        <p class="muted" style="margin:0;"><a href="listings.php">← All listings</a></p>
        <h1 style="margin:.25rem 0 0;"><?= $is_add ? 'Add a listing' : 'Edit listing' ?></h1>
    </div>
    <?php if (!$is_add): ?>
        <a href="../directory-item.php?id=<?= $listing_id ?>" target="_blank" class="btn btn-outline">
            View live listing ↗
        </a>
    <?php endif; ?>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-bottom:1rem;">
        <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
    </div>
<?php endif; ?>
<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success" data-autohide>Saved.</div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data"
      action="listing-edit.php?<?= $is_add?'action=add':'id='.$listing_id ?>">
    <?= csrf_field() ?>

    <div class="l-layout">

        <!-- ── Main column ── -->
        <div>
            <!-- Basics -->
            <div class="b-card">
                <h2>Business details</h2>

                <label>Business name *</label>
                <input type="text" name="name" id="l-name" required
                       value="<?= htmlspecialchars($listing['name'] ?? '') ?>">

                <label>Slug <small>(URL identifier, auto from name if blank)</small></label>
                <input type="text" name="slug" id="l-slug"
                       value="<?= htmlspecialchars($listing['slug'] ?? '') ?>"
                       placeholder="auto" pattern="[a-z0-9\-]+">

                <label>Tagline <small>(one short line shown under the name)</small></label>
                <input type="text" name="tagline" maxlength="200"
                       value="<?= htmlspecialchars($listing['tagline'] ?? '') ?>">

                <label>Description *</label>
                <textarea name="description" rows="5" required><?= htmlspecialchars($listing['description'] ?? '') ?></textarea>

                <label>Categories * <small>(tick all that apply — pick a primary with the radio)</small></label>
                <div class="cat-picker">
                    <?php foreach ($categories as $c):
                        $slug = $c['slug'];
                        $checked = in_array($slug, $selected_cats, true);
                        $is_pri  = ($primary_cat ?? '') === $slug;
                    ?>
                        <label class="cat-row">
                            <input type="checkbox" name="categories[]" value="<?= htmlspecialchars($slug) ?>"
                                   <?= $checked ? 'checked' : '' ?> class="cat-check">
                            <span class="cat-label"><?= htmlspecialchars($c['name']) ?></span>
                            <span class="cat-primary-wrap">
                                <input type="radio" name="primary_category" value="<?= htmlspecialchars($slug) ?>"
                                       <?= $is_pri ? 'checked' : '' ?> class="cat-primary"
                                       title="Mark as primary category">
                                <span class="cat-primary-lbl">primary</span>
                            </span>
                        </label>
                    <?php endforeach; ?>
                </div>

                <label>Tier *</label>
                <select name="tier" required>
                    <?php foreach (['Bronze','Silver','Gold','Platinum','Diamond'] as $t): ?>
                        <option value="<?= $t ?>" <?= ($listing['tier'] ?? '') === $t ? 'selected' : '' ?>>
                            <?= $t ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Contact -->
            <div class="b-card">
                <h2>Contact &amp; location</h2>
                <div class="form-2col">
                    <div>
                        <label>Phone</label>
                        <input type="tel" name="phone" value="<?= htmlspecialchars($listing['phone'] ?? '') ?>">
                    </div>
                    <div>
                        <label>Email</label>
                        <input type="email" name="email" value="<?= htmlspecialchars($listing['email'] ?? '') ?>">
                    </div>
                </div>
                <label>Website</label>
                <input type="url" name="website" value="<?= htmlspecialchars($listing['website'] ?? '') ?>"
                       placeholder="https://">
                <label>Physical address</label>
                <input type="text" name="address" value="<?= htmlspecialchars($listing['address'] ?? '') ?>">
            </div>
        </div>

        <!-- ── Sidebar ── -->
        <div>
            <!-- Status -->
            <div class="b-card">
                <h2>Publish</h2>
                <label style="display:flex;align-items:center;gap:.5rem;font-weight:400;cursor:pointer;margin-bottom:.75rem;">
                    <input type="checkbox" name="published" value="1" <?= !empty($listing['published']) ? 'checked' : '' ?>>
                    <span>Published (visible on directory)</span>
                </label>
                <label style="display:flex;align-items:center;gap:.5rem;font-weight:400;cursor:pointer;">
                    <input type="checkbox" name="featured" value="1" <?= !empty($listing['featured']) ? 'checked' : '' ?>>
                    <span>⭐ Featured</span>
                </label>

                <div style="display:flex;flex-direction:column;gap:.4rem;margin-top:1rem;">
                    <button type="submit" class="btn"><?= $is_add ? 'Create listing' : 'Save changes' ?></button>
                    <a href="listings.php" class="btn btn-outline" style="text-align:center;">Cancel</a>
                </div>
            </div>

            <!-- Owner -->
            <div class="b-card">
                <h2>Claimed by</h2>
                <select name="member_id">
                    <option value="0">— Unclaimed —</option>
                    <?php foreach ($members as $m): ?>
                        <option value="<?= $m['id'] ?>"
                                <?= ($listing['member_id'] ?? 0) == $m['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($m['business_name']) ?> — <?= htmlspecialchars($m['email']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Logo -->
            <div class="b-card">
                <h2>Logo</h2>
                <?php if (!empty($listing['logo_path'])): ?>
                    <div class="logo-preview-wrap" id="logo-preview-current">
                        <img src="../<?= htmlspecialchars($listing['logo_path']) ?>" alt="logo">
                    </div>
                    <label style="display:flex;align-items:center;gap:.4rem;font-size:.82rem;font-weight:400;margin-bottom:.75rem;cursor:pointer;">
                        <input type="checkbox" name="remove_logo" value="1">
                        Remove current logo
                    </label>
                <?php endif; ?>

                <!-- Inline preview of newly selected logo (before save) -->
                <div class="logo-preview-wrap" id="logo-preview-new" style="display:none;margin-bottom:.75rem;">
                    <img id="logo-preview-new-src" src="" alt="new logo preview">
                </div>
                <p id="logo-preview-new-label" style="display:none;font-size:.78rem;color:var(--brand-primary);margin:0 0 .75rem;font-weight:600;">
                    ✓ New logo selected — click "Save changes" to upload.
                </p>

                <div class="upload-zone" id="logo-zone">
                    <input type="file" name="logo" id="logo-input"
                           accept="image/jpeg,image/png,image/gif,image/webp">
                    <div>
                        <div style="font-size:1.5rem;">🖼</div>
                        <p style="font-size:.82rem;margin:.4rem 0 0;color:var(--ink-muted);">
                            Click or drag · JPG/PNG, max 2MB
                        </p>
                    </div>
                </div>
            </div>

            <!-- Banner / business photo -->
            <div class="b-card">
                <h2>Business photo / banner</h2>
                <p class="muted" style="font-size:.82rem;margin:0 0 1rem;">
                    Shown at the top of the directory card and the business detail page.
                    If left blank, the logo is used in its place.
                    Landscape / wide photos work best.
                </p>

                <?php if (!empty($listing['banner_path'])): ?>
                    <div class="banner-preview-wrap" id="banner-preview-current">
                        <img src="../<?= htmlspecialchars($listing['banner_path']) ?>" alt="banner">
                    </div>
                    <label style="display:flex;align-items:center;gap:.4rem;font-size:.82rem;font-weight:400;margin-bottom:.75rem;cursor:pointer;">
                        <input type="checkbox" name="remove_banner" value="1">
                        Remove current photo
                    </label>
                <?php endif; ?>

                <div class="banner-preview-wrap" id="banner-preview-new" style="display:none;margin-bottom:.75rem;">
                    <img id="banner-preview-new-src" src="" alt="new banner preview">
                </div>
                <p id="banner-preview-new-label" style="display:none;font-size:.78rem;color:var(--brand-primary);margin:0 0 .75rem;font-weight:600;">
                    ✓ New photo selected — click "Save changes" to upload.
                </p>

                <div class="upload-zone" id="banner-zone">
                    <input type="file" name="banner" id="banner-input"
                           accept="image/jpeg,image/png,image/gif,image/webp">
                    <div>
                        <div style="font-size:1.5rem;">🏢</div>
                        <p style="font-size:.82rem;margin:.4rem 0 0;color:var(--ink-muted);">
                            Click or drag · JPG/PNG, max 5MB
                        </p>
                    </div>
                </div>
            </div>

            <?php if ($metrics): ?>
            <!-- Metrics -->
            <div class="b-card">
                <h2>Views</h2>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:.5rem;">
                    <div class="m-stat-mini">
                        <p class="lbl">Last 30d</p>
                        <p class="val" style="color:var(--brand-primary);"><?= number_format($metrics['views_30d']) ?></p>
                    </div>
                    <div class="m-stat-mini">
                        <p class="lbl">Unique</p>
                        <p class="val"><?= number_format($metrics['uniques_30d']) ?></p>
                    </div>
                </div>
                <p style="text-align:center;margin:.75rem 0 0;font-size:.82rem;color:var(--ink-muted);">
                    <?= number_format($metrics['views_all']) ?> views all-time
                </p>
            </div>
            <?php endif; ?>
        </div>
    </div>
</form>

</div>
</section>

<script>
// Auto-slug from name
const nameEl = document.getElementById('l-name');
const slugEl = document.getElementById('l-slug');
if (nameEl && slugEl) {
    nameEl.addEventListener('input', function () {
        if (!slugEl.dataset.edited) {
            slugEl.value = this.value.toLowerCase()
                .replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
        }
    });
    slugEl.addEventListener('input', () => slugEl.dataset.edited = '1');
}

// Logo drag-and-drop + inline preview
const lzone = document.getElementById('logo-zone');
const linput = document.getElementById('logo-input');
const logoPreviewBox     = document.getElementById('logo-preview-new');
const logoPreviewImg     = document.getElementById('logo-preview-new-src');
const logoPreviewLabel   = document.getElementById('logo-preview-new-label');
const logoPreviewCurrent = document.getElementById('logo-preview-current');

function showLogoPreview(file) {
    if (!file || !logoPreviewBox || !logoPreviewImg) return;
    const reader = new FileReader();
    reader.onload = (e) => {
        logoPreviewImg.src = e.target.result;
        logoPreviewBox.style.display = 'block';
        if (logoPreviewLabel) logoPreviewLabel.style.display = 'block';
        if (logoPreviewCurrent) logoPreviewCurrent.style.opacity = '0.35';
    };
    reader.readAsDataURL(file);
}

if (lzone && linput) {
    lzone.addEventListener('dragover',  e => { e.preventDefault(); lzone.classList.add('dragover'); });
    lzone.addEventListener('dragleave', () => lzone.classList.remove('dragover'));
    lzone.addEventListener('drop', e => {
        e.preventDefault(); lzone.classList.remove('dragover');
        if (e.dataTransfer.files[0]) {
            const dt = new DataTransfer();
            dt.items.add(e.dataTransfer.files[0]);
            linput.files = dt.files;
            showLogoPreview(e.dataTransfer.files[0]);
        }
    });
    linput.addEventListener('change', () => {
        if (linput.files && linput.files[0]) showLogoPreview(linput.files[0]);
    });
}

// ── Banner drag-and-drop + preview ──
const bz = document.getElementById('banner-zone');
const bi = document.getElementById('banner-input');
const bannerPreviewBox     = document.getElementById('banner-preview-new');
const bannerPreviewImg     = document.getElementById('banner-preview-new-src');
const bannerPreviewLabel   = document.getElementById('banner-preview-new-label');
const bannerPreviewCurrent = document.getElementById('banner-preview-current');

function showBannerPreview(file) {
    if (!file || !bannerPreviewBox || !bannerPreviewImg) return;
    const reader = new FileReader();
    reader.onload = (e) => {
        bannerPreviewImg.src = e.target.result;
        bannerPreviewBox.style.display = 'block';
        if (bannerPreviewLabel) bannerPreviewLabel.style.display = 'block';
        if (bannerPreviewCurrent) bannerPreviewCurrent.style.opacity = '0.35';
    };
    reader.readAsDataURL(file);
}

if (bz && bi) {
    bz.addEventListener('dragover',  e => { e.preventDefault(); bz.classList.add('dragover'); });
    bz.addEventListener('dragleave', () => bz.classList.remove('dragover'));
    bz.addEventListener('drop', e => {
        e.preventDefault(); bz.classList.remove('dragover');
        if (e.dataTransfer.files[0]) {
            const dt = new DataTransfer();
            dt.items.add(e.dataTransfer.files[0]);
            bi.files = dt.files;
            showBannerPreview(e.dataTransfer.files[0]);
        }
    });
    bi.addEventListener('change', () => {
        if (bi.files && bi.files[0]) showBannerPreview(bi.files[0]);
    });
}

// ── Category picker: only show "primary" radio for checked rows;
//    auto-select first checkbox as primary if none chosen yet ──
(function () {
    const rows = document.querySelectorAll('.cat-row');
    function syncRows() {
        let anyPrimaryChecked = false;
        rows.forEach(r => {
            const ck = r.querySelector('.cat-check');
            r.classList.toggle('has-check', ck.checked);
            const pri = r.querySelector('.cat-primary');
            pri.disabled = !ck.checked;
            if (pri.checked && ck.checked) anyPrimaryChecked = true;
        });
        // If no primary is currently valid, pick first checked
        if (!anyPrimaryChecked) {
            for (const r of rows) {
                const ck = r.querySelector('.cat-check');
                if (ck.checked) {
                    r.querySelector('.cat-primary').checked = true;
                    break;
                }
            }
        }
    }
    rows.forEach(r => {
        r.querySelector('.cat-check').addEventListener('change', syncRows);
        // Clicking the primary radio also auto-checks the box
        r.querySelector('.cat-primary').addEventListener('change', () => {
            r.querySelector('.cat-check').checked = true;
            syncRows();
        });
    });
    syncRows();
})();
</script>

<?php require __DIR__ . '/_footer.php'; ?>