<?php
declare(strict_types=1);

namespace App\Modules\Rentals\Models;

use App\Core\Model;

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

    protected static array $fillable = [
        'entity_type',
        'name_ar',
        'name_en',
        'contact_person',
        'contact_phone',
        'contact_email',
        'address',
        'tax_number',
        'official_letter_received',
        'board_approved',
        'approval_date',
        'status',
        'notes',
    ];

    /**
     * Get all entity types with Arabic labels.
     */
    public static function getEntityTypes(): array
    {
        return [
            'school'     => 'مدرسة',
            'university' => 'جامعة',
            'embassy'    => 'سفارة',
            'federation' => 'اتحاد',
            'private'    => 'خاص',
            'corporate'  => 'شركة',
        ];
    }

    /**
     * Get all statuses with Arabic labels.
     */
    public static function getStatuses(): array
    {
        return [
            'pending'     => 'قيد المراجعة',
            'approved'    => 'مُعتمد',
            'active'      => 'فعال',
            'suspended'   => 'موقوف',
            'blacklisted' => 'محظور',
        ];
    }

    /**
     * Get the Arabic label for a status key.
     */
    public static function getStatusLabel(string $status): string
    {
        $statuses = self::getStatuses();
        return $statuses[$status] ?? $status;
    }

    /**
     * Get the badge color for a status.
     */
    public static function getStatusColor(string $status): string
    {
        $colors = [
            'pending'     => '#D97706',
            'approved'    => '#7C3AED',
            'active'      => '#059669',
            'suspended'   => '#DC2626',
            'blacklisted' => '#991B1B',
        ];
        return $colors[$status] ?? '#6B7280';
    }

    /**
     * Search rental entities with filters and pagination.
     */
    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $query = static::query();

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $query = $query->whereRaw(
                '(`name_ar` LIKE ? OR `name_en` LIKE ? OR `contact_person` LIKE ? OR `contact_phone` LIKE ?)',
                [$search, $search, $search, $search]
            );
        }

        if (!empty($filters['entity_type'])) {
            $query = $query->where('entity_type', '=', $filters['entity_type']);
        }

        if (!empty($filters['status'])) {
            $query = $query->where('status', '=', $filters['status']);
        }

        $query = $query->orderBy('created_at', 'DESC');

        return $query->paginate($perPage, $page);
    }
}
