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

if (!isLoggedIn()) {
    redirectWithMessage(APP_URL . '/login.php', 'Trebuie să te conectezi', 'error');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirectWithMessage(APP_URL . '/admin/products.php', 'Invalid request', 'error');
}

$id = $_POST['id'] ?? null;
$name = escape($_POST['name'] ?? '');
$price = (float)($_POST['price'] ?? 0);
$cost = (float)($_POST['cost'] ?? 0);
$stock = (int)($_POST['stock'] ?? 0);
$min_stock = (int)($_POST['min_stock'] ?? 5);
$category_id = (int)($_POST['category_id'] ?? 1);
$sku = escape($_POST['sku'] ?? '');
$description = escape($_POST['description'] ?? '');
$active = (int)($_POST['active'] ?? 1);

if (empty($name)) {
    redirectWithMessage(APP_URL . '/admin/products.php', 'Numele produsului este obligatoriu', 'error');
}

if ($id) {
    // Update existing product
    $id = (int)$id;
    $query = "UPDATE products 
              SET name='$name', price=$price, cost=$cost, stock=$stock, min_stock=$min_stock, 
                  category_id=$category_id, sku='$sku', description='$description', active=$active
              WHERE id=$id";
    
    if ($db->query($query)) {
        auditLog('update', 'products', $id, $name, [], ['price' => $price, 'stock' => $stock, 'cost' => $cost]);
        redirectWithMessage(APP_URL . '/admin/products.php', 'Produs actualizat cu succes', 'success');
    } else {
        redirectWithMessage(APP_URL . '/admin/products.php', 'Eroare la actualizare: ' . $db->error, 'error');
    }
} else {
    // Insert new product
    $query = "INSERT INTO products (name, price, cost, stock, min_stock, category_id, sku, description, active)
              VALUES ('$name', $price, $cost, $stock, $min_stock, $category_id, '$sku', '$description', $active)";
    
    if ($db->query($query)) {
        $product_id = $db->insert_id;
        auditLog('create', 'products', $product_id, $name, [], ['price' => $price, 'stock' => $stock, 'cost' => $cost]);
        redirectWithMessage(APP_URL . '/admin/products.php', 'Produs adăugat cu succes', 'success');
    } else {
        redirectWithMessage(APP_URL . '/admin/products.php', 'Eroare la adăugare: ' . $db->error, 'error');
    }
}
?>
