<?php

$GLOBALS['globals_branch_names_already_fetched'] = [];
$GLOBALS['globals_branch_ids_already_fetched'] = [];


function getBranchId($conn, $institution_id, $branch_name) {
    $branch_name_key = strtolower(trim($branch_name));

    // Check cache
    if (in_array($branch_name_key, $GLOBALS['globals_branch_names_already_fetched'])) {
        return $GLOBALS['globals_branch_ids_already_fetched'][
            array_search($branch_name_key, $GLOBALS['globals_branch_names_already_fetched'])
        ];
    }

    // Fetch from DB
    $stmt = $conn->prepare("SELECT id FROM branch WHERE name = ? AND institution_id = ?");
    $stmt->execute([$branch_name, $institution_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        errorreturn("Branch not found: '$branch_name'");
    }

    // Store in global cache
    $GLOBALS['globals_branch_names_already_fetched'][] = $branch_name_key;
    $GLOBALS['globals_branch_ids_already_fetched'][] = $result['id'];

    return $result['id'];
}
