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

use Feegleweb\Octoshop\Models\Product;
use Illuminate\Database\Eloquent\Collection;
use OFFLINE\SiteSearch\Classes\Result;
use OFFLINE\SiteSearch\Models\Settings;

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

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

            $result        = new Result($this->query, $relevance);
            $result->title = $product->title;
            $result->text  = $product->intro;
            $result->url   = $this->getUrl($product);
            $result->thumb = $this->getThumb($product->images);
            $result->model = $product;

            $this->addResult($result);
        }

        return $this;
    }

    /**
     * Get all products with matching title or content.
     *
     * @return Collection
     */
    protected function products()
    {
        return Product::enabled()->withImages()
                      ->where('title', 'like', "%{$this->query}%")
                      ->orWhere('description', 'like', "%{$this->query}%")
                      ->orderBy('updated_at', 'desc')
                      ->get();
    }

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

    /**
     * Generates the url to a shop product.
     *
     * @param $product
     *
     * @return string
     */
    protected function getUrl($product)
    {
        $url = trim(Settings::get('octoshop_products_itemurl', '/product'), '/');

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

    /**
     * Display name for this provider.
     *
     * @return mixed
     */
    public function displayName()
    {
        return Settings::get(
            'octoshop_products_label',
            trans('offline.sitesearch::lang.settings.octoshop_itemurl_badge')
        );
    }

    /**
     * Returns the plugin's identifier string.
     *
     * @return string
     */
    public function identifier()
    {
        return 'Feegleweb.Octoshop';
    }

}
