<?php
namespace App\Repositories;

use Exception;
use App\Models\PaymentMethod;
use App\DTOs\PaymentMethods\PaymentMethodCreateDto;
use App\DTOs\PaymentMethods\PaymentMethodUpdateDto;
use App\Repositories\Interfaces\IPaymentMethodRepository;

class PaymentMethodRepository implements IPaymentMethodRepository
{
    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 PaymentMethod::orderBy($orderBy, $orderDir)
                    ->where('ruc_number', '=', $request['ruc_number'])
                    ->where('description', 'like', '%'.$search.'%')
                    ->skip($start)
                    ->take($length)
                    ->get();
            } else {
                return PaymentMethod::orderBy($orderBy, $orderDir)
                    ->where('ruc_number', '=', $request['ruc_number'])
                    ->skip($start)
                    ->take($length)
                    ->get();
            }            
        } else {
            return PaymentMethod::where('ruc_number', '=', $request['ruc_number'])->get();
        }               
    }

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

    public function store(PaymentMethodCreateDto $store): PaymentMethod
    {
        $entry = new PaymentMethod();

        $entry->ruc_number = $store->ruc_number;
        $entry->code = $store->code;
        $entry->description = $store->description;
        $entry->type = $store->type;
        $entry->days = $store->days;

        $entry->save();

        return $entry;
    }

    public function update(PaymentMethodUpdateDto $store): void
    {
        $entry = PaymentMethod::where('ruc_number', '=', $store->ruc_number)->find($store->id);
        if( is_null($entry) ){
            throw new \Exception("No existe la forma de pago relacionada al RUC");
        }

        $entry->ruc_number = $store->ruc_number;
        $entry->code = $store->code;
        $entry->description = $store->description;
        $entry->type = $store->type;
        $entry->days = $store->days;

        $entry->save();
    }

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