<?php

namespace App\Repositories;

use Illuminate\Support\Facades\Storage;

abstract class Repository
{
    protected $model;

    /**
     * Display specified resource.
     *
     * @param varchar $with
     * @param uuid    $id
     *
     * @return \Illuminate\Http\Response
     */
    public function findId($id = null, $with = null)
    {
        return $this->model
            ->when($with, function ($query) use ($with) {
                return $query->with($with);
            })
            ->when($id, function ($query) use ($id) {
                return $query->where('id', $id);
            })
            ->first();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store($request, $owner = 1)
    {
        if ($owner == 1) {
            $request['userid_created'] = auth()->user()->id;
        }

        return $this->model->create($request);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param Model                    $model
     *
     * @return \Illuminate\Http\Response
     */
    public function update($request, $model, $owner = 1)
    {
        if ($owner == 1) {
            $request['userid_updated'] = auth()->user()->id;
        }

        return $model->update($request);
    }

    /**
     * Show the specified resource in storage.
     *
     * @param uuid $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return $this->model->where('user_id', $id)->first();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Model $model
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($model)
    {
        return $model->delete();
    }

    /**
     * Upload the specified resource from storage.
     *
     * @param $name
     * @param Request $request
     * @param $tipe
     *
     * @return \Illuminate\Http\Response
     */
    public function upload($name, $request, $tipe)
    {
        $file = $request->file($tipe);
        Storage::disk('static')->put('simia/uploads/'.$tipe.'/'.$name, file_get_contents($file->getRealPath()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Model $model
     * @param $tipe
     *
     * @return \Illuminate\Http\Response
     */
    public function deletefile($model, $tipe)
    {
        if ($model->$tipe) {
            Storage::disk('static')->delete('simia/uploads/'.$tipe.'/'.$model->$tipe);
        }
    }
}
