<?php $isEdit = !is_null($category); ?>

<!-- Page Header -->
<div class="page-header">
    <div>
        <h1><?= $isEdit ? 'Edit Category' : 'Add Category' ?></h1>
        <p><?= $isEdit ? 'Update category details and icon.' : 'Create a new menu category.' ?></p>
    </div>
    <a href="<?= url('categories') ?>" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i> Back to Categories
    </a>
</div>

<div class="row justify-content-center">
<div class="col-12 col-lg-8">

<form method="POST"
      action="<?= $isEdit ? url('categories/' . $category['id'] . '/update') : url('categories/store') ?>"
      enctype="multipart/form-data"
      class="fd-form"
      novalidate>
    <?= csrf_field() ?>

    <div class="card mb-4">
        <div class="card-header">
            <i class="bi bi-info-circle text-accent"></i>
            <h6 class="card-title">Category Details</h6>
        </div>
        <div class="card-body">

            <!-- Name -->
            <div class="mb-4">
                <label class="form-label" for="name">
                    Category Name <span class="text-danger">*</span>
                </label>
                <input type="text"
                       id="name"
                       name="name"
                       class="form-control"
                       placeholder="e.g. Burgers, Pizzas, Drinks"
                       value="<?= e($isEdit ? $category['name'] : \Core\Request::post('name', '')) ?>"
                       maxlength="100"
                       required>
                <div class="form-text">The name shown to customers in the app and menu.</div>
            </div>

            <!-- Sort Order -->
            <div class="mb-4">
                <label class="form-label" for="sort_order">Display Order</label>
                <input type="number"
                       id="sort_order"
                       name="sort_order"
                       class="form-control"
                       style="max-width:160px;"
                       min="0"
                       max="999"
                       value="<?= e($isEdit ? $category['sort_order'] : '0') ?>">
                <div class="form-text">Lower number = shown first. Use 0, 1, 2… to order categories.</div>
            </div>

            <!-- Status -->
            <div class="mb-2">
                <label class="form-label d-block">Status</label>
                <div class="form-check form-switch">
                    <input class="form-check-input"
                           type="checkbox"
                           id="is_active"
                           name="is_active"
                           value="1"
                           <?= (!$isEdit || $category['is_active']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="is_active">
                        Active — visible to customers
                    </label>
                </div>
            </div>

        </div>
    </div>

    <!-- Icon Upload Card -->
    <div class="card mb-4">
        <div class="card-header">
            <i class="bi bi-image text-accent"></i>
            <h6 class="card-title">Category Icon</h6>
            <span class="ms-auto text-secondary" style="font-size:.75rem;">
                Max <?= UPLOAD_MAX_SIZE ?> KB · JPG, PNG, WebP · Square recommended
            </span>
        </div>
        <div class="card-body">
            <div class="row align-items-center g-4">

                <!-- Preview -->
                <div class="col-auto">
                    <div style="position:relative;display:inline-block;">
                        <img id="iconPreview"
                             src="<?= $isEdit && $category['icon_image'] ? e(upload_url($category['icon_image'])) : 'https://placehold.co/120x120/f4f6fc/adb5bd?text=Icon' ?>"
                             alt="Icon Preview"
                             style="width:120px;height:120px;object-fit:cover;border-radius:16px;border:2px solid var(--border-color);">
                        <?php if ($isEdit && $category['icon_image']): ?>
                        <button type="button"
                                id="removeIconBtn"
                                class="btn btn-danger btn-sm"
                                style="position:absolute;top:-8px;right:-8px;width:26px;height:26px;padding:0;border-radius:50%;font-size:.75rem;"
                                title="Remove icon">
                            <i class="bi bi-x"></i>
                        </button>
                        <input type="hidden" name="remove_image" id="removeImageFlag" value="0">
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Upload -->
                <div class="col">
                    <label class="img-upload-wrap d-block" for="icon_image" style="cursor:pointer;">
                        <i class="bi bi-cloud-upload fs-2 text-secondary d-block mb-2"></i>
                        <div class="fw-600 mb-1">Click to upload icon</div>
                        <div class="text-secondary" style="font-size:.8rem;">
                            Drag & drop or click · JPG, PNG, WebP<br>
                            Max size: <?= UPLOAD_MAX_SIZE ?> KB · Will be cropped to square
                        </div>
                        <input type="file"
                               id="icon_image"
                               name="icon_image"
                               class="d-none img-upload-input"
                               accept="image/jpeg,image/png,image/webp"
                               data-preview="iconPreview">
                    </label>
                </div>

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

    <!-- Actions -->
    <div class="d-flex gap-2">
        <button type="submit" class="btn btn-accent px-4">
            <i class="bi bi-check-lg me-1"></i>
            <?= $isEdit ? 'Update Category' : 'Create Category' ?>
        </button>
        <a href="<?= url('categories') ?>" class="btn btn-outline-secondary px-4">
            Cancel
        </a>
    </div>

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

<?php
ob_start();
?>
<script>
// Remove image button
const removeBtn  = document.getElementById('removeIconBtn');
const removeFlag = document.getElementById('removeImageFlag');
const preview    = document.getElementById('iconPreview');

if (removeBtn) {
    removeBtn.addEventListener('click', function () {
        removeFlag.value = '1';
        preview.src = 'https://placehold.co/120x120/f4f6fc/adb5bd?text=Icon';
        this.style.display = 'none';
    });
}

// Drag & drop on upload area
const uploadLabel = document.querySelector('.img-upload-wrap');
if (uploadLabel) {
    ['dragover','dragenter'].forEach(e => uploadLabel.addEventListener(e, ev => {
        ev.preventDefault();
        uploadLabel.style.borderColor = 'var(--accent)';
        uploadLabel.style.background  = 'var(--accent-soft)';
    }));
    ['dragleave','drop'].forEach(e => uploadLabel.addEventListener(e, ev => {
        uploadLabel.style.borderColor = '';
        uploadLabel.style.background  = '';
    }));
    uploadLabel.addEventListener('drop', ev => {
        ev.preventDefault();
        const file = ev.dataTransfer.files[0];
        if (file) {
            document.getElementById('icon_image').files = ev.dataTransfer.files;
            const reader = new FileReader();
            reader.onload = e => { preview.src = e.target.result; };
            reader.readAsDataURL(file);
        }
    });
}
</script>
<?php $extraJs = ob_get_clean(); ?>
