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

if (!isLoggedIn()) {
    redirectWithMessage(APP_URL . '/login.php', 'Unauthorized', 'error');
}

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

$product_id = (int)($_POST['product_id'] ?? 0);
$quantity = (int)($_POST['quantity'] ?? 0);

if ($product_id <= 0 || $quantity == 0) {
    redirectWithMessage(APP_URL . '/admin/stock.php', 'Date nevalide', 'error');
}

// Get current stock
$result = $db->query("SELECT stock FROM products WHERE id = $product_id");
if (!$result || $result->num_rows == 0) {
    redirectWithMessage(APP_URL . '/admin/stock.php', 'Produs nu a fost găsit', 'error');
}

$current_stock = $result->fetch_assoc()['stock'];
$new_stock = max(0, $current_stock + $quantity);

// Update stock
$query = "UPDATE products SET stock = $new_stock WHERE id = $product_id";

if ($db->query($query)) {
    // Log stock history
    $user_id = $_SESSION['user_id'];
    $reason = $quantity > 0 ? 'Adăugare manuală' : 'Scădere manuală';
    $db->query("INSERT INTO stock_history (product_id, type, quantity_change, reason, user_id) 
               VALUES ($product_id, 'adjustment', $quantity, '$reason', $user_id)");
    
    redirectWithMessage(APP_URL . '/admin/stock.php', 'Stoc ajustat cu succes', 'success');
} else {
    redirectWithMessage(APP_URL . '/admin/stock.php', 'Eroare la ajustare: ' . $db->error, 'error');
}
?>
