<?php

namespace App\Http\Controllers\Traits;

use App\Models\VideoIntext;
use App\Models\VideoIntext as Video;
use Illuminate\Http\Request;
use App\Http\Resources\JsonResource;
use App\Http\Resources\VideoInText as VideoResource;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Carbon;

trait VideoIntextTrait
{
    /**
     * This ajax method returns records from 'video_intext' table
     *
     * @return JSON
     */
    public function getVideoIntexts()
    {
        //Napraviti logiku dovlacenja svih video kodova
        return VideoResource::collection(Video::all());
    }

    /**
     * This ajax method returns filtered record from 'video_intext' table
     *
     * @return JSON
     */
    public function getOneVideoIntext(Request $request)
    {
        //Napraviti logiku dovlacenja jednog video koda ciji je id prosledjen kroz request
        $video =  Video::findOrFail($request->entityId);

        if(!$video){
            return JsonResource::make()->withError('Greska prilikom citanja iz baze');
        }

        return new VideoResource($video);


    }

    /**
     * This ajax method create new record in 'video_intext' table
     *
     * @return JSON
     */
    public function saveVideoIntext(Request $request)
    {
        //Napraviti logiku suvanja jednog video koda dospelog iz requesta i vracanja tog koda nazad
        $data = $request->validate([
            'code' => 'required'
        ]);
        $data['created_at'] = Carbon::now();
        $data['updated_at'] = Carbon::now();
        $data['created_by'] = auth()->user()->id;
        $data['updated_by'] = auth()->user()->id;

        $video = new Video($data);
        $video->save();
        return JsonResource::make(['entityId' => $video->id])->withSuccess("Uspesno dodat Video");
    }

    /**
     * This ajax method update record in 'video_intext' table
     *
     * @return JSON
     */
    public function updateVideoIntext(Request $request)
    {

        $video =  Video::findOrFail($request['entityId']);

        //Napraviti logiku update-a jednog video koda dospelog iz requesta i vracanja tog koda nazad
        $data = $request->validate([
            'code' => 'required'
        ]);
        $data['updated_at'] = Carbon::now();
        $data['updated_by'] = auth()->user()->id;
        unset($data['entityId']);
        $video->update($data);
        return JsonResource::make(['entityId' => $video->id])->withSuccess("Uspesno dodat Video");
    }
}