<?php
include '../db.php';
include '../auth.php';
require_right('Access POS');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['item_id']) || !isset($input['station_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$item_id = intval($input['item_id']);
$station_id = $input['station_id'] === '' ? null : intval($input['station_id']);

try {
    // Begin transaction
    $conn->begin_transaction();
    
    // Remove existing assignment for this item
    $stmt = $conn->prepare("DELETE FROM kds_station_items WHERE item_id = ?");
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    
    // If station_id is provided, create new assignment
    if ($station_id !== null) {
        $stmt = $conn->prepare("INSERT INTO kds_station_items (station_id, item_id) VALUES (?, ?)");
        $stmt->bind_param("ii", $station_id, $item_id);
        $stmt->execute();
    }
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode(['success' => true, 'message' => 'Assignment updated successfully']);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
