<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

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

    protected static array $fillable = [
        'title_code', 'name_ar', 'name_en', 'grade_level', 'min_salary',
        'max_salary', 'description_ar', 'is_active', 'job_description_ar',
        'job_description_en',
    ];

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

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = 'is_archived = 0';
        $params = [];

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $where .= ' AND (name_ar LIKE ? OR name_en LIKE ? OR title_code LIKE ?)';
            $params[] = $search;
            $params[] = $search;
            $params[] = $search;
        }
        if (!empty($filters['grade_level'])) {
            $where .= ' AND grade_level = ?';
            $params[] = (int) $filters['grade_level'];
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM hr_job_titles WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT * FROM hr_job_titles WHERE {$where} ORDER BY grade_level ASC, name_ar ASC LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }
}
