<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

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

    protected static array $fillable = [
        'employee_id', 'period_id', 'payroll_run_id',
        'gross_taxable_monthly', 'annual_taxable_income',
        'personal_exemption', 'insurance_exemption',
        'net_taxable_income', 'annual_tax', 'monthly_tax',
        'ytd_tax', 'ytd_taxable_income', 'calculation_json', 'notes',
    ];

    public static function getForPeriod(int $periodId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT tr.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number
             FROM hr_tax_records tr
             JOIN hr_employee_profiles p ON p.employee_id = tr.employee_id
             WHERE tr.period_id = ?
             ORDER BY p.first_name_ar ASC",
            [$periodId]
        );
    }

    public static function getYtdForEmployee(int $employeeId, int $year): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT tr.*
             FROM hr_tax_records tr
             JOIN hr_payroll_periods pp ON pp.id = tr.period_id
             WHERE tr.employee_id = ? AND pp.year = ?
             ORDER BY pp.month DESC LIMIT 1",
            [$employeeId, $year]
        );
    }

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

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

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