<?php
/**
 * salary_lock.php
 * Centralized concurrency control for salary system
 */

function acquireSalaryLock(PDO $conn, int $timeout = 10): void
{
    $stmt = $conn->prepare("SELECT GET_LOCK('utc_salary_archive_lock', :timeout)");
    $stmt->execute([':timeout' => $timeout]);

    $locked = $stmt->fetchColumn();

    if ((int)$locked !== 1) {
        throw new Exception(
            "System Busy: Another salary process (generation / archive / delete) is running."
        );
    }
}

function releaseSalaryLock(PDO $conn): void
{
    // Always try to release — even if not held
    try {
        $conn->query("SELECT RELEASE_LOCK('utc_salary_archive_lock')");
    } catch (Throwable $e) {
        // Silent fail: lock auto-releases on connection close anyway
    }
}
