<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

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

    protected static array $fillable = [
        'employee_profile_id', 'termination_type', 'request_date', 'effective_date',
        'last_working_day', 'notice_period_start', 'notice_period_end',
        'notice_period_served', 'notice_period_compensation',
        'years_of_service', 'last_basic_salary', 'last_total_salary',
        'severance_first_5y', 'severance_after_5y', 'total_severance',
        'remaining_leave_days', 'leave_compensation', 'total_entitlement',
        'deductions_json', 'total_deductions', 'net_settlement',
        'status', 'workflow_instance_id',
        'approved_by', 'approved_at', 'paid_date',
        'calculation_json', 'notes',
    ];

    public static function getTerminationTypes(): array
    {
        return [
            'resignation'       => 'استقالة',
            'termination'       => 'فصل',
            'end_of_contract'   => 'انتهاء عقد',
            'retirement'        => 'تقاعد',
            'death'             => 'وفاة',
            'disability'        => 'عجز',
            'mutual_agreement'  => 'اتفاق مشترك',
        ];
    }

    public static function getStatuses(): array
    {
        return [
            'draft'            => 'مسودة',
            'calculated'       => 'تم الحساب',
            'pending_approval' => 'في انتظار الاعتماد',
            'approved'         => 'معتمد',
            'paid'             => 'تم الصرف',
            'cancelled'        => 'ملغى',
        ];
    }

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

        if (!empty($filters['status'])) {
            $where .= ' AND eos.status = ?';
            $params[] = $filters['status'];
        }
        if (!empty($filters['type'])) {
            $where .= ' AND eos.termination_type = ?';
            $params[] = $filters['type'];
        }
        if (!empty($filters['q'])) {
            $where .= ' AND (p.first_name_ar LIKE ? OR p.last_name_ar LIKE ? OR p.employee_number LIKE ?)';
            $term = '%' . $filters['q'] . '%';
            $params[] = $term;
            $params[] = $term;
            $params[] = $term;
        }

        $countRow = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM hr_end_of_service eos
             JOIN hr_employee_profiles p ON p.id = eos.employee_profile_id WHERE {$where}",
            $params
        );
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT eos.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number
             FROM hr_end_of_service eos
             JOIN hr_employee_profiles p ON p.id = eos.employee_profile_id
             WHERE {$where}
             ORDER BY eos.request_date DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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