<?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 generateCycleCode(): string
    {
        $db = App::getInstance()->db();
        $year = date('Y');
        $prefix = 'PC-' . $year . '-';

        $last = $db->selectOne(
            "SELECT cycle_code FROM hr_performance_cycles WHERE cycle_code LIKE ? ORDER BY id DESC LIMIT 1",
            [$prefix . '%']
        );
        if ($last) {
            $parts = explode('-', $last['cycle_code']);
            $seq = (int) end($parts) + 1;
        } else {
            $seq = 1;
        }

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

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

        $last = $db->selectOne(
            "SELECT loan_number FROM hr_employee_loans WHERE loan_number LIKE ? ORDER BY id DESC LIMIT 1",
            [$prefix . '%']
        );
        if ($last) {
            $parts = explode('-', $last['loan_number']);
            $seq = (int) end($parts) + 1;
        } else {
            $seq = 1;
        }

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