<?php
require_once __DIR__ . '/includes/admin_header.php';

// Fetch categories
$categories_result = $conn->query("SELECT * FROM categories ORDER BY name");
$categories = [];
while ($row = $categories_result->fetch_assoc()) {
    $categories[] = $row;
}

// Fetch product if editing
$product = null;
if (isset($_GET['id'])) {
    $product_id = intval($_GET['id']);

    $stmt = $conn->prepare("SELECT * FROM products WHERE product_id = ?");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $product = $result->fetch_assoc();
    $stmt->close();

    if (!$product) {
        header("Location: products.php");
        exit();
    }
}
?>

<div class="admin-content">
    <div class="page-header">
        <h1 class="page-title"><?= $product ? 'Edit Product' : 'Add New Product' ?></h1>
        <div class="breadcrumb">
            <li><a href="products.php">Products</a></li>
            <li><?= $product ? 'Edit' : 'Add New' ?></li>
        </div>
    </div>

    <form class="form-container" action="product_save.php" method="post" enctype="multipart/form-data">
        <?php if ($product): ?>
            <input type="hidden" name="product_id" value="<?= htmlspecialchars($product['product_id']) ?>">
        <?php endif; ?>

        <div class="form-grid">
            <div class="form-group">
                <label for="name">Product Name</label>
                <input type="text" id="name" name="name" class="form-control"
                       value="<?= htmlspecialchars($product['name'] ?? '') ?>" required>
            </div>

            <div class="form-group">
                <label for="category_id">Category</label>
                <select id="category_id" name="category_id" class="form-control">
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $category): ?>
                        <option value="<?= $category['category_id'] ?>"
                            <?= ($product['category_id'] ?? '') == $category['category_id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($category['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="base_price">Price (KSh)</label>
                <input type="number" id="base_price" name="base_price" class="form-control"
                       step="0.01" min="0" value="<?= htmlspecialchars($product['base_price'] ?? '') ?>" required>
            </div>

            <div class="form-group">
                <label for="stock">Stock Quantity</label>
                <input type="number" id="stock" name="stock" class="form-control"
                       min="0" value="<?= htmlspecialchars($product['stock'] ?? 0) ?>">
            </div>

            <div class="form-group">
                <label for="is_featured">Featured Product</label>
                <select id="is_featured" name="is_featured" class="form-control">
                    <option value="0" <?= ($product['is_featured'] ?? 0) == 0 ? 'selected' : '' ?>>No</option>
                    <option value="1" <?= ($product['is_featured'] ?? 0) == 1 ? 'selected' : '' ?>>Yes</option>
                </select>
            </div>

            <div class="form-group">
                <label for="is_active">Status</label>
                <select id="is_active" name="is_active" class="form-control">
                    <option value="1" <?= ($product['is_active'] ?? 1) == 1 ? 'selected' : '' ?>>Active</option>
                    <option value="0" <?= ($product['is_active'] ?? 1) == 0 ? 'selected' : '' ?>>Inactive</option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label for="description">Description</label>
            <textarea id="description" name="description" class="form-control"
                      rows="5"><?= htmlspecialchars($product['description'] ?? '') ?></textarea>
        </div>

        <div class="form-group">
            <label>Product Images</label>
            <div class="file-upload" id="fileUpload">
                <i class="fas fa-cloud-upload-alt"></i>
                <p>Drag & drop files here or click to browse</p>
                <input type="file" id="images" name="images[]" multiple accept="image/*">
            </div>

            <?php if ($product && $product['image_url']): ?>
                <div class="image-preview">
                    <div class="preview-item">
                        <img src="../images/products/<?= htmlspecialchars($product['image_url']) ?>" alt="Current Image">
                        <div class="remove-image" onclick="removeImage(<?= $product['product_id'] ?>)">
                            <i class="fas fa-times"></i>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="form-actions">
            <a href="products.php" class="btn">Cancel</a>
            <button type="submit" class="btn btn-primary">Save Product</button>
        </div>
    </form>
</div>

<script>
    const fileUpload = document.getElementById('fileUpload');
    const fileInput = document.querySelector('#fileUpload input[type="file"]');

    fileUpload.addEventListener('dragover', (e) => {
        e.preventDefault();
        fileUpload.style.borderColor = '#4f46e5';
        fileUpload.style.backgroundColor = 'rgba(79, 70, 229, 0.05)';
    });

    fileUpload.addEventListener('dragleave', () => {
        fileUpload.style.borderColor = '#d1d5db';
        fileUpload.style.backgroundColor = 'transparent';
    });

    fileUpload.addEventListener('drop', (e) => {
        e.preventDefault();
        fileUpload.style.borderColor = '#d1d5db';
        fileUpload.style.backgroundColor = 'transparent';
        fileInput.files = e.dataTransfer.files;
        updateFileList();
    });

    fileUpload.addEventListener('click', () => {
        fileInput.click();
    });

    fileInput.addEventListener('change', updateFileList);

    function updateFileList() {
        if (fileInput.files.length > 0) {
            fileUpload.querySelector('p').textContent = `${fileInput.files.length} file(s) selected`;
        }
    }

    function removeImage(productId) {
        if (confirm('Are you sure you want to remove this image?')) {
            window.location.href = `product_remove_image.php?product_id=${productId}`;
        }
    }
</script>

<?php require_once __DIR__ . '/includes/admin_footer.php'; ?>
