<?php
namespace App\Repositories;

use Exception;
use App\Models\Categories;
use App\DTOs\Categories\CategoriesCreateDto;
use App\DTOs\Categories\CategoriesUpdateDto;
use App\Repositories\Interfaces\ICategoriesRepository;

class CategoriesRepository implements ICategoriesRepository
{
    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 = Categories::orderBy($orderBy, $orderDir);
            
            if (isset($request['search'])) {
                $search = $request['search'];
                $query = $query->where('code', 'like', '%'.$search.'%')
                               ->orWhere('name', 'like', '%'.$search.'%');
            }
            $categories_count = $query->count();
            $categories = $query->skip($start)->take($length);
            $categories = $categories->get();

        } else {
            $ct = Categories::query();
            $categories_count = $ct->count();
            $categories = $ct->get();
        }
        $respuesta['total'] = $categories_count;
        $respuesta['list'] = $categories;
        
        return $respuesta; 
    }

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

    public function store(CategoriesCreateDto $store): Categories
    {
        $entry = new Categories();

        $entry->code = $store->code;
        $entry->name = $store->name;
        $entry->image = $store->image;

        $entry->save();

        return $entry;
    }

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

        $entry->code = $store->code;
        $entry->name = $store->name;
        $entry->image = $store->image;

        $entry->save();
    }

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

}