<?php
namespace App\Repositories;

use Exception;
use App\Models\Warehouse;
use App\DTOs\Warehouses\WarehouseCreateDto;
use App\DTOs\Warehouses\WarehouseUpdateDto;
use App\Repositories\Interfaces\IWarehouseRepository;

class WarehouseRepository implements IWarehouseRepository
{
    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 Warehouse::orderBy($orderBy, $orderDir)
                    ->where('warehouse', 'like', '%'.$search.'%')
                    ->skip($start)
                    ->take($length)
                    ->get();
            } else {
                return Warehouse::orderBy($orderBy, $orderDir)
                    ->skip($start)
                    ->take($length)
                    ->get();
            }            
        } else {
            return Warehouse::get();
        }               
    }

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

    public function store(WarehouseCreateDto $store): Warehouse
    {
        $entry = new Warehouse();

        $entry->code = $store->code;
        $entry->warehouse = $store->warehouse;
        $entry->address = $store->address;
        $entry->location = $store->location;
        $entry->external_guide_serie = $store->external_guide_serie;
        $entry->external_guide_number = $store->external_guide_number;
        $entry->internal_guide_serie = $store->internal_guide_serie;
        $entry->internal_guide_number = $store->internal_guide_number;

        $entry->save();

        return $entry;
    }

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

        $entry->code = $store->code;
        $entry->warehouse = $store->warehouse;
        $entry->address = $store->address;
        $entry->location = $store->location;
        $entry->external_guide_serie = $store->external_guide_serie;
        $entry->external_guide_number = $store->external_guide_number;
        $entry->internal_guide_serie = $store->internal_guide_serie;
        $entry->internal_guide_number = $store->internal_guide_number;

        $entry->save();
    }

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