<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

use App\Core\Model;
use App\Core\App;
use App\Core\Pagination;

class HrPayrollRun extends Model
{
    protected static string $table = 'hr_payroll_runs';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'period_id', 'employee_profile_id', 'basic_salary', 'gross_earnings',
        'total_allowances', 'overtime_amount', 'total_deductions',
        'insurance_employee', 'insurance_employer', 'tax_amount',
        'loan_deduction', 'penalty_deduction', 'absence_deduction',
        'other_deductions', 'net_salary',
        'working_days', 'present_days', 'absent_days', 'overtime_hours',
        'payment_method', 'payment_reference', 'paid_at',
        'calculation_json', 'status', 'notes',
    ];

    public static function getForPeriod(int $periodId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pr.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number, d.name_ar as department_name
             FROM hr_payroll_runs pr
             JOIN hr_employee_profiles p ON p.id = pr.employee_profile_id
             LEFT JOIN hr_departments d ON d.id = p.department_id
             WHERE pr.period_id = ?
             ORDER BY p.first_name_ar ASC",
            [$periodId]
        );
    }

    public static function getForEmployee(int $profileId, ?int $year = null): array
    {
        $db = App::getInstance()->db();
        $where = 'pr.employee_profile_id = ?';
        $params = [$profileId];

        if ($year) {
            $where .= ' AND pp.year = ?';
            $params[] = $year;
        }

        return $db->select(
            "SELECT pr.*, pp.year, pp.month, pp.period_code
             FROM hr_payroll_runs pr
             JOIN hr_payroll_periods pp ON pp.id = pr.period_id
             WHERE {$where}
             ORDER BY pp.year DESC, pp.month DESC",
            $params
        );
    }

    public static function getComponentsLog(int $runId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT *, name_ar as component_name FROM hr_payroll_components_log WHERE payroll_run_id = ? ORDER BY sort_order ASC",
            [$runId]
        );
    }
}
