<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

class HrLeaveRequest extends Model
{
    protected static string $table = 'hr_leave_requests';
    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', 'leave_type_id', 'start_date', 'end_date',
        'total_days', 'half_day', 'half_day_type', 'reason',
        'document_path', 'status', 'workflow_instance_id',
        'approved_by', 'approved_at', 'rejection_reason',
        'return_date', 'notes',
    ];

    public static function getStatuses(): array
    {
        return [
            'pending'    => 'في الانتظار',
            'approved'   => 'معتمد',
            'rejected'   => 'مرفوض',
            'cancelled'  => 'ملغى',
        ];
    }

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

        if (!empty($filters['employee_profile_id'])) {
            $where .= ' AND lr.employee_profile_id = ?';
            $params[] = (int) $filters['employee_profile_id'];
        }
        if (!empty($filters['leave_type_id'])) {
            $where .= ' AND lr.leave_type_id = ?';
            $params[] = (int) $filters['leave_type_id'];
        }
        if (!empty($filters['status'])) {
            $where .= ' AND lr.status = ?';
            $params[] = $filters['status'];
        }
        if (!empty($filters['date_from'])) {
            $where .= ' AND lr.start_date >= ?';
            $params[] = $filters['date_from'];
        }
        if (!empty($filters['date_to'])) {
            $where .= ' AND lr.end_date <= ?';
            $params[] = $filters['date_to'];
        }
        if (!empty($filters['department_id'])) {
            $where .= ' AND p.department_id = ?';
            $params[] = (int) $filters['department_id'];
        }

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

        $rows = $db->select(
            "SELECT lr.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number, lt.name_ar as leave_type_name, d.name_ar as department_name
             FROM hr_leave_requests lr
             JOIN hr_employee_profiles p ON p.id = lr.employee_profile_id
             JOIN hr_leave_types lt ON lt.id = lr.leave_type_id
             LEFT JOIN hr_departments d ON d.id = p.department_id
             WHERE {$where}
             ORDER BY lr.created_at DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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

    public static function getPendingForApproval(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT lr.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number, lt.name_ar as leave_type_name
             FROM hr_leave_requests lr
             JOIN hr_employee_profiles p ON p.id = lr.employee_profile_id
             JOIN hr_leave_types lt ON lt.id = lr.leave_type_id
             WHERE lr.status = 'pending' AND lr.is_archived = 0
             ORDER BY lr.created_at ASC"
        );
    }
}
