<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Manufacturer;
use App\Http\Resources\ManufacturerResource;

class ManufacturerController extends Controller
{
    const ITEM_PER_PAGE = 25;

    public function index(Request $request)
    {
        $searchParams = $request->all();
        $limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
        $keyword = Arr::get($searchParams, 'keyword', '');
        $status = Arr::get($searchParams, 'status', '');

        $list = Manufacturer::select('id', 'name', 'slug', 'image')
            ->isPublished();

        if (!empty($keyword)) {
            $list->where('name', 'LIKE', '%' . $keyword . '%');
        }

        if ($status != '') {
            $list->where('is_activated', $status);
        }

        $list->orderBy('position', 'ASC')
            ->orderBy('id', 'DESC');

        return ManufacturerResource::collection($list->paginate($limit));
    }

    public function top()
    {
        $list = Manufacturer::select('id', 'name', 'slug', 'image')
            ->isPublished()
            ->orderBy('position')
            ->orderBy('id', 'DESC')
            ->paginate(self::ITEM_PER_PAGE);

        return ManufacturerResource::collection($list);
    }

    public function show($id = '')
    {
        $manufacturer = Manufacturer::select('*')
            ->isPublished()
            ->where('id', $id)
            ->first();

        return new ManufacturerResource($manufacturer);
    }
}
