<?php
/**
 * Class ItemFAQ
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */

namespace Mtc\Plugins\ItemFAQ\Classes;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use Mtc\Shop\Category;
use Mtc\Shop\Item;

/**
 * Class SchemaItem
 *
 * Seo Schema Item model
 * Used to store seo schema graph fields and values
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
class ItemFAQ extends Model
{
    use Item\BelongsToItem;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'items_faq';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'item_id',
        'category_id',
        'question',
        'answer',
        'order',
    ];

    /**
     * Boot the model
     */
    public static function boot() : void
    {
        parent::boot();

        self::saving(function ($entry) {
            $max = self::query()
                    ->where($entry->item_id ? 'item_id' : 'category_id', $entry->item_id ?? $entry->category_id)
                    ->max('order') ?? 0;
            $entry->order = $max + 1;
        });
    }

    /**
     * Add tabNav item to item navigation in admin page
     *
     * @access public
     * @static
     * @param Item $item Currently opened item
     * @param array $request $_REQUEST
     * @return string $nav_item html code for navigation item
     */
    public static function addTabNav(\Item $item, array $request)
    {
        $twig = App::make('twig');

        $nav_item = $twig->render('ItemFAQ/admin/tabnav.twig', [
            'item' => $item,
            'request' => $request,
            'request_uri' => $_SERVER['REQUEST_URI']
        ]);

        return $nav_item;
    }

    public static function updateCache($faq_object)
    {
        $is_category = $faq_object instanceof Category;
        if ($faq_object instanceof \Item && $faq_object->use_category_faq) {
            $cache = '';
        } else {
            $faqs = ItemFAQ::query()
                ->where($is_category ? 'category_id' : 'item_id', $faq_object->id)
                ->orderBy('order')
                ->get()
                ->map(function (self $faq) use ($faq_object) {
                    return $faq->buildCache($faq_object);
                })->toArray();

            $cache = '<script type="application/ld+json">'
                . json_encode(
                    [
                        '@context' => 'https://schema.org/',
                        '@type' => 'FAQPage',
                        '@graph' => $faqs,
                    ]
                    , JSON_UNESCAPED_SLASHES)
                . '</script>';
        }

        $model = $faq_object instanceof \Item ? new Item() : new Category();
        $model::query()
            ->where('id', $faq_object->id)
            ->update([
                'faq_cache' => $cache
            ]);
    }

    /**
     * Build up the item json schema for the question
     *
     * @param $faq_object
     * @return array
     */
    public function buildCache($faq_object)
    {
        $url = $faq_object->url;

        return [
            '@context' => 'https://schema.org',
            '@type' => 'Question',
            'about' => [
                'id' => $url
            ],
            'text' => $this->question,
            'acceptedAnswer' => [
                '@type' => 'Answer',
                'text' => $this->answer,
                'author' => [
                    '@id' => SITE_URL
                ]
            ]
        ];

    }
}
