<?php
namespace App\Repositories;

use Exception;
use App\Models\UnitMeasure;
use Illuminate\Pagination\Paginator;
use App\DTOs\UnitMeasure\UnitMeasureCreateDto;
use App\DTOs\UnitMeasure\UnitMeasureUpdateDto;
use App\Repositories\Interfaces\IUnitMeasureRepository;

class UnitMeasureRepository implements IUnitMeasureRepository
{
    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 = UnitMeasure::orderBy($orderBy, $orderDir);

            if (isset($request['search'])) {
                $search = $request['search'];
                $query = $query->where('code', 'like', '%'.$search.'%')
                    ->orWhere('description', 'like', '%'.$search.'%')
                    ->orWhere('code_sunat', 'like', '%'.$search.'%')
                    ->orWhere('description_fe', 'like', '%'.$search.'%');
            }
            $measureunits_count = $query->count();
            $measureunits = $query->skip($start)->take($length);
            $measureunits = $measureunits->get();

        } else {
            $um = UnitMeasure::query();
            $measureunits_count = $um->count();
            $measureunits = $um->get();
        }
        
        $respuesta['total'] = $measureunits_count;
        $respuesta['list'] = $measureunits;
        
        return $respuesta;
    }

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

    public function store(UnitMeasureCreateDto $store): UnitMeasure
    {
        $entry = new UnitMeasure();

        $entry->code = $store->code;
        $entry->description = $store->description;
        $entry->code_sunat = $store->code_sunat;
        $entry->description_fe = $store->description_fe;
        
        $entry->save();

        return $entry;
    }

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

        $entry->code = $store->code;
        $entry->description = $store->description;
        $entry->code_sunat = $store->code_sunat;
        $entry->description_fe = $store->description_fe;

        $entry->save();
    }

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