<?php
namespace OFFLINE\SiteSearch\Classes\Providers;

use Responsiv\Showcase\Models\Item;
use Illuminate\Database\Eloquent\Collection;
use OFFLINE\SiteSearch\Classes\Result;
use OFFLINE\SiteSearch\Models\Settings;

/**
 * Searches the contents generated by the
 * Responsiv.Showcase plugin
 *
 * @package OFFLINE\SiteSearch\Classes\Providers
 */
class ResponsivShowcaseResultsProvider extends ResultsProvider
{
    /**
     * Runs the search for this provider.
     *
     * @return ResultsProvider
     */
    public function search()
    {
        if ( ! $this->isInstalledAndEnabled()) {
            return $this;
        }

        foreach ($this->items() as $item) {
            // Make this result more relevant, if the query is found in the title
            $relevance = mb_stripos($item->title, $this->query) === false ? 1 : 2;

            $result        = new Result($this->query, $relevance);
            $result->title = $item->title;
            $result->text  = $item->description;
            $result->url   = $this->getUrl($item);
            $result->model = $item;

            $this->addResult($result);
        }

        return $this;
    }

    /**
     * Get all posts with matching title or content.
     *
     * @return Collection
     */
    protected function items()
    {
        return Item::where('title', 'like', "%{$this->query}%")
                   ->orWhere('description', 'like', "%{$this->query}%")
                   ->orWhere('content', 'like', "%{$this->query}%")
                   ->get();
    }

    /**
     * Checks if the Responsiv.Showcase Plugin is installed and
     * enabled in the config.
     *
     * @return bool
     */
    protected function isInstalledAndEnabled()
    {
        return $this->isPluginAvailable($this->identifier)
        && Settings::get('responsiv_showcase_enabled', true);
    }

    /**
     * Generates the url to a blog post.
     *
     * @param $post
     *
     * @return string
     */
    protected function getUrl($post)
    {
        $url        = trim(Settings::get('responsiv_showcase_url', '/showcase/project'), '/');
        $langPrefix = $this->translator ? $this->translator->getLocale() : '';

        return implode('/', [$langPrefix, $url, $post->slug]);
    }

    /**
     * Display name for this provider.
     *
     * @return mixed
     */
    public function displayName()
    {
        return Settings::get('responsiv_showcase_label', 'Showcase');
    }

    /**
     * Return the plugin's identifier string.
     *
     * @return string
     */
    public function identifier()
    {
        return 'Responsiv.Showcase';
    }
}
