<?php
// POST handling before _guard so header() redirects work
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
auth_require_admin();

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

$cat    = null;
$errors = [];

if (!$is_add) {
    $cat = db_row('SELECT * FROM categories WHERE id=:id', ['id'=>$cat_id]);
    if (!$cat) { http_response_code(404); echo 'Category not found.'; exit; }
}

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

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

    $name        = trim($_POST['name'] ?? '');
    $custom_slug = trim($_POST['slug'] ?? '');
    $icon        = trim($_POST['icon'] ?? '');
    $sort_order  = (int)($_POST['sort_order'] ?? 0);

    if (!$name) $errors[] = 'Name is required.';
    if ($custom_slug && !preg_match('/^[a-z0-9\-]+$/', $custom_slug)) {
        $errors[] = 'Slug may only contain lowercase letters, numbers, and hyphens.';
    }

    // If slug changed, remember old one so we can migrate listings
    $old_slug = $cat['slug'] ?? null;

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

    // Banner image upload (shown on directory when this category is selected)
    $banner_path = $cat['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/categories/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name_safe = 'banner-' . ($cat_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/categories/' . $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 ?: cat_slug_unique($name, $cat_id ?: null);
        $data = [
            'slug'        => $slug,
            'name'        => $name,
            'icon'        => $icon ?: null,
            'image_path'  => $image_path,
            'banner_path' => $banner_path,
            'sort_order'  => $sort_order,
        ];

        if ($is_add) {
            db_insert('categories', $data);
            header('Location: categories.php?msg=' . urlencode('Category created.')); exit;
        } else {
            db_update('categories', $cat_id, $data);
            // If slug changed, update dependent listings
            if ($old_slug && $old_slug !== $slug) {
                db_exec('UPDATE listings SET category_slug=:new WHERE category_slug=:old',
                        ['new'=>$slug,'old'=>$old_slug]);
            }
            header('Location: category-edit.php?id='.$cat_id.'&msg=saved'); exit;
        }
    }

    // Repopulate on error
    $cat = array_merge($cat ?? [], [
        'name'=>$name,'slug'=>$custom_slug,'icon'=>$icon,
        'sort_order'=>$sort_order,'image_path'=>$image_path,
        'banner_path'=>$banner_path,
    ]);
}

if ($is_add && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $next_order = (int)db_value('SELECT COALESCE(MAX(sort_order),0)+1 FROM categories');
    $cat = ['name'=>'','slug'=>'','icon'=>'','image_path'=>null,'banner_path'=>null,'sort_order'=>$next_order];
}

