<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Models;

use App\Core\Model;

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

    protected static array $fillable = [
        'code',
        'name_ar',
        'name_en',
        'warehouse_type',
        'location_ar',
        'keeper_employee_id',
        'capacity_units',
        'branch_id',
        'phone',
        'is_active',
        'notes',
    ];

    /**
     * Get all warehouse types with Arabic labels.
     */
    public static function getTypes(): array
    {
        return [
            'general'     => 'عام',
            'sports_shop' => 'محل رياضي',
            'cafeteria'   => 'كافيتريا',
            'gym'         => 'جيم',
            'medical'     => 'طبي',
            'maintenance' => 'صيانة',
        ];
    }

    /**
     * Get the Arabic label for a warehouse type.
     */
    public static function getTypeLabel(string $type): string
    {
        $types = self::getTypes();
        return $types[$type] ?? $type;
    }

    /**
     * Get all active warehouses ordered by name_ar.
     */
    public static function allActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->orderBy('name_ar', 'ASC')
            ->get();
    }

    /**
     * Search warehouses 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 ?)', [$search]);
        }

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

        if (isset($filters['is_active']) && $filters['is_active'] !== '') {
            $query = $query->where('is_active', '=', (int) $filters['is_active']);
        }

        $query = $query->orderBy('name_ar', 'ASC');

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