<?php
namespace App\Repositories;

use Exception;
use App\Models\Model;
use App\DTOs\Models\ModelCreateDto;
use App\DTOs\Models\ModelUpdateDto;
use App\Repositories\Interfaces\IModelRepository;

class ModelRepository implements IModelRepository
{
    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 = Model::with('brand')->orderBy($orderBy, $orderDir);

            if (isset($request['search'])) {
                $search = $request['search'];
                $query = $query->where('code', 'like', '%'.$search.'%')
                               ->orWhere('model', 'like', '%'.$search.'%'); 
            }
            $models_count = $query->count();
            $models = $query->skip($start)->take($length);
            $models = $models->get();

        } else {
            $mo = Model::with('brand');
            $models_count = $mo->count();
            $models = $mo->get();
        }

        $respuesta['total'] = $models_count;
        $respuesta['list'] = $models;
        
        return $respuesta;
    }

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

    public function store(ModelCreateDto $store): Model
    {
        $entry = new Model();

        $entry->id_brand = $store->id_brand;
        $entry->code = $store->code;
        $entry->model = $store->model;

        $entry->save();

        return $entry;
    }

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

        $entry->id_brand = $store->id_brand;
        $entry->code = $store->code;
        $entry->model = $store->model;

        $entry->save();
    }

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