<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

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

    protected static array $fillable = [
        'cycle_code', 'name_ar', 'name_en', 'year', 'period_type',
        'start_date', 'end_date', 'review_deadline', 'status',
    ];

    public static function getPeriodTypes(): array
    {
        return [
            'annual'       => 'سنوي',
            'semi_annual'  => 'نصف سنوي',
            'quarterly'    => 'ربع سنوي',
        ];
    }

    public static function getStatuses(): array
    {
        return [
            'draft'  => 'مسودة',
            'active' => 'نشط',
            'review' => 'تحت المراجعة',
            'closed' => 'مغلق',
        ];
    }

    public static function getActiveCycle(): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM hr_performance_cycles WHERE status IN ('active','review') ORDER BY year DESC LIMIT 1"
        );
    }

    public static function getReviewsForCycle(int $cycleId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pr.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number, d.name_ar as department_name,
                    CONCAT(rev.first_name_ar, ' ', rev.last_name_ar) as reviewer_name
             FROM hr_performance_reviews pr
             JOIN hr_employee_profiles p ON p.id = pr.employee_profile_id
             LEFT JOIN hr_departments d ON d.id = p.department_id
             LEFT JOIN hr_employee_profiles rev ON rev.employee_id = pr.reviewer_id
             WHERE pr.cycle_id = ?
             ORDER BY p.first_name_ar ASC",
            [$cycleId]
        );
    }
}
