<?php
declare(strict_types=1);

namespace App\Modules\HR\Services;

use App\Core\App;
use App\Modules\HR\Models\HrPayrollRun;
use App\Modules\HR\Models\HrEmployeeProfile;

/**
 * Salary Slip Generation Service
 *
 * Generates HTML salary slips for printing/PDF.
 */
final class SalarySlipService
{
    public static function generateSlipData(int $runId): ?array
    {
        $db = App::getInstance()->db();

        $run = $db->selectOne("SELECT * FROM hr_payroll_runs WHERE id = ?", [$runId]);
        if (!$run) {
            return null;
        }

        $profile = HrEmployeeProfile::find((int) $run['employee_profile_id']);
        if (!$profile) {
            return null;
        }

        $period = $db->selectOne("SELECT * FROM hr_payroll_periods WHERE id = ?", [(int) $run['period_id']]);

        $components = HrPayrollRun::getComponentsLog($runId);

        $earnings = [];
        $deductions = [];
        foreach ($components as $comp) {
            if ($comp['type'] === 'earning') {
                $earnings[] = $comp;
            } else {
                $deductions[] = $comp;
            }
        }

        $department = null;
        if ($profile->department_id) {
            $department = $db->selectOne("SELECT name_ar FROM hr_departments WHERE id = ?", [(int) $profile->department_id]);
        }
        $jobTitle = null;
        if ($profile->job_title_id) {
            $jobTitle = $db->selectOne("SELECT name_ar FROM hr_job_titles WHERE id = ?", [(int) $profile->job_title_id]);
        }

        $monthNames = [
            1 => 'يناير', 2 => 'فبراير', 3 => 'مارس', 4 => 'أبريل',
            5 => 'مايو', 6 => 'يونيو', 7 => 'يوليو', 8 => 'أغسطس',
            9 => 'سبتمبر', 10 => 'أكتوبر', 11 => 'نوفمبر', 12 => 'ديسمبر',
        ];

        return [
            'run'            => $run,
            'profile'        => $profile->toArray(),
            'period'         => $period,
            'earnings'       => $earnings,
            'deductions'     => $deductions,
            'department'     => $department['name_ar'] ?? '-',
            'job_title'      => $jobTitle['name_ar'] ?? '-',
            'month_name'     => $monthNames[(int) $period['month']] ?? '',
            'year'           => $period['year'] ?? '',
        ];
    }
}
