<div id="page-wrapper">
    <div id="page-inner">
        <div class="row g-4">
            <div class="col-md-7">
                <?php
            if (session_status() == PHP_SESSION_NONE) session_start();
            if (!empty($_SESSION['message'])): ?>
                <div class="custom-alert alert alert-info" id="customAlert">
                    <?= $_SESSION['message'] ?>
                    <span class="close-btn float-end" onclick="this.parentElement.style.display='none'">&times;</span>
                </div>
                <?php unset($_SESSION['message']); endif; ?>
                <div class="card">
                    <div class="card-header text-white">
                        <?= isset($_GET['edit']) ? 'Edit Product' : 'Add Product' ?>
                    </div>
                    <div class="card-body">
                        <?php
                          $editData = null;
                          if (isset($_GET['edit'])) {
                              foreach ($products as $p) {
                                  if ($p['id'] == $_GET['edit']) {
                                      $editData = $p;
                                      break;
                                  }
                              }
                          }
                          ?>
                        <form method="post" enctype="multipart/form-data">
                            <input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">
                            <input type="hidden" name="old_image" value="<?= $editData['pro_image'] ?? '' ?>">

                            <div class="mb-3">
                                <label>Select Category</label>
                                <select name="category_id" id="categorySelect" class="form-control" required>
                                    <option value="">-- Select Category --</option>

                                    <?php foreach($categories as $cat): ?>
                                    <?php if(empty($cat['parent_id'])): ?>
                                    <option value="<?= $cat['id'] ?>"
                                        <?= isset($editData) && $editData['category_id'] == $cat['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($cat['cat_title']) ?>
                                    </option>
                                    <?php endif; ?>
                                    <?php endforeach; ?>

                                </select>
                            </div>
                            <!-- Sub Category -->
                            <div class="mb-3">
                                <label>Sub Category</label>
                                <select name="sub_category_id" id="subCategorySelect" class="form-control">
                                    <option value="">Select Sub Category</option>
                                </select>
                            </div>
<div class="mb-3">
                                <label>Product Title</label>
                                <input type="text" name="pro_title" class="form-control" required
                                    value="<?= $editData['pro_title'] ?? '' ?>">
                            </div>
                            <!-- Price -->
                            <div class="mb-3">
                                <label>Price</label>
                                <input type="number" name="price" class="form-control"
                                    value="<?= $editData['price'] ?? '' ?>">
                            </div>

                            <!-- Sale Price -->
                            <div class="mb-3">
                                <label>Sale Price</label>
                                <input type="number" name="sale_price" class="form-control"
                                    value="<?= $editData['sale_price'] ?? '' ?>">
                            </div>

                            <!-- Highlight -->
                            <div class="mb-3">
                                <label>Highlight</label>
                                <textarea name="highlight"
                                    class="form-control"><?= $editData['highlight'] ?? '' ?></textarea>
                            </div>

                            <!-- Full Description -->
                            <!-- <div class="mb-3">
                                <label>Full Description</label>
                                <textarea name="description"
                                    class="form-control"><?= $editData['description'] ?? '' ?></textarea>
                            </div> -->

                            <!-- Benefits -->
                            <div class="mb-3">
                                <label>Benefits</label>
                                <textarea name="benefits" id="benefits"
                                    class="form-control"><?= $editData['benefits'] ?? '' ?></textarea>
                            </div>

                            <!-- How to Use -->
                            <div class="mb-3">
                                <label>How to Use</label>
                                <textarea name="how_to_use"  id="how_to_use"
                                    class="form-control"><?= $editData['how_to_use'] ?? '' ?></textarea>
                            </div>

                            <!-- Ideal For -->
                            <div class="mb-3">
                                <label>Ideal For</label>
                                <textarea name="ideal_for"  id="ideal_for"
                                    class="form-control"><?= $editData['ideal_for'] ?? '' ?></textarea>
                            </div>

                            <!-- Care -->
                            <div class="mb-3">
                                <label>Care</label>
                                <textarea name="care" class="form-control"  id="care"><?= $editData['care'] ?? '' ?></textarea>
                            </div>

                            <!-- Special Instruction -->
                            <div class="mb-3">
                                <label>Special Instruction</label>
                                <textarea name="special_instruction"
                                    class="form-control"  id="special_instruction"><?= $editData['special_instruction'] ?? '' ?></textarea>
                            </div>
                            
                            <!-- <div class="mb-3">
                                <label>Material</label>
                                <input type="text" name="pro_material" class="form-control" required
                                    value="<?= $editData['pro_material'] ?? '' ?>">
                            </div> -->

                            <div class="mb-3">
                                <label>Product Description:</label>
                                <textarea name="short_description" class="form-control" id="data"
                                    rows="3"><?= $editData['short_description'] ?? '' ?></textarea>
                            </div>

                            <div class="mb-3">
                                <label>Main Image</label>
                                <input type="file" name="pro_image" class="form-control" accept=".png,.jpg,.jpeg,.webp">
                                <?php if (!empty($editData['pro_image'])): ?>
                                <img src="../assets/images/products/<?= $editData['pro_image'] ?>" width="80"
                                    class="mt-2 rounded">
                                <?php endif; ?>
                            </div>

                            <!-- Multiple Images Upload Section -->
                            <div class="mb-3">
                                <label class="d-flex justify-content-between align-items-center">
                                    <span>Upload Multiple Images</span>
                                </label>

                                <div id="imageUploadGroup">
                                    <div class="input-group mb-2 image-row">
                                        <input type="file" name="gallery_images[]" class="form-control"
                                            accept=".png,.jpg,.jpeg,.webp" />
                                        <button type="button" class="btn btn-success add-image-btn" title="Add Image">
                                            <i class="fas fa-plus"></i>
                                        </button>
                                    </div>
                                </div>

                                <?php if (isset($editData['id'])): ?>
                                <div class="mt-3">
                                    <label class="fw-bold">Existing Images:</label><br>
                                    <?php
                                      $images = $this->model('Product')->getImages($editData['id']);
                                      foreach ($images as $img): ?>
                                    <div class="d-inline-block position-relative me-2 mb-2">
                                        <img src="../assets/images/products/gallery/<?= $img['image_name'] ?>"
                                            width="80" class="rounded border">
                                        <a href="?delete_image=<?= $img['id'] ?>&edit=<?= $editData['id'] ?>"
                                            class="btn btn-sm btn-danger position-absolute top-0 end-0"
                                            onclick="return confirm('Delete this image?')">&times;</a>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                            </div>

                            <button type="submit" name="<?= isset($editData) ? 'edit' : 'add' ?>"
                                class="btn btn-primary w-100">
                                <?= isset($editData) ? 'Update Product' : 'Add Product' ?>
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-5">
                <div class="card">
                    <div class="card-header bg-dark text-white">Product List</div>
                    <div class="card-body">
                        <table class="table table-bordered table-striped">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Title</th>
                                    <th>Category</th>
                                    <!-- <th>Image</th> -->
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($products)): ?>
                                <?php foreach($products as $index => $p): ?>
                                <tr>
                                    <td><?= $index + 1 ?></td>
                                    <td><?= htmlspecialchars($p['pro_title']) ?></td>
                                    <td><?= htmlspecialchars($p['cat_title'] ?? '—') ?></td>
                                    <!-- <td>
                                      <?php if (!empty($p['pro_image'])): ?>
                                        <img src="../assets/images/products/<?= $p['pro_image'] ?>" width="50">
                                      <?php else: ?>
                                        <span class="text-muted">No image</span>
                                      <?php endif; ?>
                                    </td> -->
                                    <td>
                                        <a href="?edit=<?= $p['id'] ?>" class="btn btn-sm btn-warning"><i
                                                class="fas fa-edit"></i></a>
                                        <a href="?delete=<?= $p['id'] ?>" class="btn btn-sm btn-danger"
                                            onclick="return confirm('Delete this product?')"><i
                                                class="fas fa-trash-alt"></i></a>
                                                <a href="?clone=<?= $p['id'] ?>" 
   class="btn btn-sm btn-info"
   onclick="return confirm('Clone this product?')">
   <i class="fas fa-copy"></i>
