<?php

namespace Mtc\Shop;

use Illuminate\Database\Eloquent\Model;

/**
 * @author Uldis Zvirbulis <uldis.zvirbulis@mtcmedia.co.uk>
 */
class Warning extends Model
{
    protected $fillable = [
        'content',
        'warning_type',
    ];

    public static $warning_types = [
        1 => 'info',
        2 => 'warning',
        3 => 'danger',
    ];

    /**
     * Define the relationship to Item
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function items()
    {
        return $this->belongsToMany(Item::class, 'warning_items');
    }

    public static function importWarnings($text)
    {
        if (empty(trim($text))) {
            return [];
        }
        $start = '[alert type="';
        $end = '"]';
        $delimiter = '#';
        $regex = $delimiter.preg_quote($start, $delimiter).'(.*?)'.preg_quote($end, $delimiter).$delimiter.'s';
        preg_match_all($regex, $text, $matches);
        if (empty($matches[1])) {
            return false;
        }
        $warning_types = [];
        foreach ($matches[1] as $key => $match) {
            $warning_type = $match;
            $start = $matches[0][$key];
            $end = '[/alert]';
            $delimiter = '#';
            $regex = $delimiter.preg_quote($start, $delimiter).'(.*?)'.preg_quote($end, $delimiter).$delimiter.'s';
            preg_match($regex, $text, $content_match);
            $content = trim($content_match[1]);
            if ($warning = (new self)->where('content', $content)->first()) {
                $warning_types[] = $warning->id;
            } else {
                $warning_types[] = (new self)->create([
                    'content' => $content,
                    'warning_type' => array_search(strtolower($warning_type), self::$warning_types, true),
                ])->id;
            }
        }

        return $warning_types;
    }

    public static function exportWarnings($item_id)
    {
        $warnings_string = '';
        foreach (Item::getWarnings($item_id) as $warning) {
            $warnings_string .= '[alert type="'.$warning['type'].'"]'.$warning['content'].'[/alert]';
        }

        return $warnings_string;
    }
}
