<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/product.php';

// Check if user is admin
if (!isAdmin()) {
    header('Location: ../login.php?redirect=admin/');
    exit;
}

$pageTitle = 'Manage Products';
$productModel = new Product();

// Handle CRUD operations
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create':
                $data = [
                    'name' => sanitize($_POST['name']),
                    'description' => sanitize($_POST['description']),
                    'price' => (float)$_POST['price'],
                    'category' => sanitize($_POST['category']),
                    'image_url' => sanitize($_POST['image_url']),
                    'stock_quantity' => (int)$_POST['stock_quantity'],
                    'sizes' => explode(',', $_POST['sizes']),
                    'colors' => explode(',', $_POST['colors']),
                    'is_active' => isset($_POST['is_active']) ? 1 : 0
                ];
                $result = $productModel->create($data);
                $message = $result['success'] ? 'Product created successfully!' : 'Failed to create product.';
                break;
                
            case 'update':
                $data = [
                    'name' => sanitize($_POST['name']),
                    'description' => sanitize($_POST['description']),
                    'price' => (float)$_POST['price'],
                    'category' => sanitize($_POST['category']),
                    'image_url' => sanitize($_POST['image_url']),
                    'stock_quantity' => (int)$_POST['stock_quantity'],
                    'sizes' => explode(',', $_POST['sizes']),
                    'colors' => explode(',', $_POST['colors']),
                    'is_active' => isset($_POST['is_active']) ? 1 : 0
                ];
                $result = $productModel->update($_POST['id'], $data);
                $message = $result['success'] ? 'Product updated successfully!' : 'Failed to update product.';
                break;
                
            case 'delete':
                $result = $productModel->delete($_POST['id']);
                $message = $result['success'] ? 'Product deleted successfully!' : 'Failed to delete product.';
                break;
        }
    }
}

// Get products
$search = isset($_GET['search']) ? $_GET['search'] : null;
$products = $productModel->getAllAdmin($search);

require_once __DIR__ . '/admin_header.php';
?>

<!-- Admin Products Page -->
<div class="admin-header">
    <h1>Manage Products</h1>
    <button class="btn btn-primary" onclick="openModal('add')">Add New Product</button>
</div>

<?php if ($message): ?>
    <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>

<!-- Search -->
<form method="GET" style="margin-bottom: var(--spacing-lg);">
    <input type="text" name="search" class="search-input" placeholder="Search products..." value="<?php echo htmlspecialchars($search ?? ''); ?>">
    <button type="submit" class="btn btn-secondary">Search</button>
    <?php if ($search): ?>
        <a href="products.php" class="btn">Clear</a>
    <?php endif; ?>
</form>

<!-- Products Table -->
<div class="admin-card">
    <table class="admin-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Image</th>
                <th>Name</th>
                <th>Category</th>
                <th>Price</th>
                <th>Stock</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($products as $product): ?>
                <tr>
                    <td><?php echo $product['id']; ?></td>
                    <td><img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="" style="width: 50px; height: 60px; object-fit: cover;"></td>
                    <td><?php echo htmlspecialchars($product['name']); ?></td>
                    <td><?php echo htmlspecialchars($product['category']); ?></td>
                    <td><?php echo formatPrice($product['price']); ?></td>
                    <td><?php echo $product['stock_quantity']; ?></td>
                    <td><span class="status-badge status-<?php echo $product['is_active'] ? 'delivered' : 'cancelled'; ?>"><?php echo $product['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                    <td>
                        <button class="btn btn-small" onclick="openModal('edit', <?php echo htmlspecialchars(json_encode($product)); ?>)">Edit</button>
                        <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this product?');">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                            <button type="submit" class="btn btn-danger btn-small">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Add/Edit Modal -->
<div class="modal" id="productModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">Add Product</h2>
            <button class="modal-close" onclick="closeModal()">&times;</button>
        </div>
        
        <form method="POST" id="productForm">
            <input type="hidden" name="action" id="formAction" value="create">
            <input type="hidden" name="id" id="productId">
            
            <div class="form-group">
                <label for="name">Product Name</label>
                <input type="text" id="name" name="name" required>
            </div>
            
            <div class="form-group">
                <label for="description">Description</label>
                <textarea id="description" name="description" rows="3"></textarea>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="price">Price</label>
                    <input type="number" id="price" name="price" step="0.01" required>
                </div>
                <div class="form-group">
                    <label for="category">Category</label>
                    <select id="category" name="category" required>
                        <option value="Tops">Tops</option>
                        <option value="Bottoms">Bottoms</option>
                        <option value="Outerwear">Outerwear</option>
                        <option value="Accessories">Accessories</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label for="image_url">Image URL</label>
                <input type="url" id="image_url" name="image_url" required>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="stock_quantity">Stock Quantity</label>
                    <input type="number" id="stock_quantity" name="stock_quantity" value="0" required>
                </div>
                <div class="form-group">
                    <label for="sizes">Sizes (comma separated)</label>
                    <input type="text" id="sizes" name="sizes" placeholder="S, M, L, XL">
                </div>
            </div>
            
            <div class="form-group">
                <label for="colors">Colors (comma separated)</label>
                <input type="text" id="colors" name="colors" placeholder="Black, White, Gray">
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" id="is_active" name="is_active" checked>
                    Active
                </label>
            </div>
            
            <button type="submit" class="btn btn-primary btn-block">Save Product</button>
        </form>
    </div>
</div>

<script>
function openModal(mode, product = null) {
    const modal = document.getElementById('productModal');
    const form = document.getElementById('productForm');
    const title = document.getElementById('modalTitle');
    const formAction = document.getElementById('formAction');
    
    if (mode === 'edit' && product) {
        title.textContent = 'Edit Product';
        formAction.value = 'update';
        document.getElementById('productId').value = product.id;
        document.getElementById('name').value = product.name;
        document.getElementById('description').value = product.description || '';
        document.getElementById('price').value = product.price;
        document.getElementById('category').value = product.category;
        document.getElementById('image_url').value = product.image_url;
        document.getElementById('stock_quantity').value = product.stock_quantity;
        document.getElementById('sizes').value = (product.sizes || []).join(', ');
        document.getElementById('colors').value = (product.colors || []).join(', ');
        document.getElementById('is_active').checked = product.is_active == 1;
    } else {
        title.textContent = 'Add Product';
        formAction.value = 'create';
        form.reset();
    }
    
    modal.classList.add('active');
}

function closeModal() {
    document.getElementById('productModal').classList.remove('active');
}

// Close modal on outside click
document.getElementById('productModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});
</script>

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