<?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/orders.php', 'Invalid request', 'error');
}

$order_id = (int)($_POST['id'] ?? 0);

if ($order_id <= 0) {
    redirectWithMessage(APP_URL . '/admin/orders.php', 'Invalid order ID', 'error');
}

// Get order items to restore stock
$result = $db->query("SELECT product_id, quantity FROM order_items WHERE order_id = $order_id");
if ($result && $result->num_rows > 0) {
    while ($item = $result->fetch_assoc()) {
        $product_id = $item['product_id'];
        $quantity = $item['quantity'];
        
        // Restore stock
        $db->query("UPDATE products SET stock = stock + $quantity WHERE id = $product_id");
        
        // Log
        $user_id = $_SESSION['user_id'];
        $db->query("INSERT INTO stock_history (product_id, type, quantity_change, reason, user_id) 
                   VALUES ($product_id, 'purchase', $quantity, 'Ștergere comandă #$order_id', $user_id)");
    }
}

// Delete order
$db->query("DELETE FROM order_items WHERE order_id = $order_id");
$db->query("DELETE FROM orders WHERE id = $order_id");

// Audit log
auditLog('delete', 'orders', $order_id, "Comandă #$order_id ștearsă");

redirectWithMessage(APP_URL . '/admin/orders.php', 'Comandă ștearsă cu succes', 'success');
?>
