<?php

namespace Mtc\Plugins\NHS\Classes;

use Illuminate\Database\Eloquent\Model;

class NHSUnilexiconProduct extends Model
{
    protected $table = 'nhs_unilexicon_products';
    public $timestamps = false;

    protected $fillable = [
        'id',
        'invalid',
        'gtin',
        'tariffs',
        'price',
        'name',
        'short',
        'supplier',
        'mtc__display_name',
        'number_of_charges',
    ];


    public function scopeUnique($query)
    {
        return $query->groupBy('mtc__display_name');
    }


    public function scopeValid($query)
    {
        return $query->where('invalid', '!=', '1');
    }


    public static function searchByTerm(String $term, $limit = 10)
    {
        $results = self::unique()
            ->valid()
            ->where('mtc__display_name', 'LIKE', "%{$term}%")
            ->limit($limit)
            ->orderBy('mtc__display_name')
        ;

        return $results->pluck('mtc__display_name');
    }


    public static function getIdFromName(String $name)
    {
        $unilexicon_id = '0';

        $product = self::unique()
            ->where('mtc__display_name', $name)
            ->where('invalid', '!=', '1')
            ->first()
        ;

        if ($product) {
            $unilexicon_id = $product->id;
        }

        // It's a BIGINT.
        // Using current setup the number gets truncated if not casted to string.
        return (string)$unilexicon_id;
    }
}

