<!--start main wrapper-->
<main class="main-wrapper">
    <div class="main-content">
        <div class="row">
            <div class="col-md-8 my-2">
                <h3 class="fmon">Update Product</h3>
            </div>
        </div>

        <form class="row my-2" id="productForm" enctype="multipart/form-data">
            <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
            <input type="hidden" name="old_image" value="<?= $product['image'] ?>">

            <div class="col-md-6 my-2">
                <input class="form-control formInput" type="text" name="service_name"
                    placeholder="Product Name" value="<?= htmlspecialchars($product['serviceName']) ?>" required>
            </div>

            <div class="col-md-6 my-2">
                <select class="form-control formInput" name="category_id" required>
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $category): ?>
                        <option class="text-capitalize" value="<?= $category['id'] ?>" 
                            <?= $product['categoryId'] == $category['id'] ? 'selected' : '' ?>>
                            <?= $category['name'] ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-12 my-2">
                <textarea class="form-control formInput" name="detail"
                    placeholder="Products Details" rows="4" required><?= htmlspecialchars($product['detail']) ?></textarea>
            </div>

            <div class="col-md-6 my-2">
                <div class="input-group">
                    <input class="form-control formInput" type="number" name="price"
                        placeholder="Price" step="0.01" value="<?= $product['price'] ?>" required>
                    <span class="input-group-text">AED</span>
                </div>
            </div>

            <div class="col-md-12 my-2">
                <input type="file" name="product_image" id="uploadImage" class="d-none" accept="image/*">
                <label for="uploadImage" class="btn btnUpload w-100">
                    <span id="fileName">Tap to upload image</span>
                </label>
                <div id="imagePreview" class="mt-2">
                    <?php if (!empty($product['image'])): ?>
                        <img src="<?= $product['image'] ?>" class="img-thumbnail" style="max-width: 200px;">
                    <?php endif; ?>
                </div>
            </div>

            <div class="col-md-12 my-2 d-flex justify-content-center">
                <button type="submit" class="btn setBtn px-5 py-3 mt-2">Update Product</button>
            </div>
        </form>
    </div>
</main>

<script>
    document.getElementById('uploadImage').addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('fileName').textContent = file.name;

            const reader = new FileReader();
            reader.onload = function (e) {
                const preview = `<img src="${e.target.result}" class="img-thumbnail" style="max-width: 200px;">`;
                document.getElementById('imagePreview').innerHTML = preview;
            }
            reader.readAsDataURL(file);
        }
    });

    document.getElementById('productForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(this);

        // Show loader
        document.querySelector(".loader-overlay").style.display = "block";

        fetch("<?= base_url('product/editProduct') ?>", {
            method: "POST",
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                document.querySelector(".loader-overlay").style.display = "none";
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message,
                        confirmButtonColor: '#FFD700'
                    }).then(() => {
                        window.location.href = data.redirect;
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: data.message,
                        confirmButtonColor: '#FFD700'
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.querySelector(".loader-overlay").style.display = "none";
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Failed to update product',
                    confirmButtonColor: '#FFD700'
                });
            });
    });
</script>

<!--end main wrapper-->

<!--start overlay-->
<div class="overlay btn-toggle"></div>
<!--end overlay-->
