<?php
/**
 * ============================================================
 * ADMIN: Product Add/Edit Form
 * ============================================================
 * Handles both creating and editing products with multiple images
 */

require_once APP_PATH . '/services/product_service.php';

$productId = (int)($_GET['id'] ?? 0);
$isEdit = $productId > 0;
$product = null;

if ($isEdit) {
    $product = ProductService::getById($productId);
    if (!$product) {
        redirect(adminUrl('?page=products'));
    }
    $pageTitle = 'Edit Product';
} else {
    $pageTitle = 'Add Product';
}

// Get categories
$categories = Database::fetchAll("SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name");

$formAction = $isEdit 
    ? adminUrl('ajax/products/update.php') 
    : adminUrl('ajax/products/create.php');

include ADMIN_PATH . '/includes/header.php';
include ADMIN_PATH . '/includes/sidebar.php';
?>

<main class="admin-main">
    <?php include ADMIN_PATH . '/includes/topbar.php'; ?>
    
    <div class="admin-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <a href="<?= adminUrl('?page=products') ?>" class="text-muted text-decoration-none">
                    <i class="bi bi-arrow-left me-1"></i> Back to Products
                </a>
                <h1 class="page-title mb-0 mt-2"><?= $pageTitle ?></h1>
            </div>
        </div>
        
        <form id="productForm" action="<?= $formAction ?>" method="POST" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <?php if ($isEdit): ?>
            <input type="hidden" name="product_id" value="<?= $productId ?>">
            <?php endif; ?>
            
            <div class="row g-4">
                <!-- Left Column: Main Info -->
                <div class="col-lg-8">
                    <div class="admin-form mb-4">
                        <h5 class="mb-3">Basic Information</h5>
                        
                        <div class="mb-3">
                            <label for="name" class="form-label">Product Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" 
                                   value="<?= sanitize($product['name'] ?? '') ?>" required>
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="category_id" class="form-label">Category <span class="text-danger">*</span></label>
                                <select class="form-select" id="category_id" name="category_id" required>
                                    <option value="">Select Category</option>
                                    <?php foreach ($categories as $cat): ?>
                                    <option value="<?= $cat['id'] ?>" 
                                            <?= ($product['category_id'] ?? '') == $cat['id'] ? 'selected' : '' ?>>
                                        <?= sanitize($cat['name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="sku" class="form-label">SKU</label>
                                <input type="text" class="form-control" id="sku" name="sku" 
                                       value="<?= sanitize($product['sku'] ?? '') ?>">
                            </div>
                        </div>
                        
                        <div class="mb-3 mt-3">
                            <label for="short_description" class="form-label">Short Description</label>
                            <textarea class="form-control" id="short_description" name="short_description" 
                                      rows="2"><?= sanitize($product['short_description'] ?? '') ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">Full Description</label>
                            <textarea class="form-control" id="description" name="description" 
                                      rows="5"><?= $product['description'] ?? '' ?></textarea>
                        </div>
                    </div>
                    
                    <!-- Images -->
                    <div class="admin-form mb-4">
                        <h5 class="mb-3">Product Images</h5>
                        
                        <div class="image-upload-zone">
                            <i class="bi bi-cloud-arrow-up fs-1 text-muted"></i>
                            <p class="mb-0">Click or drag images here to upload</p>
                            <small class="text-muted">Max <?= MAX_PRODUCT_IMAGES ?> images, <?= MAX_FILE_SIZE / 1024 / 1024 ?>MB each</small>
                        </div>
                        <input type="file" id="productImages" name="images[]" multiple accept="image/*" class="d-none">
                        
                        <div class="image-preview-grid">
                            <?php if ($isEdit && !empty($product['images'])): ?>
                            <?php foreach ($product['images'] as $img): ?>
                            <div class="image-preview-item <?= $img['is_primary'] ? 'primary' : '' ?>" data-id="<?= $img['id'] ?>">
                                <img src="<?= UPLOADS_URL . '/products/' . $img['file_path'] ?>" alt="">
                                <div class="image-actions">
                                    <?php if (!$img['is_primary']): ?>
                                    <button type="button" class="btn btn-success btn-sm btn-set-primary" 
                                            data-id="<?= $img['id'] ?>" title="Set as primary">
                                        <i class="bi bi-star"></i>
                                    </button>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-danger btn-sm btn-delete-image" 
                                            data-id="<?= $img['id'] ?>" title="Delete">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                                <input type="hidden" name="existing_images[]" value="<?= $img['id'] ?>">
                            </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- SEO -->
                    <div class="admin-form">
                        <h5 class="mb-3">SEO Settings</h5>
                        
                        <div class="mb-3">
                            <label for="meta_title" class="form-label">Meta Title</label>
                            <input type="text" class="form-control" id="meta_title" name="meta_title" 
                                   value="<?= sanitize($product['meta_title'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label for="meta_description" class="form-label">Meta Description</label>
                            <textarea class="form-control" id="meta_description" name="meta_description" 
                                      rows="2"><?= sanitize($product['meta_description'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>
                
                <!-- Right Column: Pricing & Status -->
                <div class="col-lg-4">
                    <div class="admin-form mb-4">
                        <h5 class="mb-3">Pricing</h5>
                        
                        <div class="mb-3">
                            <label for="price" class="form-label">Regular Price (৳) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="price" name="price" 
                                   value="<?= $product['price'] ?? '' ?>" step="0.01" min="0" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="sale_price" class="form-label">Sale Price (৳)</label>
                            <input type="number" class="form-control" id="sale_price" name="sale_price" 
                                   value="<?= $product['sale_price'] ?? '' ?>" step="0.01" min="0">
                            <small class="text-muted">Leave empty if not on sale</small>
                        </div>
                    </div>
                    
                    <div class="admin-form mb-4">
                        <h5 class="mb-3">Inventory</h5>
                        
                        <div class="mb-3">
                            <label for="stock_qty" class="form-label">Stock Quantity</label>
                            <input type="number" class="form-control" id="stock_qty" name="stock_qty" 
                                   value="<?= $product['stock_qty'] ?? 0 ?>" min="0">
                        </div>
                    </div>
                    
                    <div class="admin-form mb-4">
                        <h5 class="mb-3">Status</h5>
                        
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1"
                                   <?= ($product['is_active'] ?? 1) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="is_active">Active (visible on site)</label>
                        </div>
                        
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="is_featured" name="is_featured" value="1"
                                   <?= ($product['is_featured'] ?? 0) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="is_featured">Featured Product</label>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="bi bi-check-lg me-2"></i>
                            <?= $isEdit ? 'Update Product' : 'Create Product' ?>
                        </button>
                        <a href="<?= adminUrl('?page=products') ?>" class="btn btn-outline-secondary">Cancel</a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</main>

<div class="sidebar-overlay"></div>

<script>
// Handle delete existing image
$(document).on('click', '.btn-delete-image', function() {
    const $item = $(this).closest('.image-preview-item');
    const imageId = $(this).data('id');
    
    // Add to delete list
    $('<input>').attr({
        type: 'hidden',
        name: 'delete_images[]',
        value: imageId
    }).appendTo('#productForm');
    
    $item.fadeOut(300, function() { $(this).remove(); });
});

// Handle set primary image
$(document).on('click', '.btn-set-primary', function() {
    const imageId = $(this).data('id');
    
    // Update UI
    $('.image-preview-item').removeClass('primary');
    $(this).closest('.image-preview-item').addClass('primary');
    
    // Set hidden input
    $('#productForm').find('input[name="primary_image_id"]').remove();
    $('<input>').attr({
        type: 'hidden',
        name: 'primary_image_id',
        value: imageId
    }).appendTo('#productForm');
});
</script>

<?php include ADMIN_PATH . '/includes/footer.php'; ?>
