<?php

namespace App\Services\Repositories;

use App\Models\TableNumber;
use App\Services\Interfaces\TableNumberRepositoryInterface;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TableNumberRepository implements TableNumberRepositoryInterface
{
    public function get(Request $request)
    {
        $query = TableNumber::query();

        if ($request->number) {
            $query->where('number', $request->number);
        }

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        if ($request->orderBy) {
            $query->orderBy('number',  $request->orderBy);
        }
        else
        {
            $query->orderBy('id', 'DESC');
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        if ($request->paginate ?? null) {
            $tables= $query->paginate(50);
        }else{
            $tables=$query->cursor();
        }

        return $tables;
    }


    public function checkItem($id)
    {
        $table = TableNumber::withTrashed()->where('foodics_id', $id)->first();
        return $table;
    }


    public function create($request)
    {
        $data = $request instanceof Request ?  $request->all() : (array) $request;
        unset($data['created_at']);
        unset($data['updated_at']);
        unset($data['deleted_at']);
        $data['number'] = $request->name;
        $data['body'] = json_encode($data);
        $data['foodics_id'] = $data['id'];
        TableNumber::create($data);

    }
    public function update($request,$id)
    {
        $table = TableNumber::withTrashed()->where('foodics_id', $id)->firstOrFail();
        $data = $request instanceof Request ?  $request->all() : (array) $request;
        unset($data['created_at']);
        unset($data['updated_at']);
        unset($data['deleted_at']);
        $data['number'] = $request->name;
        $data['body'] = json_encode($data);
        $data['foodics_id'] = $data['id'];
        $table->update($data);
    }
    public function delete(Request $request,$id)
    {
        $table = TableNumber::where('foodics_id', $id)->firstOrFail();
        $table->delete();
    }
    public function restore($request,$id)
    {
        $table = TableNumber::onlyTrashed()->where('foodics_id', $id)->firstOrFail();
        $table->restore();
    }
}
