<?php
/**
 * HR module bootstrap: schema ensure, defaults, CSRF, role checks.
 * Requires: mysqli $conn from layouts/dbconn.php, session started, $_SESSION['user_id'].
 */

if (!function_exists('hr_ensure_schema')) {
    function hr_ensure_schema(mysqli $conn): void
    {
        static $done = false;
        if ($done) {
            return;
        }
        $path = __DIR__ . '/hr_schema_statements.php';
        if (!is_readable($path)) {
            return;
        }
        $stmts = include $path;
        if (!is_array($stmts)) {
            return;
        }
        foreach ($stmts as $sql) {
            if (!$conn->query($sql)) {
                error_log('HR schema error: ' . $conn->error);
            }
        }
        hr_seed_defaults($conn);
        $done = true;
    }

    function hr_seed_defaults(mysqli $conn): void
    {
        $r = $conn->query("SELECT COUNT(*) AS c FROM hr_leave_types");
        if ($r && ($row = $r->fetch_assoc()) && (int)$row['c'] === 0) {
            $defaults = [
                ['Annual Leave', 21, 1, 0, 1],
                ['Sick Leave', 14, 0, 1, 1],
                ['Maternity Leave', 90, 0, 1, 1],
                ['Paternity Leave', 14, 0, 0, 1],
                ['Compassionate Leave', 5, 0, 0, 1],
                ['Study Leave', 5, 0, 0, 1],
            ];
            $st = $conn->prepare("INSERT INTO hr_leave_types (type_name, days_per_year, allow_carry_forward, requires_attachment, is_paid) VALUES (?,?,?,?,?)");
            foreach ($defaults as $d) {
                $nm = $d[0];
                $dy = (float)$d[1];
                $cf = (int)$d[2];
                $at = (int)$d[3];
                $pd = (int)$d[4];
                $st->bind_param('sdiii', $nm, $dy, $cf, $at, $pd);
                $st->execute();
            }
            $st->close();
        }

        $settings = [
            'PAYE_PERSONAL_RELIEF' => ['2400', 'Monthly personal relief (KES), resident — verify with KRA'],
            'SHIF_EE_RATE' => ['0.0275', 'SHIF employee % of gross (Social Health Insurance Act — adjust if law changes)'],
            'SHIF_ER_RATE' => ['0.0275', 'SHIF employer % of gross (mirror; verify statutory split)'],
            'HOUSING_EE_RATE' => ['0.015', 'Affordable Housing Levy employee rate'],
            'HOUSING_ER_RATE' => ['0.015', 'Affordable Housing Levy employer rate'],
            'NSSF_LEL' => ['7000', 'NSSF lower earnings limit (monthly pensionable band)'],
            'NSSF_IEL' => ['36000', 'NSSF upper pensionable ceiling for Tier II (monthly)'],
            'NSSF_EE_RATE' => ['0.06', 'NSSF tier contribution rate (6% each tier segment)'],
            'NSSF_ER_RATE' => ['0.06', 'Employer NSSF rate on matching bands (simplified mirror)'],
        ];
        $chk = $conn->prepare("SELECT 1 FROM hr_settings WHERE setting_key = ? LIMIT 1");
        $ins = $conn->prepare("INSERT INTO hr_settings (setting_key, setting_value, description) VALUES (?,?,?)");
        foreach ($settings as $k => $pair) {
            $chk->bind_param('s', $k);
            $chk->execute();
            $res = $chk->get_result();
            if ($res && $res->num_rows === 0) {
                $v = $pair[0];
                $d = $pair[1];
                $ins->bind_param('sss', $k, $v, $d);
                $ins->execute();
            }
        }
        $chk->close();
        $ins->close();
    }

    function hr_setting(mysqli $conn, string $key, string $default = '0'): string
    {
        $st = $conn->prepare("SELECT setting_value FROM hr_settings WHERE setting_key = ? LIMIT 1");
        $st->bind_param('s', $key);
        $st->execute();
        $row = $st->get_result()->fetch_assoc();
        $st->close();
        return $row ? (string)$row['setting_value'] : $default;
    }

    function hr_csrf_token(): string
    {
        if (empty($_SESSION['hr_csrf'])) {
            $_SESSION['hr_csrf'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['hr_csrf'];
    }

    function hr_csrf_validate(?string $token): bool
    {
        return is_string($token) && isset($_SESSION['hr_csrf']) && hash_equals($_SESSION['hr_csrf'], $token);
    }

    function hr_is_admin(): bool
    {
        $code = $_SESSION['role_code'] ?? '';
        return in_array($code, ['SUPER_ADMIN', 'HOSPITAL_ADMIN'], true);
    }

    function hr_employee_id_for_user(mysqli $conn, int $userId): ?int
    {
        $st = $conn->prepare("SELECT employee_id FROM hr_employees WHERE user_id = ? AND employment_status != 'TERMINATED' LIMIT 1");
        $st->bind_param('i', $userId);
        $st->execute();
        $row = $st->get_result()->fetch_assoc();
        $st->close();
        return $row ? (int)$row['employee_id'] : null;
    }

    function hr_format_name(array $e): string
    {
        $parts = array_filter([$e['first_name'] ?? '', $e['other_names'] ?? '', $e['last_name'] ?? '']);
        return trim(implode(' ', $parts));
    }
}

require_once __DIR__ . '/hr_payroll.php';
