<?php

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $conn->real_escape_string($_POST['name']);
    $category_id = (int)$_POST['category_id'];
    $base_price = (float)$_POST['base_price'];
    $stock = (int)$_POST['stock'];
    $description = $conn->real_escape_string($_POST['description']);
    $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
    $is_featured = isset($_POST['is_featured']) ? (int)$_POST['is_featured'] : 0;

    // Handle image upload
    $image_name = '';
    $upload_dir = "../images/products/";
    if (!empty($_FILES['images']['name'][0])) {
        $original_name = basename($_FILES['images']['name'][0]);
        $image_name = time() . '_' . preg_replace("/[^A-Za-z0-9_\-\.]/", '_', $original_name);
        $target_file = $upload_dir . $image_name;
        move_uploaded_file($_FILES['images']['tmp_name'][0], $target_file);
    }

    // Check if editing or adding
    if (!empty($_POST['product_id'])) {
        // Update
        $product_id = (int)$_POST['product_id'];

        if (!empty($image_name)) {
            // Update with new image
            $stmt = $conn->prepare("UPDATE products SET name=?, category_id=?, base_price=?, stock=?, image_url=?, description=?, is_active=?, is_featured=? WHERE product_id=?");
            $stmt->bind_param("siddssiii", $name, $category_id, $base_price, $stock, $image_name, $description, $is_active, $is_featured, $product_id);
        } else {
            // Update without changing image
            $stmt = $conn->prepare("UPDATE products SET name=?, category_id=?, base_price=?, stock=?, description=?, is_active=?, is_featured=? WHERE product_id=?");
            $stmt->bind_param("siddsiii", $name, $category_id, $base_price, $stock, $description, $is_active, $is_featured, $product_id);
        }

        if ($stmt->execute()) {
            header("Location: products.php?success=updated");
            exit;
        } else {
            $error = "Failed to update product: " . $conn->error;
        }

    } else {
        // Insert
        $stmt = $conn->prepare("INSERT INTO products (name, category_id, base_price, stock, image_url, description, is_active, is_featured) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("siddssii", $name, $category_id, $base_price, $stock, $image_name, $description, $is_active, $is_featured);

        if ($stmt->execute()) {
            header("Location: products.php?success=added");
            exit;
        } else {
            $error = "Failed to add product: " . $conn->error;
        }
    }
}
?>

<div class="admin-content">
    <div class="alert alert-danger"><?= $error ?? 'Unknown error occurred.' ?></div>
    <a href="products.php" class="btn btn-secondary">Back to Products</a>
</div>

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