<?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 = $_POST['id'] ?? null;
$first_name = escape($_POST['first_name'] ?? '');
$last_name = escape($_POST['last_name'] ?? '');
$phone = escape($_POST['phone'] ?? '');
$status_id = (int)($_POST['status_id'] ?? 1);
$discount_id = ($_POST['discount_id'] ?? '') ? (int)$_POST['discount_id'] : null;
$order_date = escape($_POST['order_date'] ?? date('Y-m-d'));
$notes = escape($_POST['notes'] ?? '');
$delivery_enabled = isset($_POST['delivery_enabled']) ? 1 : 0;
$delivery_price = $delivery_enabled ? (float)($_POST['delivery_price'] ?? 0) : 0;
$delivery_address = escape($_POST['delivery_address'] ?? '');

$product_ids = $_POST['product_id'] ?? [];
$quantities = $_POST['quantity'] ?? [];
$prices = $_POST['price'] ?? [];

if (empty($first_name)) {
    redirectWithMessage(APP_URL . '/admin/orders.php', 'Numele clientului este obligatoriu', 'error');
}

if (empty($product_ids)) {
    redirectWithMessage(APP_URL . '/admin/orders.php', 'Trebuie să adaugi cel puțin un produs', 'error');
}

// Get or create client
$existing_client = $db->query("SELECT id FROM clients WHERE first_name = '$first_name' AND last_name = '$last_name' AND phone = '$phone' LIMIT 1");
if ($existing_client && $existing_client->num_rows > 0) {
    $client_id = $existing_client->fetch_assoc()['id'];
} else {
    // Create new client
    $db->query("INSERT INTO clients (first_name, last_name, phone, status_id) VALUES ('$first_name', '$last_name', '$phone', 1)");
    $client_id = $db->insert_id;
}

if ($order_id) {
    // Update existing order
    $order_id = (int)$order_id;
    
    // Update order
    $query = "UPDATE orders 
              SET client_id=$client_id, status_id=$status_id, discount_id=" . ($discount_id ? $discount_id : "NULL") . ", 
                  order_date='$order_date', notes='$notes', delivery_enabled=$delivery_enabled, 
                  delivery_price=$delivery_price, delivery_address='$delivery_address'
              WHERE id=$order_id";
    
    if (!$db->query($query)) {
        redirectWithMessage(APP_URL . '/admin/orders.php', 'Eroare la actualizare: ' . $db->error, 'error');
    }
    
    // Delete old items
    $db->query("DELETE FROM order_items WHERE order_id = $order_id");
} else {
    // Create new order
    $query = "INSERT INTO orders (client_id, status_id, discount_id, order_date, notes, delivery_enabled, delivery_price, delivery_address)
              VALUES ($client_id, $status_id, " . ($discount_id ? $discount_id : "NULL") . ", '$order_date', '$notes', $delivery_enabled, $delivery_price, '$delivery_address')";
    
    if (!$db->query($query)) {
        redirectWithMessage(APP_URL . '/admin/orders.php', 'Eroare la creare: ' . $db->error, 'error');
    }
    
    $order_id = $db->insert_id;
}

// Add/update items
for ($i = 0; $i < count($product_ids); $i++) {
    $product_id = (int)$product_ids[$i];
    $quantity = (int)($quantities[$i] ?? 1);
    
    // Get price from database, not from form
    $product_result = $db->query("SELECT price FROM products WHERE id = $product_id");
    $product_data = $product_result ? $product_result->fetch_assoc() : null;
    $price = $product_data ? (float)$product_data['price'] : 0;
    
    $db->query("INSERT INTO order_items (order_id, product_id, quantity, price) 
               VALUES ($order_id, $product_id, $quantity, $price)");
}

// Update product stock if new order
if (!$_POST['id']) {
    for ($i = 0; $i < count($product_ids); $i++) {
        $product_id = (int)$product_ids[$i];
        $quantity = (int)($quantities[$i] ?? 1);
        
        // Get current stock
        $result = $db->query("SELECT stock FROM products WHERE id = $product_id");
        $current_stock = $result->fetch_assoc()['stock'];
        $new_stock = max(0, $current_stock - $quantity);
        
        // Update stock
        $db->query("UPDATE products SET stock = $new_stock 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, 'sale', -$quantity, 'Vânzare comandă #$order_id', $user_id)");
    }
}

// Audit log
$first_name_last_two = str_repeat('*', max(0, strlen($first_name) - 2)) . substr($first_name, -2);
$order_name = "$first_name_last_two $last_name - ID $order_id";
auditLog(
    $_POST['id'] ? 'update' : 'create',
    'orders',
    $order_id,
    $order_name,
    [], // old values would require fetching before update, skipping for brevity
    ['client' => "$first_name $last_name", 'status' => $status_id, 'items_count' => count($product_ids), 'total' => $order_date]
);

redirectWithMessage(APP_URL . '/admin/orders.php', 
    $order_id && $_POST['id'] ? 'Comandă actualizată cu succes' : 'Comandă creată cu succes', 
    'success');
?>
