<?php
require_once '../includes/header.php';
require_once '../includes/require_admin.php';

// Get product ID from URL
$product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get product details
$product = getProductById($pdo, $product_id);

if (!$product) {
    redirect(SITE_URL . '/admin/products.php');
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitizeInput($_POST['name']);
    $description = sanitizeInput($_POST['description']);
    $price = floatval($_POST['price']);
    $category = sanitizeInput($_POST['category']);
    
    // Handle file upload
    $image = $product['image']; // Keep existing image by default
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../assets/uploads/';
        $fileName = basename($_FILES['image']['name']);
        $targetFilePath = $uploadDir . $fileName;
        $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
        
        // Allow certain file formats
        $allowTypes = array('jpg', 'png', 'jpeg', 'gif');
        if (in_array($fileType, $allowTypes)) {
            // Upload file to server
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFilePath)) {
                // Save relative path to database
                $image = 'assets/uploads/' . $fileName;
            } else {
                $message = '<div class="message error">Failed to upload image.</div>';
            }
        } else {
            $message = '<div class="message error">Sorry, only JPG, JPEG, PNG, & GIF files are allowed.</div>';
        }
    }
    
    // Validation
    if (empty($name) || empty($description) || empty($price) || empty($category)) {
        $message = '<div class="message error">All fields are required.</div>';
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, category = ?, image = ? WHERE id = ?");
            $stmt->execute([$name, $description, $price, $category, $image, $product_id]);
            
            $message = '<div class="message success">Product updated successfully.</div>';
            
            // Refresh product data
            $product = getProductById($pdo, $product_id);
        } catch (PDOException $e) {
            $message = '<div class="message error">Error updating product.</div>';
        }
    }
}
?>

<div class="container">
    <div class="admin-header">
        <h2>Edit Product</h2>
        <a href="<?php echo SITE_URL; ?>/admin/products.php" class="btn btn-outline">Back to Products</a>
    </div>
    
    <div class="admin-nav">
        <ul>
            <li><a href="<?php echo SITE_URL; ?>/admin/index.php">Dashboard</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/products.php">Products</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/add_product.php">Add Product</a></li>
    </ul>
    </div>
    
    <?php echo $message; ?>
    
    <div class="form-container">
        <form method="POST" action="" enctype="multipart/form-data">
            <div class="form-group">
                <label for="name">Product Name</label>
                <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($product['name']); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="description">Description</label>
                <textarea id="description" name="description" rows="4" required><?php echo htmlspecialchars($product['description']); ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="price">Price ($)</label>
                <input type="number" id="price" name="price" step="0.01" min="0" value="<?php echo htmlspecialchars($product['price']); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="category">Category</label>
                <select id="category" name="category" required>
                    <option value="">Select Category</option>
                    <option value="Electronics" <?php echo ($product['category'] === 'Electronics') ? 'selected' : ''; ?>>Electronics</option>
                    <option value="Clothing" <?php echo ($product['category'] === 'Clothing') ? 'selected' : ''; ?>>Clothing</option>
                    <option value="Home & Garden" <?php echo ($product['category'] === 'Home & Garden') ? 'selected' : ''; ?>>Home & Garden</option>
                    <option value="Books" <?php echo ($product['category'] === 'Books') ? 'selected' : ''; ?>>Books</option>
                    <option value="Sports" <?php echo ($product['category'] === 'Sports') ? 'selected' : ''; ?>>Sports</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="image">Product Image</label>
                <input type="file" id="image" name="image" accept="image/*">
                <?php if (!empty($product['image'])): ?>
                    <div class="product-image-preview">
                        <p>Current Image:</p>
                        <img src="<?php echo SITE_URL . '/' . htmlspecialchars($product['image']); ?>" alt="Product Image" style="max-width: 200px; height: auto;">
                    </div>
                <?php endif; ?>
            </div>
            
            <button type="submit" class="btn btn-primary btn-large btn-block">Update Product</button>
        </form>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>