<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

use App\Traits\TagsTrait;
use App\Traits\PhotosTrait;
use App\Utilities\PageLink;

class TimetableContent extends Model
{
    use HasFactory;
    use TagsTrait;
    use PhotosTrait;

    protected $with = ['tag', 'photos'];

    protected $appends = ['url'];

    public function saveTimetableContent(array $input, int $id = null)
    {
        if ($id) {
            $timetable_content = TimetableContent::findOrFail($id);
        } else {
            $timetable_content = new TimetableContent();
        }

        $tag = Tag::findOrFail(Arr::get($input, 'tag.id'));

        $timetable_content->tag_id = $tag->id;
        $timetable_content->header = Arr::get($input, 'header');
        $timetable_content->body = Arr::get($input, 'body');
        $timetable_content->style = Arr::get($input, 'style');
        $timetable_content->link = Arr::get($input, 'link');
        $timetable_content->link_text = Arr::get($input, 'link_text');
        $timetable_content->inline = Arr::get($input, 'inline') ? true : false;

        $timetable_content->save();

        $timetable_content->savePhotos($input);
        $timetable_content->saveTags($input);

        cache()->tags([cache_name($timetable_content)])->flush();

        return $timetable_content;
    }

    public function tag()
    {
        return $this->belongsTo(Tag::class);
    }

    public function getUrlAttribute()
    {
        if ($this->link) {
            return PageLink::convertLink($this->link);
        } else {
            return null;
        }
    }
}
