<?php
declare(strict_types=1);

namespace App\Modules\HR\Services;

use App\Core\App;

/**
 * HR Number Sequence Generator
 *
 * Generates unique sequential numbers for:
 *   - Employee numbers (EMP-YYYY-NNNNN)
 *   - Contract numbers (CTR-YYYY-NNNNN)
 *   - Payroll period codes (PAY-YYYY-MM)
 */
final class HrNumberGenerator
{
    public static function generateEmployeeNumber(): string
    {
        $db = App::getInstance()->db();
        $year = date('Y');
        $prefix = 'EMP-' . $year . '-';

        $last = $db->selectOne(
            "SELECT employee_number FROM hr_employee_profiles WHERE employee_number LIKE ? ORDER BY id DESC LIMIT 1",
            [$prefix . '%']
        );

        if ($last) {
            $parts = explode('-', $last['employee_number']);
            $seq = (int) end($parts) + 1;
        } else {
            $seq = 1;
        }

        return $prefix . str_pad((string) $seq, 5, '0', STR_PAD_LEFT);
    }

    public static function generateContractNumber(): string
    {
        return ContractService::generateContractNumber();
    }

    public static function generatePeriodCode(int $year, int $month): string
    {
        return sprintf('PAY-%04d-%02d', $year, $month);
    }

    public static function generateLoanReference(): string
    {
        $db = App::getInstance()->db();
        $year = date('Y');
        $prefix = 'LN-' . $year . '-';

        $last = $db->selectOne(
            "SELECT id FROM hr_employee_loans ORDER BY id DESC LIMIT 1"
        );
        $seq = ($last ? (int) $last['id'] : 0) + 1;

        return $prefix . str_pad((string) $seq, 5, '0', STR_PAD_LEFT);
    }
}
