<style>
.form-header-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.form-card-modern {
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    margin-bottom: 1.5rem;
    border: none;
    overflow: hidden;
}

.form-card-modern .card-header {
    background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
    border-bottom: 2px solid #e2e8f0;
    padding: 1.25rem 1.5rem;
    font-weight: 600;
    color: #2d3748;
}

.form-card-modern .card-body {
    padding: 2rem;
}

.form-label-modern {
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.form-control-modern {
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
}

.form-control-modern:focus {
    border-color: #72A565;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    outline: none;
}

.form-group-modern {
    margin-bottom: 1.5rem;
}

.btn-submit-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(102, 126, 234, 0.3);
}

.btn-submit-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(102, 126, 234, 0.4);
    color: white;
}

.image-preview {
    width: 200px;
    height: 200px;
    object-fit: cover;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    margin-top: 1rem;
}

.form-check-input:checked {
    background-color: #667eea;
    border-color: #72A565;
}
</style>

<div class="form-header-modern">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h2 class="mb-2">
                <i class="fa-solid fa-edit"></i> Edit Product
            </h2>
            <p class="mb-0 opacity-75">Update product information</p>
        </div>
        <div>
            <a href="<?php echo base_url('products'); ?>" class="btn btn-light btn-modern">
                <i class="fa-solid fa-arrow-left"></i> Back to Products
            </a>
        </div>
    </div>
</div>

