<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

class HrSalaryStructure extends Model
{
    protected static string $table = 'hr_salary_structures';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'code', 'name_ar', 'name_en', 'description', 'is_default', 'is_active',
    ];

    public static function allActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->orderBy('name_ar', 'ASC')
            ->get();
    }

    public static function getDefault(): ?array
    {
        return static::query()
            ->where('is_default', '=', 1)
            ->where('is_active', '=', 1)
            ->first();
    }

    public static function getComponents(int $structureId, bool $activeOnly = true): array
    {
        $db = App::getInstance()->db();
        $where = 'structure_id = ?';
        $params = [$structureId];
        if ($activeOnly) {
            $where .= ' AND is_active = 1';
        }
        return $db->select(
            "SELECT * FROM hr_salary_components WHERE {$where} ORDER BY sort_order ASC",
            $params
        );
    }

    public static function getEarningComponents(int $structureId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM hr_salary_components WHERE structure_id = ? AND type = 'earning' AND is_active = 1 ORDER BY sort_order ASC",
            [$structureId]
        );
    }

    public static function getDeductionComponents(int $structureId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM hr_salary_components WHERE structure_id = ? AND type = 'deduction' AND is_active = 1 ORDER BY sort_order ASC",
            [$structureId]
        );
    }
}
