<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_AdvanceSeoManager
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\AdvanceSeoManager\Block\RichSnippets;

class JsonLd extends \Webkul\AdvanceSeoManager\Block\Head
{

    /**
     * create jsonLd data
     *
     * @return string
     */
    public function getJsonLd()
    {
        try {
            $data = '';
            if ($this->getCurrentPage() == parent::PRODUCT_PAGE) {
                $product = $this->getProduct();
                $data = $this->jsonLdBuilder->build(parent::PRODUCT_PAGE, $product);
            } elseif ($this->getCurrentPage() == parent::CATEGORY_PAGE) {
                $category = $this->getCategory();
                $data = $this->jsonLdBuilder->build(parent::CATEGORY_PAGE, $category);
            } else {
                $data = $this->jsonLdBuilder->build(parent::CMS_PAGE, $this->_cms);
            }
            if ($this->validateJSonLd($data)) {
                return $data;
            }
            return '';
        } catch (\Exception $e) {
            //@TODO log exception
            return '';
        }
    }

    /**
     * validate json ld
     *
     * @param  mixed $jsonLd
     * @return string
     * @throws Exception
     */
    public function validateJSonLd($jsonLd)
    {
        if (is_string($jsonLd)) {
            return $jsonLd;
        }
        throw new \Magento\Framework\Exception\LocalizedException(__($this->jsonHelper->jsonEncode($jsonLd)));
    }
}