$page_title = $is_add ? 'New category' : 'Edit — ' . ($cat['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);}

.upload-zone{border:2px dashed var(--line);border-radius:var(--radius);padding:1.5rem;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%;}

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

.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:21/9;object-fit:cover;}

.preview-tile{
    width:100%;
    aspect-ratio:4/3;
    border-radius:var(--radius-lg);
    background:#333 center/cover no-repeat;
    position:relative;
    overflow:hidden;
}
.preview-tile::after{
    content:'';
    position:absolute;inset:0;
    background:linear-gradient(180deg, rgba(0,0,0,.15), rgba(0,0,0,.5));
}
</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="categories.php">← All categories</a></p>
        <h1 style="margin:.25rem 0 0;"><?= $is_add ? 'Add a category' : 'Edit category' ?></h1>
    </div>
    <?php if (!$is_add): ?>
        <a href="../directory.php?cat=<?= htmlspecialchars($cat['slug']) ?>" target="_blank" class="btn btn-outline">
            View on directory ↗
        </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="category-edit.php?<?= $is_add?'action=add':'id='.$cat_id ?>">
    <?= csrf_field() ?>

    <div class="l-layout">
        <div>
            <div class="b-card">
                <h2>Category details</h2>

                <label>Name * <small>(internal — won't be shown on tile if image is uploaded)</small></label>
                <input type="text" name="name" id="c-name" required
                       value="<?= htmlspecialchars($cat['name'] ?? '') ?>">

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

                <label>Icon <small>(emoji, fallback for tiles with no image)</small></label>
                <input type="text" name="icon" maxlength="8"
                       value="<?= htmlspecialchars($cat['icon'] ?? '') ?>"
                       placeholder="🍽 or 🏨 or 🛠" style="font-size:1.1rem;">

                <label>Sort order</label>
                <input type="number" name="sort_order" value="<?= (int)($cat['sort_order'] ?? 0) ?>">
                <p class="muted" style="font-size:.8rem;margin-top:-.5rem;">
                    Lower numbers show first. You can also drag-and-drop rows on the list page.
                </p>
            </div>
        </div>

        <div>
            <!-- Save -->
            <div class="b-card">
                <h2>Save</h2>
                <div style="display:flex;flex-direction:column;gap:.4rem;">
                    <button type="submit" class="btn"><?= $is_add ? 'Create category' : 'Save changes' ?></button>
                    <a href="categories.php" class="btn btn-outline" style="text-align:center;">Cancel</a>
                </div>
            </div>

            <!-- Image upload -->
            <div class="b-card">
                <h2>Tile image</h2>
                <p class="muted" style="font-size:.82rem;margin:0 0 1rem;">
                    This image will be shown on the homepage and directory tile.
                    For best results, include the category name as text in the image itself.
                </p>

                <?php if (!empty($cat['image_path'])): ?>
                    <div class="img-preview-wrap" id="img-preview-current">
                        <img src="../<?= htmlspecialchars($cat['image_path']) ?>" alt="current image">
                    </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_image" value="1">
                        Remove current image
                    </label>
                <?php endif; ?>

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

                <div class="upload-zone" id="img-zone">
                    <input type="file" name="image" id="img-input"
                           accept="image/jpeg,image/png,image/gif,image/webp">
                    <div>
                        <div style="font-size:1.8rem;">🖼</div>
                        <p style="font-size:.88rem;margin:.4rem 0 .25rem;font-weight:600;">Click or drag an image</p>
                        <p style="font-size:.75rem;color:var(--ink-muted);margin:0;">
                            JPG, PNG, WebP · max 3MB<br>
                            Recommended: 800×600, 4:3 aspect
                        </p>
                    </div>
                </div>
            </div>

            <!-- Directory banner upload -->
            <div class="b-card">
                <h2>Directory banner</h2>
                <p class="muted" style="font-size:.82rem;margin:0 0 1rem;">
                    Wide hero image shown at the top of the directory page when visitors filter by this category.
                    If blank, the default directory banner is used.
                </p>

                <?php if (!empty($cat['banner_path'])): ?>
                    <div class="banner-preview-wrap" id="banner-preview-current">
                        <img src="../<?= htmlspecialchars($cat['banner_path']) ?>" alt="current 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 banner
                    </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 banner 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.8rem;">🖼</div>
                        <p style="font-size:.88rem;margin:.4rem 0 .25rem;font-weight:600;">Click or drag a banner</p>
                        <p style="font-size:.75rem;color:var(--ink-muted);margin:0;">
                            JPG, PNG, WebP · max 5MB<br>
                            Recommended: 1920×400, wide landscape
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

</div>
</section>

<script>
// Auto-slug from name
const nameEl = document.getElementById('c-name');
const slugEl = document.getElementById('c-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');
}

// Drag-and-drop + inline preview
const iz = document.getElementById('img-zone');
const ii = document.getElementById('img-input');
const previewBox     = document.getElementById('img-preview-new');
const previewImg     = document.getElementById('img-preview-new-src');
const previewLabel   = document.getElementById('img-preview-new-label');
const previewCurrent = document.getElementById('img-preview-current');

function showPreview(file) {
    if (!file || !previewBox || !previewImg) return;
    const reader = new FileReader();
    reader.onload = (e) => {
        previewImg.src = e.target.result;
        previewBox.style.display = 'block';
        if (previewLabel) previewLabel.style.display = 'block';
        // Fade out the current/saved image so it's obvious the new one is replacing it
        if (previewCurrent) previewCurrent.style.opacity = '0.35';
    };
    reader.readAsDataURL(file);
}

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

    // Handle normal file picker selection
    ii.addEventListener('change', () => {
        if (ii.files && ii.files[0]) showPreview(ii.files[0]);
    });
}

// ── Banner upload 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]);
    });
}
</script>

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