<?php
// === UTILITY FUNCTIONS ===

// Clean input helper
function clean_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function payroll_generate_org_code(int $id): string
{
    $year = date('Y');
    $suffix = str_pad((string) $id, 4, '0', STR_PAD_LEFT);
    return "ORG{$year}_{$suffix}";
}

function payroll_current_user_email(string $fallback = 'user@example.com'): string
{
    $sessionEmail = trim((string) ($_SESSION['user_email'] ?? ''));
    if ($sessionEmail !== '' && filter_var($sessionEmail, FILTER_VALIDATE_EMAIL)) {
        return $sessionEmail;
    }

    $sessionUser = trim((string) ($_SESSION['user'] ?? ''));
    if ($sessionUser !== '' && filter_var($sessionUser, FILTER_VALIDATE_EMAIL)) {
        return $sessionUser;
    }

    return $fallback;
}

// Mask email for display
function mask_email($email) {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return $email;
    [$user, $domain] = explode('@', $email);
    $userMasked = substr($user, 0, 2) . str_repeat('*', max(2, strlen($user) - 4)) . substr($user, -2);
    $domainParts = explode('.', $domain);
    $domainMasked = substr($domainParts[0], 0, 1) . str_repeat('*', max(1, strlen($domainParts[0]) - 2)) . substr($domainParts[0], -1);
    $tld = implode('.', array_slice($domainParts, 1));
    return $userMasked . '@' . $domainMasked . '.' . $tld;
}
?>

