<?php

namespace Bastion\Handlers;

use App\Services\SettingsService;
use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\QueryBuilder\Builder;
use Openguru\OpenCartFramework\QueryBuilder\JoinClause;
use Symfony\Component\HttpFoundation\JsonResponse;

class DictionariesHandler
{
    private Builder $queryBuilder;
    private SettingsService $settings;

    public function __construct(Builder $queryBuilder, SettingsService $settings)
    {
        $this->queryBuilder = $queryBuilder;
        $this->settings = $settings;
    }

    public function getCategories(Request $request): JsonResponse
    {
        $perPage = $request->get('perPage', 20);
        $categoryIds = $request->json('category_ids', []);
        $languageId = $this->settings->config()->getApp()->getLanguageId();

        $data = $this->queryBuilder->newQuery()
            ->select([
                'categories.category_id' => 'id',
                'categories.parent_id' => 'parent_id',
                'categories.image' => 'image',
                'descriptions.name' => 'name',
                'descriptions.description' => 'description',
            ])
            ->from(db_table('category'), 'categories')
            ->join(
                db_table('category_description') . ' AS descriptions',
                function (JoinClause $join) use ($languageId) {
                    $join->on('categories.category_id', '=', 'descriptions.category_id')
                        ->where('descriptions.language_id', '=', $languageId);
                }
            )
            ->where('categories.status', '=', 1)
            ->when($categoryIds, function (Builder $query) use ($categoryIds) {
                $query->whereIn('categories.category_id', $categoryIds);
            })
            ->orderBy('parent_id')
            ->orderBy('sort_order')
            ->limit($perPage)
            ->get();

        return new JsonResponse(compact('data'));
    }
}
