<?php
require_once 'admin_config.php';
requireAdminLogin();

$categories = $pdo->query("SELECT * FROM categories ORDER BY name")->fetchAll();
$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category_id = $_POST['category_id'];
    $name = $_POST['name'];
    $description = $_POST['description'];
    $price = $_POST['price'];
    $stock_quantity = $_POST['stock_quantity'];
    
   // Handle image upload
$image_url = null;
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $upload_dir = '../uploads/products/';  // Changed path to go up one level
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    $file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $filename = time() . '_' . uniqid() . '.' . $file_extension;
    $target_file = $upload_dir . $filename;
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
        $image_url = 'uploads/products/' . $filename;  // Relative path from root
    }
}
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO equipment (category_id, name, description, price, stock_quantity, image_url) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$category_id, $name, $description, $price, $stock_quantity, $image_url]);
        $success = 'Product added successfully!';
    } catch(PDOException $e) {
        $error = 'Error adding product: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Product | EliteEquip Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="admin_style.css" rel="stylesheet">
</head>
<body>
<div class="admin-container">
    <?php include 'sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'topbar.php'; ?>
        
        <div class="form-container">
            <h2 style="margin-bottom: 20px;">Add New Product</h2>
            
            <?php if ($success): ?>
                <div class="alert" style="background: #d1fae5; color: #065f46; margin-bottom: 20px;"><?php echo $success; ?></div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert" style="background: #fee2e2; color: #991b1b; margin-bottom: 20px;"><?php echo $error; ?></div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Category *</label>
                    <select name="category_id" class="form-control" required>
                        <option value="">Select Category</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Product Name *</label>
                    <input type="text" name="name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Description *</label>
                    <textarea name="description" class="form-control" required></textarea>
                </div>
                
                <div class="form-group">
                    <label>Price ($) *</label>
                    <input type="number" step="0.01" name="price" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Stock Quantity *</label>
                    <input type="number" name="stock_quantity" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Product Image</label>
                    <input type="file" name="image" class="form-control" accept="image/*">
                    <small style="color: #64748b;">Recommended size: 500x500px</small>
                    <div class="image-preview" id="imagePreview"></div>
                </div>
                
                <button type="submit" class="btn-primary">
                    <i class="fas fa-save"></i> Add Product
                </button>
                <a href="products.php" class="btn-danger" style="padding: 10px 20px; margin-left: 10px;">Cancel</a>
            </form>
        </div>
    </div>
</div>
<script src="admin_script.js"></script>
<script>
document.querySelector('input[name="image"]').addEventListener('change', function(e) {
    const preview = document.getElementById('imagePreview');
    if (this.files && this.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.innerHTML = `<img src="${e.target.result}" style="max-width: 200px; border-radius: 10px; margin-top: 10px;">`;
        };
        reader.readAsDataURL(this.files[0]);
    }
});
</script>
</body>
</html>