<?php
namespace App\Repositories;

use Exception;
use App\Models\Brand;
use App\DTOs\Brands\BrandCreateDto;
use App\DTOs\Brands\BrandUpdateDto;
use App\Repositories\Interfaces\IBrandRepository;

class BrandRepository implements IBrandRepository
{
    public function paginate(array $request)
    {
        if ((isset($request['search'])) || (isset($request['orderby'])) || (isset($request['orderdir'])) || (isset($request['start'])) || (isset($request['length']))) {
            $orderBy = $request['orderby'];
            $orderDir = $request['orderdir'];
            $start = $request['start'];
            $length = $request['length'];
            $query = Brand::orderBy($orderBy, $orderDir);

            if (isset($request['search'])) {
                $search = $request['search'];
                $query = $query->where('code', 'like', '%'.$search.'%')
                               ->orWhere('brand', 'like', '%'.$search.'%');
            }
            $brands_count = $query->count();
            $brands = $query->skip($start)->take($length);
            $brands = $brands->get();
            
        } else {
            $br = Brand::query();
            $brands_count = $br->count();
            $brands = $br->get();
        }

        $respuesta['total'] = $brands_count;
        $respuesta['list'] = $brands;
        
        return $respuesta;
    }

    public function find(int $id): ?Brand
    {
        return Brand::find($id);
    }

    public function store(BrandCreateDto $store): Brand
    {
        $entry = new Brand();

        $entry->code = $store->code;
        $entry->brand = $store->brand;

        $entry->save();

        return $entry;
    }

    public function update(BrandUpdateDto $store): void
    {
        $entry = Brand::find($store->id);

        $entry->code = $store->code;
        $entry->brand = $store->brand;

        $entry->save();
    }

    public function destroy(int $id): void
    {
        Brand::destroy($id);
    }
}
