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

$id = $_GET['id'] ?? 0;
$stmt = $pdo->prepare("SELECT * FROM equipment WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();

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

$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'];
    
   $image_url = $product['image_url'];
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $upload_dir = '../uploads/products/';
    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)) {
        // Delete old image if exists
        if ($image_url && file_exists('../' . $image_url)) {
            unlink('../' . $image_url);
        }
        $image_url = 'uploads/products/' . $filename;
    }
}
    
    try {
        $stmt = $pdo->prepare("
            UPDATE equipment 
            SET category_id = ?, name = ?, description = ?, price = ?, stock_quantity = ?, image_url = ? 
            WHERE id = ?
        ");
        $stmt->execute([$category_id, $name, $description, $price, $stock_quantity, $image_url, $id]);
        $success = 'Product updated successfully!';
        $product = array_merge($product, ['category_id' => $category_id, 'name' => $name, 'description' => $description, 'price' => $price, 'stock_quantity' => $stock_quantity, 'image_url' => $image_url]);
    } catch(PDOException $e) {
        $error = 'Error updating 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>Edit 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;">Edit 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 $cat['id'] == $product['category_id'] ? 'selected' : ''; ?>>
                                <?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" value="<?php echo htmlspecialchars($product['name']); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Description *</label>
                    <textarea name="description" class="form-control" required><?php echo htmlspecialchars($product['description']); ?></textarea>
                </div>
                
                <div class="form-group">
                    <label>Price ($) *</label>
                    <input type="number" step="0.01" name="price" class="form-control" value="<?php echo $product['price']; ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Stock Quantity *</label>
                    <input type="number" name="stock_quantity" class="form-control" value="<?php echo $product['stock_quantity']; ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Product Image</label>
                    <input type="file" name="image" class="form-control" accept="image/*">
                    <?php if ($product['image_url']): ?>
                        <div class="image-preview">
                            <img src="<?php echo $product['image_url']; ?>" style="max-width: 200px; border-radius: 10px; margin-top: 10px;">
                        </div>
                    <?php endif; ?>
                    <div class="image-preview" id="imagePreview"></div>
                </div>
                
                <button type="submit" class="btn-primary">
                    <i class="fas fa-save"></i> Update Product
                </button>
                <a href="products.php" class="btn-danger" style="padding: 10px 20px; margin-left: 10px;">Cancel</a>
            </form>
        </div>
    </div>
</div>

<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>
<script src="admin_script.js"></script>
</body>
</html>