<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

class HrContract extends Model
{
    protected static string $table = 'hr_contracts';
    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', 'contract_number', 'contract_type',
        'start_date', 'end_date', 'probation_months',
        'working_hours_per_day', 'working_days_per_week',
        'notice_period_months', 'basic_salary', 'total_package',
        'terms_json', 'renewal_of_contract_id',
        'workflow_instance_id', 'signed_date',
        'signed_by_employee', 'signed_by_employer',
        'document_path', 'status', 'notes',
    ];

    public static function getContractTypes(): array
    {
        return [
            'definite'   => 'محدد المدة',
            'indefinite' => 'غير محدد المدة',
        ];
    }

    public static function getStatuses(): array
    {
        return [
            'draft'            => 'مسودة',
            'pending_approval' => 'في انتظار الاعتماد',
            'active'           => 'ساري',
            'renewed'          => 'تم التجديد',
            'expired'          => 'منتهي',
            'terminated'       => 'تم إنهاؤه',
        ];
    }

    public static function getActiveForEmployee(int $profileId): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM hr_contracts WHERE employee_profile_id = ? AND status = 'active' AND is_archived = 0 ORDER BY start_date DESC LIMIT 1",
            [$profileId]
        );
    }

    public static function getExpiringWithinDays(int $days): array
    {
        $db = App::getInstance()->db();
        $futureDate = date('Y-m-d', strtotime("+{$days} days"));
        return $db->select(
            "SELECT c.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number
             FROM hr_contracts c
             JOIN hr_employee_profiles p ON p.id = c.employee_profile_id
             WHERE c.status = 'active'
               AND c.contract_type = 'definite'
               AND c.end_date IS NOT NULL
               AND c.end_date <= ?
               AND c.end_date >= CURDATE()
               AND c.is_archived = 0
             ORDER BY c.end_date ASC",
            [$futureDate]
        );
    }

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

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $where .= ' AND (CONCAT(p.first_name_ar, \' \', p.last_name_ar) LIKE ? OR c.contract_number LIKE ?)';
            $params[] = $search;
            $params[] = $search;
        }
        if (!empty($filters['status'])) {
            $where .= ' AND c.status = ?';
            $params[] = $filters['status'];
        }
        if (!empty($filters['contract_type'])) {
            $where .= ' AND c.contract_type = ?';
            $params[] = $filters['contract_type'];
        }

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

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

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