<?php
session_start();
require_once 'config/db.php';
require_once 'includes/auth_check.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: stock.php');
    exit;
}

$db = new Database();
$conn = $db->getConnection();

$product_id = $_POST['product_id'] ?? '';
$type = $_POST['type'] ?? '';
$quantity = $_POST['quantity'] ?? '';
$reason = $_POST['reason'] ?? '';

if (!$product_id || !$type || !$quantity || !is_numeric($quantity) || $quantity <= 0) {
    $_SESSION['error'] = 'جميع الحقول مطلوبة والكمية يجب أن تكون رقماً موجباً';
    header('Location: stock.php');
    exit;
}

try {
    // Début de la transaction
    $conn->beginTransaction();

    // Vérifier le stock actuel
    $stmt = $conn->prepare("SELECT quantity FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$product) {
        throw new Exception('المنتج غير موجود');
    }

    // Calculer la nouvelle quantité
    $new_quantity = $type == 'in' ? 
        $product['quantity'] + $quantity : 
        $product['quantity'] - $quantity;

    // Vérifier si le stock est suffisant pour un retrait
    if ($type == 'out' && $new_quantity < 0) {
        throw new Exception('الكمية المتوفرة غير كافية');
    }

    // Mettre à jour le stock
    $stmt = $conn->prepare("UPDATE products SET quantity = ? WHERE id = ?");
    $stmt->execute([$new_quantity, $product_id]);

    // Enregistrer le mouvement
    $stmt = $conn->prepare("INSERT INTO stock_movements (product_id, type, quantity, reason) VALUES (?, ?, ?, ?)");
    $stmt->execute([$product_id, $type, $quantity, $reason]);

    // Valider la transaction
    $conn->commit();
    $_SESSION['success'] = 'تم تسجيل حركة المخزون بنجاح';

} catch (Exception $e) {
    // Annuler la transaction en cas d'erreur
    $conn->rollBack();
    $_SESSION['error'] = $e->getMessage();
}

header('Location: stock.php');
exit;
