<?php namespace Concore\Foundation\Http\ViewComposers;

use Illuminate\Contracts\View\View;
use Request, Lang;

class LayoutsBodyComposer {

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view_data = $view->getData();
        if(!isset($view_data['body_class'])) {
            $view->with('body_class',$this->getBodyClass());
        }
    }

    /**
     * Return a body class based on the current URL.
     *
     * @return string
     */
    protected function getBodyClass() {

        $body_classes = Request::segments() ?: ['home'];
        $body_classes[] = str_replace('.','-',Request::route()->getName());
        
        $body_classes = array_unique(array_filter($body_classes));

        // Add either the proceeding word or num to individual numbers, since they are illegal class names
        foreach($body_classes as $key => &$body_class) {
            if (is_numeric(substr($body_class, 0, 1))) {
                if (isset($body_classes[$key-1])) {
                    $prev = $body_classes[$key-1];
                    $body_class = str_singular($prev).'-'.$body_class;
                }
                else {
                    $body_class = 'num-'.$body_class;
                }
            }
        }

        // Add "rtl" if the language used is right-to-left
        if(in_array(Lang::getLocale(),setting_or_config('foundation.rtl-languages'))) {
            $body_classes[] = 'rtl';
        }

        return implode(' ',$body_classes);
    }

}