<?php namespace App\Modules\Utils\Alert;

use View, Session;
class Alert {

	const SESSION_NAME = 'AlertMessages';

	public function message($message, $type='success')
	{
		$messages = Session::get(static::SESSION_NAME, array());
		if(is_object($message) and get_class($message) == 'Illuminate\Support\MessageBag')
		{
			//dd(array_values($message->all()));
			$messages[] = ['message' => array_values($message->all()), 'type' => $type];
		}
		else
		{
			$messages[] = compact('message', 'type');
		}
		Session::flash(static::SESSION_NAME, $messages);
	}

	public function render()
    {
        $messages 	= Session::get(static::SESSION_NAME, null);
        $html 		= '';
        if ($messages != null)
        {
           Session::flash(static::SESSION_NAME, null);
           foreach ($messages as $message) {
           		$html.= Alert::make($message['message'], $message['type']);
           }
        }

        return $html;
    }




	/**
	* Get a bootstrap alert
	*
	* @param string $message Message to show
	* @param string $type Alert type (For example, if you want a "alert-danger", you need put only "danger")
	* @param bool $close Define if you want a close button
	*
	* @return string Html string with the element
	*/
	public function make($message, $type='success') {

		$message_html = '';
		if(!is_array($message))
		{
			$message_html =	'<p>'.$message.'</p>';
		}
		else
		{
			foreach ($message as $msg) {
				$message_html .='<p>'.$msg.'</p>';
			}
		}
		

		return View::make('alert::alert')
				->with('type', 		$type)
				->with('message', 	$message_html);
	}



	/**
	* Handle dynamic method calls into the method.
	* @param string $name
	* @param array $arguments
	* @return mixed
	*/
	/*public function __call($name, $arguments) {

		if(starts_with($name, 'alert'))
		{
			// It is understood that attempts to create an alert

			$message = '';
			if(isset($arguments[0]))
				$message = $arguments[0];

			$type	= strtolower(substr($name, 5));

			return $this->alert($message, $type);
		}

		throw new \BadMethodCallException("Method [$name] does not exist.");
	}*/
}