<form id="editProductForm" method="post" action="<?php echo base_url('products/updateproduct/' . $productId); ?>" enctype="multipart/form-data">
    <!-- Basic Information -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-info-circle text-primary"></i> Basic Information
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label for="productName" class="form-label-modern">Product Name *</label>
                    <input type="text" class="form-control form-control-modern" id="productName" name="productName" 
                        value="<?php echo isset($product['productName']) ? htmlspecialchars($product['productName']) : ''; ?>" required>
                </div>
                <div class="col-md-6 form-group-modern">
                    <label for="productUnit" class="form-label-modern">Product Unit</label>
                    <input type="text" class="form-control form-control-modern" id="productUnit" name="productUnit" 
                        value="<?php echo isset($product['productUnit']) ? htmlspecialchars($product['productUnit']) : ''; ?>">
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 form-group-modern">
                    <label for="productDetail" class="form-label-modern">Product Description</label>
                    <textarea class="form-control form-control-modern" id="productDetail" name="productDetail" rows="4"><?php echo isset($product['productDetail']) ? htmlspecialchars($product['productDetail']) : ''; ?></textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Pricing Information -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-dollar-sign text-primary"></i> Pricing Information
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label for="productPrice" class="form-label-modern">Base Price *</label>
                    <input type="number" step="0.01" min="0" class="form-control form-control-modern" id="productPrice" name="productPrice" 
                        value="<?php echo isset($product['productPrice']) ? $product['productPrice'] : '0.00'; ?>" required>
                </div>
                <div class="col-md-6 form-group-modern">
                    <label for="displayPrice" class="form-label-modern">Display Price</label>
                    <input type="number" step="0.01" min="0" class="form-control form-control-modern" id="displayPrice" name="displayPrice" 
                        value="<?php echo isset($product['displayPrice']) ? $product['displayPrice'] : (isset($product['productPrice']) ? $product['productPrice'] : '0.00'); ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- Category & Vendor Assignment -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-tags text-primary"></i> Category & Vendor
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label for="categoryId" class="form-label-modern">Category</label>
                    <select class="form-control form-control-modern" id="categoryId" name="categoryId">
                        <option value="">Select Category</option>
                        <?php foreach ($categories as $categoryId => $category): ?>
                            <option value="<?php echo $categoryId; ?>" 
                                <?php echo (isset($product['categoryId']) && $product['categoryId'] == $categoryId) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars(isset($category['name']) ? $category['name'] : 'Unknown'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 form-group-modern">
                    <label for="subcategoryId" class="form-label-modern">Subcategory</label>
                    <select class="form-control form-control-modern" id="subcategoryId" name="subcategoryId">
                        <option value="">Select Subcategory</option>
                        <?php foreach ($subcategories as $subcategoryId => $subcategory): ?>
                            <option value="<?php echo $subcategoryId; ?>" 
                                data-category="<?php echo isset($subcategory['categoryId']) ? $subcategory['categoryId'] : ''; ?>"
                                <?php echo (isset($product['subcategoryId']) && $product['subcategoryId'] == $subcategoryId) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars(isset($subcategory['name']) ? $subcategory['name'] : 'Unknown'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label for="userId" class="form-label-modern">Vendor</label>
                    <select class="form-control form-control-modern" id="userId" name="userId">
                        <option value="">Select Vendor</option>
                        <?php foreach ($vendors as $vendorId => $vendor): ?>
                            <option value="<?php echo $vendorId; ?>" 
                                <?php echo (isset($product['userId']) && $product['userId'] == $vendorId) ? 'selected' : ''; ?>>
                                <?php 
                                $vendorName = isset($vendor['shopName']) ? $vendor['shopName'] : 
                                    (isset($vendor['firstName']) ? $vendor['firstName'] . ' ' . (isset($vendor['lastName']) ? $vendor['lastName'] : '') : 'Unknown');
                                echo htmlspecialchars($vendorName);
                                ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Product Levels -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-chart-line text-primary"></i> Product Levels
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label for="potencyLevel" class="form-label-modern">THC Potency Level (%)</label>
                    <input type="number" min="0" max="100" class="form-control form-control-modern" id="potencyLevel" name="potencyLevel" 
                        value="<?php echo isset($product['potencyLevel']) ? $product['potencyLevel'] : '0'; ?>">
                </div>
                <div class="col-md-6 form-group-modern">
                    <label for="nicotineLevel" class="form-label-modern">Nicotine Level (%)</label>
                    <input type="number" min="0" max="100" class="form-control form-control-modern" id="nicotineLevel" name="nicotineLevel" 
                        value="<?php echo isset($product['nicotineLevel']) ? $product['nicotineLevel'] : '0'; ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- Product Image -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-image text-primary"></i> Product Image
            </h5>
        </div>
        <div class="card-body">
            <?php if (isset($product['productUrl']) && !empty($product['productUrl'])): ?>
                <div class="mb-3">
                    <label class="form-label-modern">Current Image</label>
                    <div>
                        <img src="<?php echo htmlspecialchars($product['productUrl']); ?>" alt="Current Product" class="image-preview" id="currentImage">
                    </div>
                </div>
            <?php endif; ?>
            <div class="form-group-modern">
                <label for="productImage" class="form-label-modern">Update Product Image</label>
                <input type="file" class="form-control form-control-modern" id="productImage" name="productImage" accept="image/*" onchange="previewImage(this)">
                <small class="text-muted">Leave blank to keep current image</small>
                <div id="imagePreview" style="display: none;">
                    <label class="form-label-modern mt-3">New Image Preview</label>
                    <img id="previewImg" src="" alt="Preview" class="image-preview">
                </div>
            </div>
        </div>
    </div>

    <!-- Status -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-toggle-on text-primary"></i> Status
            </h5>
        </div>
        <div class="card-body">
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="isVerified" name="isVerified" value="1" 
                    <?php echo (isset($product['isVerified']) && $product['isVerified']) ? 'checked' : ''; ?> 
                    style="width: 3rem; height: 1.5rem;">
                <label class="form-check-label ms-3" for="isVerified">
                    <strong>Approve Product</strong>
                    <br><small class="text-muted">Check to approve this product</small>
                </label>
            </div>
        </div>
    </div>

    <!-- Submit Button -->
    <div class="text-end mb-4">
        <button type="submit" class="btn btn-submit-modern">
            <i class="fa-solid fa-save"></i> Update Product
        </button>
    </div>
</form>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
function previewImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('previewImg').src = e.target.result;
            document.getElementById('imagePreview').style.display = 'block';
        }
        reader.readAsDataURL(input.files[0]);
    }
}

// Filter subcategories based on selected category
$('#categoryId').on('change', function() {
    var selectedCategory = $(this).val();
    $('#subcategoryId option').each(function() {
        var subcategoryCategory = $(this).data('category');
        if (!selectedCategory || subcategoryCategory == selectedCategory) {
            $(this).show();
        } else {
            $(this).hide();
            if ($(this).prop('selected')) {
                $(this).prop('selected', false);
            }
        }
    });
});

// Initialize subcategory filter on page load
$(document).ready(function() {
    $('#categoryId').trigger('change');
});

// Form submission with SweetAlert
$('#editProductForm').on('submit', function(e) {
    e.preventDefault();
    
    var formData = new FormData(this);
    
    $.ajax({
        url: $(this).attr('action'),
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message,
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = '<?php echo base_url("products"); ?>';
                    }
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: response.message
                });
            }
        },
        error: function() {
            // Fallback to regular form submission if AJAX fails
            document.getElementById('editProductForm').submit();
        }
    });
});
</script>
