<?php

namespace App\Http\Controllers;

use App\Models\TickerMessages;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;

class TickerController extends Controller
{
    public function deleteTicker(Request $request){
        if(Auth::check()){
            $toDelete = $request->input('delete')[0];
            try{
                foreach($toDelete as $item){
                    $ticker = TickerMessages::find($item);
                    $ticker->delete();
                }
                return ["messageStatus" => "success", "errorMessage" => ""];
            } catch(\Exception $e){
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.TickerController.error_occurred", ["error" => $e->getMessage()])];
            }

        }
        abort(404);
    }

    public function addTicker(Request $request){
        if(Auth::check()){
            $toAdd = $request->input('insert');
            $lang = $request->input('lang');

            try {
                $ticker = new TickerMessages();
                $ticker->message = $toAdd;
                $ticker->language = $lang;
                $ticker->save();
                return ["messageStatus" => "success", "errorMessage" => ""];
            } catch(\Exception $e){
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.TickerController.error_occurred", ["error" => $e->getMessage()])];
            }
        }
        abort(404);
    }

    public static function getTicker(){
        $t = "";
        foreach(TickerMessages::getMessages(App::getLocale())->get() as $message){
            $t .= " -- $message->message";
        }

        if(!empty($t)){
            $t .= " -- ";
        }

        return $t;
    }
}
