<?php

function payroll_pick_field(array $row, array $candidates)
{
    foreach ($candidates as $field) {
        if (array_key_exists($field, $row) && $row[$field] !== null && $row[$field] !== '') {
            return $row[$field];
        }
    }

    return null;
}

function payroll_employee_name(array $row): string
{
    $fullName = payroll_pick_field($row, ['full_name']);
    if ($fullName) {
        return (string) $fullName;
    }

    $parts = array_filter([
        payroll_pick_field($row, ['first_name', 'firstname']),
        payroll_pick_field($row, ['middle_name', 'middlename']),
        payroll_pick_field($row, ['last_name', 'lastname']),
    ]);

    return $parts ? implode(' ', $parts) : 'Employee';
}

function payroll_employee_code(array $row): string
{
    $code = payroll_pick_field($row, ['employee_code', 'employee_id', 'emp_code', 'id']);
    return trim((string) $code);
}

function payroll_org_context(mysqli $conn): array
{
    $result = $conn->query("SELECT * FROM organizations ORDER BY id DESC LIMIT 1");
    $row = $result ? $result->fetch_assoc() : null;

    return [
        'org_name' => $_SESSION['org_name'] ?? ($row['organisation_name'] ?? 'demo'),
        'org_id' => (string) ($_SESSION['org_id'] ?? ($row['organisation_id'] ?? ($row['id'] ?? '60066881652'))),
        'display_name' => $_SESSION['username'] ?? ($_SESSION['org_name'] ?? ($row['organisation_name'] ?? 'demo')),
    ];
}

function payroll_load_employees(mysqli $conn): array
{
    $employees = [];
    $org = payroll_org_context($conn);
    $hasOrgColumnResult = $conn->query("SHOW COLUMNS FROM employees LIKE 'organization_id'");
    $hasOrgColumn = (bool) ($hasOrgColumnResult && $hasOrgColumnResult->num_rows > 0);

    if ($hasOrgColumn) {
        $orgId = (int) ($org['org_id'] ?? 0);
        $stmt = $conn->prepare("SELECT * FROM employees WHERE organization_id = ? AND COALESCE(is_deleted, 0) = 0 ORDER BY id DESC");
        if ($stmt) {
            $stmt->bind_param('i', $orgId);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($result && ($row = $result->fetch_assoc())) {
                $employees[] = $row;
            }
            $stmt->close();
        }
    } else {
        $result = $conn->query("SELECT * FROM employees WHERE COALESCE(is_deleted, 0) = 0 ORDER BY id DESC");
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $employees[] = $row;
            }
        }
    }

    return $employees;
}

function payroll_table_exists(mysqli $conn, string $table): bool
{
    $safeTable = $conn->real_escape_string($table);
    $result = $conn->query("SHOW TABLES LIKE '{$safeTable}'");
    return (bool) ($result && $result->num_rows > 0);
}

function payroll_missing_tables(mysqli $conn, array $tables): array
{
    $missing = [];
    foreach ($tables as $table) {
        if (!payroll_table_exists($conn, $table)) {
            $missing[] = $table;
        }
    }

    return $missing;
}

function payroll_format_currency($amount): string
{
    return 'Rs ' . number_format((float) $amount, 2);
}

function payroll_month_label(?string $value): string
{
    if (!$value) {
        return '-';
    }

    $ts = strtotime($value);
    return $ts ? date('M Y', $ts) : (string) $value;
}

function payroll_date_label(?string $value): string
{
    if (!$value) {
        return '-';
    }

    $ts = strtotime($value);
    return $ts ? date('d M Y', $ts) : (string) $value;
}

function payroll_redirect_with_flash(string $page, string $message, bool $isError = false): void
{
    if ($isError) {
        $_SESSION['flash_err'] = $message;
    } else {
        $_SESSION['flash_ok'] = $message;
    }

    header('Location: ' . $page);
    exit();
}
