<?php
/**
 * Server Update Order Item Quantity API
 * Allows servers to edit the quantity of items in a placed order after placing the order
 * Customers can change their mind and decrease/increase quantity before payment
 */

session_start();
header('Content-Type: application/json');
require_once 'config.php';

// Suppress any output that might interfere with JSON
ini_set('display_errors', 0);

// Check server authentication
if (!isset($_SESSION['server_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$server_id = $_SESSION['server_id'];
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['order_id']) || !isset($input['item_id']) || !isset($input['new_quantity'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request. Missing order_id, item_id, or new_quantity.']);
    exit;
}

$order_id = (int)$input['order_id'];
$item_id = (int)$input['item_id'];
$new_quantity = (int)$input['new_quantity'];

// Validate quantity
if ($new_quantity < 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid quantity. Quantity cannot be negative.']);
    exit;
}

try {
    error_log('=== Updating item ' . $item_id . ' quantity to ' . $new_quantity . ' in order ' . $order_id . ' ===');
    
    // Verify order ownership and get order details
    $verify_sql = "SELECT id, server_id, status, total_amount FROM dine_in_orders WHERE id = $order_id AND server_id = $server_id";
    $result = $conn->query($verify_sql);
    
    if (!$result || $result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Order not found or not assigned to you']);
        exit;
    }
    
    $order_data = $result->fetch_assoc();
    
    // Check if order is in a state where it can be edited
    // Allow editing for: pending, confirmed, preparing statuses
    $non_editable_statuses = ['served', 'completed', 'cancelled'];
    if (in_array($order_data['status'], $non_editable_statuses)) {
        echo json_encode(['success' => false, 'message' => 'Cannot edit quantities for orders that are ' . $order_data['status']]);
        exit;
    }
    
    // Get the current item details
    $item_sql = "SELECT id, quantity, unit_price, total_price FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND item_id = $item_id";
    $item_result = $conn->query($item_sql);
    
    if (!$item_result || $item_result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Item not found in this order']);
        exit;
    }
    
    $item_data = $item_result->fetch_assoc();
    $current_quantity = (int)$item_data['quantity'];
    $unit_price = (float)$item_data['unit_price'];
    
    // Begin transaction
    $conn->begin_transaction();
    
    // If new quantity is 0, delete the item
    if ($new_quantity === 0) {
        // Delete ONLY non-served items (don't delete served items when deleting reorders)
        $delete_sql = "DELETE FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND item_id = $item_id AND status != 'served'";
        
        if (!$conn->query($delete_sql)) {
            throw new Exception('Delete query failed: ' . $conn->error);
        }
        
        error_log("Item $item_id deleted from order $order_id");
    } else {
        // Update ONLY non-served items (don't update served items when updating reorders)
        $new_total_price = $unit_price * $new_quantity;
        $update_sql = "UPDATE dine_in_order_items SET quantity = $new_quantity, total_price = $new_total_price WHERE dine_in_order_id = $order_id AND item_id = $item_id AND status != 'served'";
        
        if (!$conn->query($update_sql)) {
            throw new Exception('Update query failed: ' . $conn->error);
        }
        
        error_log("Item $item_id quantity updated. Old: $current_quantity, New: $new_quantity");
    }
    
    // Recalculate order total
    $total_sql = "UPDATE dine_in_orders SET total_amount = (SELECT COALESCE(SUM(total_price), 0) FROM dine_in_order_items WHERE dine_in_order_id = $order_id) WHERE id = $order_id";
    
    if (!$conn->query($total_sql)) {
        throw new Exception('Total update failed: ' . $conn->error);
    }
    
    error_log("Order $order_id total recalculated");
    
    // Commit transaction
    $conn->commit();
    
    // Get updated order total for response
    $updated_order_sql = "SELECT total_amount FROM dine_in_orders WHERE id = $order_id";
    $updated_order_result = $conn->query($updated_order_sql);
    $updated_order = $updated_order_result->fetch_assoc();
    
    echo json_encode([
        'success' => true,
        'message' => $new_quantity === 0 ? 'Item removed from order' : 'Item quantity updated successfully',
        'order_id' => $order_id,
        'item_id' => $item_id,
        'old_quantity' => $current_quantity,
        'new_quantity' => $new_quantity,
        'order_total' => (float)$updated_order['total_amount']
    ]);
    
    error_log('=== Quantity update complete ===');
    
} catch (Exception $e) {
    $conn->rollback();
    error_log('ERROR: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
