<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

class HrInsuranceRecord extends Model
{
    protected static string $table = 'hr_insurance_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_profile_id', 'period_id', 'payroll_run_id',
        'basic_insurable_salary', 'variable_insurable_salary',
        'employee_basic_share', 'employee_variable_share', 'total_employee_share',
        'employer_basic_share', 'employer_variable_share', 'total_employer_share',
        'total_contribution', 'insurance_number', 'notes',
    ];

    public static function getForPeriod(int $periodId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT ir.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number, p.insurance_number
             FROM hr_insurance_records ir
             JOIN hr_employee_profiles p ON p.id = ir.employee_profile_id
             WHERE ir.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 = 'ir.employee_profile_id = ?';
        $params = [$profileId];

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

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

    public static function getPeriodTotals(int $periodId): array
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT
                COUNT(*) as employee_count,
                COALESCE(SUM(total_employee_share), 0) as total_employee_share,
                COALESCE(SUM(total_employer_share), 0) as total_employer_share,
                COALESCE(SUM(total_contribution), 0) as grand_total
             FROM hr_insurance_records WHERE period_id = ?",
            [$periodId]
        );
        return $row ?: [];
    }
}
