<?php
session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../../includes/db.php';

try {

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Invalid request method");
    }

    $departmentId = (int)($_POST['target_department'] ?? 0);
    $services = $_POST['selected_services'] ?? [];

    if ($departmentId <= 0) {
        throw new Exception("Select a sub department");
    }

    if (!is_array($services) || count($services) === 0) {
        throw new Exception("Select at least one investigation");
    }

    /*
    |------------------------------------------------------------
    | VALIDATE DEPARTMENT
    |------------------------------------------------------------
    */

    $check = $conn->prepare("
        SELECT id 
        FROM lab_sub_departments 
        WHERE id = ? AND is_active = 1
    ");

    $check->bind_param("i", $departmentId);
    $check->execute();

    if ($check->get_result()->num_rows === 0) {
        throw new Exception("Invalid sub department selected");
    }

    /*
    |------------------------------------------------------------
    | UPDATE MAPPINGS
    |------------------------------------------------------------
    */

    $stmt = $conn->prepare("
        UPDATE service_catalog
        SET lab_sub_dept_id = ?
        WHERE id = ?
    ");

    $updated = 0;

    foreach ($services as $sid) {

        $sid = (int)$sid;

        if ($sid > 0) {

            $stmt->bind_param("ii", $departmentId, $sid);
            $stmt->execute();

            $updated++;
        }
    }

    echo json_encode([
        "success" => true,
        "message" => $updated . " investigations mapped successfully"
    ]);

} catch (Exception $e) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ]);
}