</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center text-muted">No products found</td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

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

<!-- FontAwesome for icons -->

<script>
document.addEventListener('DOMContentLoaded', function() {
    const uploadGroup = document.getElementById('imageUploadGroup');

    uploadGroup.addEventListener('click', function(e) {
        // Add new input when + button clicked
        if (e.target.closest('.add-image-btn')) {
            const newRow = document.createElement('div');
            newRow.classList.add('input-group', 'mb-2', 'image-row');
            newRow.innerHTML = `
        <input type="file" name="gallery_images[]" class="form-control" accept=".png,.jpg,.jpeg,.webp" />
        <button type="button" class="btn btn-danger remove-image-btn" title="Remove Image">
          <i class="fas fa-minus"></i>
        </button>
      `;
            uploadGroup.appendChild(newRow);
        }

        // Remove input when - button clicked
        if (e.target.closest('.remove-image-btn')) {
            const row = e.target.closest('.image-row');
            if (row) row.remove();
        }
    });
});
</script>
<style>
.gallery-upload-group {
    max-width: 500px;
    margin-bottom: 1rem;
}

.image-row {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
}

.image-row button.delete-btn {
    background-color: #e53e3e;
    border: none;
    color: white;
    cursor: pointer;
    padding: 0.4rem 0.6rem;
    border-radius: 4px;
    font-size: 1.1rem;
}

.add-btn {
    background-color: #0bc5ea;
    border: none;
    color: white;
    cursor: pointer;
    padding: 0.5rem 1rem;
    font-weight: 600;
    border-radius: 4px;
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    font-size: 0.9rem;
}

.add-btn i {
    font-weight: bold;
}
</style>

<script>
const categories = <?= json_encode($categories) ?>;

const categorySelect = document.getElementById('categorySelect');
const subCategorySelect = document.getElementById('subCategorySelect');

function loadSubCategories(parentId, selectedId = null) {
    subCategorySelect.innerHTML = '<option value="">Select Sub Category</option>';

    categories.forEach(cat => {
        if (cat.parent_id == parentId) {
            let selected = selectedId == cat.id ? 'selected' : '';
            subCategorySelect.innerHTML += `
                <option value="${cat.id}" ${selected}>${cat.cat_title}</option>
            `;
        }
    });
}

// ON CHANGE
categorySelect.addEventListener('change', function() {
    loadSubCategories(this.value);
});

// EDIT MODE AUTO LOAD
<?php if(isset($editData)): ?>
loadSubCategories(
    "<?= $editData['category_id'] ?>",
    "<?= $editData['sub_category_id'] ?>"
);
<?php endif; ?>
</script>