<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\TimetableContentValidation;

use App\Models\TimetableContent;

class TimetableContentsController extends Controller
{
    protected function getModel()
    {
        return new TimetableContent();
    }

    public function load()
    {
        return response()->json([
            'timetable_contents' => TimetableContent::all(),
        ]);
    }

    public function manage()
    {
        if (!auth()->user()->can('manage', TimetableContent::class)) {
            return redirect('/')->with('error', 'You do not have access to manage Timetable Content');
        }
        return view('timetable-contents.index');
    }

    public function store(TimetableContentValidation $request, $id = null)
    {
        if ($id) {
            if (!auth()->user()->can('update', TimetableContent::find($id))) {
                return response()->json(['error' => 'You do not have permission to update that content'], 403);
            }
        }

        $timetable_content = (new TimetableContent())->saveTimetableContent(requestInput(), $id);
        $timetable_content->refresh();
        $timetable_content->load('tags', 'photos');

        return response()->json([
            'success' => $timetable_content->tag->name.' Saved',
            'timetable_content' => $timetable_content,
        ]);
    }
}
