<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Models;

use App\Core\Model;

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

    protected static array $fillable = [
        'parent_id',
        'code',
        'name_ar',
        'name_en',
        'description_ar',
        'sort_order',
        'is_active',
    ];

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

    /**
     * Get root categories (where parent_id IS NULL).
     */
    public static function getRoots(): array
    {
        return static::query()
            ->whereRaw('`parent_id` IS NULL')
            ->orderBy('sort_order', 'ASC')
            ->orderBy('name_ar', 'ASC')
            ->get();
    }

    /**
     * Get children of a given parent category.
     */
    public static function getChildren(int $parentId): array
    {
        return static::query()
            ->where('parent_id', '=', $parentId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('name_ar', 'ASC')
            ->get();
    }

    /**
     * Get full category tree (roots with nested 'children' key).
     */
    public static function getTree(): array
    {
        $all = static::query()
            ->orderBy('sort_order', 'ASC')
            ->orderBy('name_ar', 'ASC')
            ->get();

        $grouped = [];
        foreach ($all as $cat) {
            $parentId = $cat['parent_id'] ?? null;
            $grouped[$parentId ?? 0][] = $cat;
        }

        $roots = $grouped[0] ?? [];
        foreach ($roots as &$root) {
            $root['children'] = $grouped[$root['id']] ?? [];
        }

        return $roots;
    }

    /**
     * Search categories 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['parent_id'])) {
            $query = $query->where('parent_id', '=', (int) $filters['parent_id']);
        }

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

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