<?php

class LWordFilter {

    protected static $rules = [
        'filter_words'        => 'required'
    ];
    protected static $labels = [
        'filter_words'        => 'Filter Words'
    ];

    public static function create($data)
    {
        $insertStatus = true;

        $validator = Validator::make($data, self::$rules, [], self::$labels);

        if ($validator->fails()) {
            return [
                'status' => false,
                'errors' => $validator->errors()->all()
            ];
        }

        $filterWords = explode(',', Input::get('filter_words'));

        foreach ($filterWords as $word) {
            $initial = mb_substr($word, 0, 1);
            $wordLength = mb_strlen($word);

            $censor = $initial;

            for ($i=0; $i < $wordLength -1; $i++) {
                $censor .= '*';
            }

            $filterWord = FilterWord::firstOrNew(['word' => $word]);
            $filterWord->word = $word;
            $filterWord->censor = $censor;
            $filterWord->status = 1;
            if (!$filterWord->save()) {
                $insertStatus = false;
            }
        }

        if ($insertStatus) {
            self::updateFiltersFile();
            return [
                'status'    => true
            ];
        }

        return [
            'status' => false,
            'errors' => 'Error an Ocurred'
        ];
    }

    public static function remove($id)
    {
        $filterWord = FilterWord::find($id);
        $filterWord->status = -1;

        if ($filterWord->save()) {
            self::updateFiltersFile();
            return [
                'status'    => true
            ];
        }

        return [
            'status' => false,
            'errors' => 'Error an Ocurred'
        ];
    }

    public static function updateFiltersFile()
    {

        $words = FilterWord::where('status', 1)->select('word', 'censor')->get();

        $filterWords = [];

        foreach($words as $word){
            $filterWords[$word->word] = $word->censor;
        }

        @file_put_contents(storage_path('filters.txt'), json_encode($filterWords));

        return true;
    }

    public static function getFilterWords()
    {
        $filterWords = FilterWord::where('status', 1)->remember(5)->get(['word'])->toArray();

        $filterWordsAr = [];

        foreach ($filterWords as $filterWord) {
            array_push($filterWordsAr, strtolower_tr($filterWord['word']));
        }

        return $filterWordsAr;
    }

}