<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mapping'])) {
    $staff_id = $_SESSION['staff_id'] ?? 1;
    $mappings = $_POST['mapping']; // Array: [service_id => sub_dept_id]

    $conn->begin_transaction();
    try {
        $stmt = $conn->prepare("UPDATE service_catalog SET lab_sub_dept_id = ? WHERE id = ?");
        
        foreach ($mappings as $service_id => $sub_dept_id) {
            $sid = (int)$service_id;
            $did = ((int)$sub_dept_id === 0) ? null : (int)$sub_dept_id;
            
            $stmt->bind_param("ii", $did, $sid);
            $stmt->execute();
        }

        // Optional: Audit Logging logic here matching processAddLabParameter.php
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Routing matrix updated successfully.']);
        
    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Failed to save: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Request']);
}