<?php
namespace App\Repositories;

use Exception;
use App\Models\TypeMovement;
use App\DTOs\TypesMovement\TypeMovementCreateDto;
use App\DTOs\TypesMovement\TypeMovementUpdateDto;
use App\Repositories\Interfaces\ITypeMovementRepository;

class TypeMovementRepository implements ITypeMovementRepository
{
    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'];

            if (isset($request['search'])) {
                $search = $request['search'];
    
                return TypeMovement::orderBy($orderBy, $orderDir)
                    ->where('motive', 'like', '%'.$search.'%')
                    ->skip($start)
                    ->take($length)
                    ->get();
            } else {
                return TypeMovement::orderBy($orderBy, $orderDir)
                    ->skip($start)
                    ->take($length)
                    ->get();
            }            
        } else {
            return TypeMovement::get();
        }               
    }

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

    public function store(TypeMovementCreateDto $store): TypeMovement
    {
        $entry = new TypeMovement();

        $entry->code = $store->code;
        $entry->motive = $store->motive;
        $entry->alias = $store->alias;
        $entry->type = $store->type;
        $entry->purchase = $store->purchase;
        $entry->billable = $store->billable;
        $entry->code_sunat = $store->code_sunat;

        $entry->save();

        return $entry;
    }

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

        $entry->code = $store->code;
        $entry->motive = $store->motive;
        $entry->alias = $store->alias;
        $entry->type = $store->type;
        $entry->purchase = $store->purchase;
        $entry->billable = $store->billable;
        $entry->code_sunat = $store->code_sunat;

        $entry->save();
    }

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