<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\News;
use App\BreakingNews;
use App\Section;
use App\Home;
use App\Page;
use App\PageAdv;
use App\SectionAdv;
use App\Event;
use App\Season;
use App\Video;
use App\Calendar;
use App\Category;
use App\Group;
use App\CalendarGame;
use App\Notifications\FacebookPost;
use App\Notifications\TwitterPost;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
ini_set("auto_detect_line_endings", true);
date_default_timezone_set('Europe/Rome');

Route::get('/test_fb', function(){
    print env('FACEBOOK_ACCESS_TOKEN', '');
    $n = News::findOrFail(41436);
    $n->notify(new FacebookPost());

});

Route::get('/update/sections', function () {

    $aPositions = array('big', 'small1', 'small2', 'small3', 'small4', 'small5', 'small6');

    $sections = Section::all();
    foreach($sections as $section)
    {
        print $section->name . "<br>";

        $section_id = $section->id;

        // Carico il layout
        $layout = $section->layout;

        /*$aExist = array();
        foreach($aPositions as $p)
        {
            if ($section[$p] != null)
                $aExist[] = $section[$p];
        }*/

        // Controllo se ci sono news che devono essere pubblicate appartenenti a questa sezione

        $checks = News::where('date', '<=', date('Y-m-d H:i:s'))->where('online', '=', true)->where(function ($q) use ($section_id) {
            $q->where('region_1_id', '=', $section_id)->orWhere('region_2_id', '=', $section_id)->orWhere('section_id', '=', $section_id);
        })->where(function ($q)  {
            $q->where('region_1_position', '<>', '')->orWhere('region_2_position', '<>', '')->orWhere('section_position', '<>', '');
        })->get();

        foreach($checks as $n)
        {
            // Controllo se questa news era già in qualche altra posizione
            $old_position = Section::where('big', '=', $n->id)
                            ->orWhere('small1', '=', $n->id)
                            ->orWhere('small2', '=', $n->id)
                            ->orWhere('small3', '=', $n->id)
                            ->orWhere('small4', '=', $n->id)
                            ->orWhere('small5', '=', $n->id)
                            ->orWhere('small6', '=', $n->id)->get();
            if ($old_position->count() > 0)
            {
                foreach($old_position as $old_p)
                {
                    foreach($aPositions as $p)
                    {

                        if ($old_p[$p] == $n->id)
                        {
                            $old_p[$p] = '';
                            $old_p->save();
                        }

                    }
                }
            }

            // Metto la news nella posizione dove deve essere messa
            foreach($aPositions as $p)
            {

                if ($n->section_id == $section_id && $n->section_position == $p)
                {
                    print "Metto la news " . $n->title . " nella posizione " . $p . " della sezione/regione " . $section->name . "<br>";
                    $section[$p] = $n->id;
                    $section->save();
                    $n->section_position = '';
                    if (!$n->published)
                    {
                        //$n->notify(new FacebookPost());
                        //$n->notify(new TwitterPost());
                        $n->published = true;
                    }
                    $n->save();
                }
                if ($n->region_1_id == $section_id && $n->region_1_position == $p)
                {
                    print "Metto la news " . $n->title . " nella posizione " . $p . " della sezione/regione " . $section->name . "<br>";
                    $section[$p] = $n->id;
                    $section->save();
                    $n->region_1_position = '';
                    if (!$n->published)
                    {
                        // $n->notify(new FacebookPost());
                        $n->notify(new TwitterPost());
                        $n->published = true;
                    }
                    $n->save();
                }
                if ($n->region_2_id == $section_id && $n->region_2_position == $p)
                {
                    print "Metto la news " . $n->title . " nella posizione " . $p . " della sezione/regione " . $section->name . "<br>";
                    $section[$p] = $n->id;
                    $section->save();
                    $n->region_2_position = '';
                    if (!$n->published)
                    {
                        // $n->notify(new FacebookPost());
                        $n->notify(new TwitterPost());
                        $n->published = true;
                    }
                    $n->save();
                }
            }

        }

    }

    $sections = Section::all();
    foreach($sections as $section)
    {

        $aExist = array();
        foreach($aPositions as $p)
        {
            if ($section[$p] != null)
                $aExist[] = $section[$p];
        }

        // Riempio i vuoti
        $news = News::whereNotIn('id', $aExist)->where(function ($q) use ($section_id) {
            $q->where('section_id', '=', $section_id)->orWhere('region_1_id', '=', $section_id)->orWhere('region_2_id', '=', $section_id);
        })->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();

        $idx = 0;
        if ($section->big == '')
        {
            $section->big = @$news[$idx]->id;
            $idx++;
        }

        if ($section->small1 == '')
        {
            $section->small1 = @$news[$idx]->id;
            $idx++;
        }

        if ($section->small2 == '')
        {
            $section->small2 = @$news[$idx]->id;
            $idx++;
        }

        if ($section->small3 == '')
        {
            $section->small3 = @$news[$idx]->id;
            $idx++;
        }

        if ($layout == 'layout_3' || $layout == 'layout_4' || $layout == 'layout_5')
        {
            if ($section->small4 == '')
            {
                $section->small4 = @$news[$idx]->id;
                $idx++;
            }

            if ($layout == 'layout_4')
            {
                if ($section->small5 == '')
                {
                    $section->small5 = @$news[$idx]->id;
                    $idx++;
                }

                if ($section->small6 == '')
                {
                    $section->small6 = @$news[$idx]->id;
                    $idx++;
                }
            }
            else
            {
                $section->small5 = '';
                $section->small6 = '';
            }
        }
        else
        {
            $section->small4 = '';
            $section->small5 = '';
            $section->small6 = '';
        }

        $section->save();

    }

});

Route::get('sitemap.xml', function() {

	// create new sitemap object
	$sitemap = App::make('sitemap');

	// set cache key (string), duration in minutes (Carbon|Datetime|int), turn on/off (boolean)
	// by default cache is disabled
	$sitemap->setCache('laravel.sitemap', 60);

	// check if there is cached sitemap and build new only if is not
    if (!$sitemap->isCached())
    {
		// add item to the sitemap (url, date, priority, freq)
        $sitemap->add(URL::to('/'), date("Y-m-d H:i:s"), '1.0', 'daily');

        $sections = Section::orderBy('position')->get();
        foreach($sections as $section)
            $sitemap->add(URL::to('/' . $section->slug), date("Y-m-d H:i:s", strtotime($section->updated_at)), '0.9', 'daily');

        $pages = Page::where('online', '=', true)->orderBy('title')->get();
        foreach($pages as $page)
            $sitemap->add(URL::to('/' . $page->slug), date("Y-m-d H:i:s", strtotime($page->updated_at)), '0.9', 'daily');

        $events = Event::where('online', '=', true)->orderBy('title')->get();
        foreach($events as $event)
            $sitemap->add(URL::to('/' . $event->slug), date("Y-m-d H:i:s", strtotime($event->updated_at)), '0.9', 'daily');

        $season_id = @Season::where('default', '=', true)->first()->id;
        $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();
        $calendars = array();
        foreach($cals as $c)
        {

            if ($c->category->grp != '')
            {
                $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
                if ($c->group_id > 0)
                    $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
                else
                    $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
            }

        }
        foreach($calendars as $type => $categories)
        {
            foreach($categories as $category => $groups)
            {
                if(is_array($groups))
                {
                    foreach($groups as $group => $cal)
                    {
                        $sitemap->add(URL::to('/calendario/' . Str::slug($category) . "-" . Str::slug($group) . "/" . $cal), date("Y-m-d H:i:s"), '0.9', 'daily');
                    }
                }
                else
                    $sitemap->add(URL::to('/calendario/' . Str::slug($category) . "-" . Str::slug($groups)), date("Y-m-d H:i:s"), '0.9', 'daily');
            }
        }

        //$news = News::where('online', '=', true)->where('breaking_news', '=', false)->orderBy('date', 'DESC')->get();
        //foreach($news as $n)
        //    $sitemap->add(URL::to('/' . $n->slug), date("Y-m-d H:i:s", strtotime($n->updated_at)), '0.9', 'hourly');

        //$cals = Calendar::orderBy('position')->get();
        //foreach($cals as $c)
        //    $sitemap->add(URL::to('/' . $c->slug), date("Y-m-d H:i:s", strtotime($c->updated_at)), '0.9', 'daily');
            /*

		//$sitemap->add(URL::to('page'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly');
        /*
		// add item with translations (url, date, priority, freq, images, title, translations)
		$translations = [
			['language' => 'fr', 'url' => URL::to('pageFr')],
			['language' => 'de', 'url' => URL::to('pageDe')],
			['language' => 'bg', 'url' => URL::to('pageBg')],
		];
		$sitemap->add(URL::to('pageEn'), '2015-06-24T14:30:00+02:00', '0.9', 'monthly', [], null, $translations);

		// add item with images
		$images = [
			['url' => URL::to('images/pic1.jpg'), 'title' => 'Image title', 'caption' => 'Image caption', 'geo_location' => 'Plovdiv, Bulgaria'],
			['url' => URL::to('images/pic2.jpg'), 'title' => 'Image title2', 'caption' => 'Image caption2'],
			['url' => URL::to('images/pic3.jpg'), 'title' => 'Image title3'],
		];
		$sitemap->add(URL::to('post-with-images'), '2015-06-24T14:30:00+02:00', '0.9', 'monthly', $images);

		// get all posts from db
		$posts = DB::table('posts')->orderBy('created_at', 'desc')->get();

		// add every post to the sitemap
		foreach ($posts as $post) {
			$sitemap->add($post->slug, $post->modified, $post->priority, $post->freq);
		}*/
	}

	// show your sitemap (options: 'xml' (default), 'html', 'txt', 'ror-rss', 'ror-rdf')
	return $sitemap->render('xml');
});

Route::get('/', function () {

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = 0;//rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }

    $show_top = true;

    if ($home->banner_right_big != '' || $home->banner_right_big_2 != '' || $home->banner_right_big_3 != '' || $home->banner_right_big_google != '')
        $show_top = false;

    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    // $sections = Section::where('type', '=', 'section')->orderBy('position')->get();
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $sections = Section::where('layout', '!=', '')->orderBy('position')->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $videos = Video::where('online', '=', true)->limit(10)->orderBy('position')->get();
    foreach($videos as $i => $v)
    {
        $x = $v->url;
        $x = str_replace("https", "", $x);
        $x = str_replace("http", "", $x);
        $v->url = $x;
    }

    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    // $sections_after = Section::where('type', '=', 'section')->where('after', '=', true)->where('layout', '!=', '')->orderBy('position')->get();
    return view('index', compact('home', 'sections', 'sections_menu', 'regions', 'pages', 'breaking_news', 'videos', 'events', 'calendars', 'aHome', 'show_top'));

});

Route::get('/videos', function(){
    $videos = Video::where('online', '=', true)->orderBy('date', 'DESC')->get();
    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();

    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    /*$calendars = array();
    foreach($cals as $c)
    {

        $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
        if ($c->group_id > 0)
            $calendars[$type][$c->category->name][$c->group->name] = $c->id;
        else
            $calendars[$type][$c->category->name] = $c->id;

    }*/
    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    return view('video', compact('videos', 'home', 'sections', 'sections_menu', 'regions', 'pages', 'breaking_news', 'videos', 'events', 'calendars', 'aHome'));
});

Route::get('/ricerca', function(){

    $news = News::where('id', -1)->get();

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }
    $search  = '';
    $videos = array();

    return view('search', compact('news', 'search', 'home', 'sections', 'sections_menu', 'regions', 'pages', 'breaking_news', 'videos', 'events', 'calendars', 'aHome'));

});

Route::post('/ricerca', function(){
    $search = $_POST["search"];
    if ($search != '')
    {
        $news = News::where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->where(function ($q) use ($search) {
            $q->where('title', 'like', '%' . $search . '%')
                ->orWhere('title_region_1', 'like', '%' . $search . '%')
                ->orWhere('title_region_2', 'like', '%' . $search . '%')
                ->orWhere('text_short', 'like', '%' . $search . '%')
                ->orWhere('text', 'like', '%' . $search . '%');
        })->orderBy('date', 'DESC')->get();
    }
    else
        $news = News::where('id', -1)->get();

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }
    $videos = array();

    return view('search', compact('news', 'search', 'home', 'sections', 'sections_menu', 'regions', 'pages', 'breaking_news', 'videos', 'events', 'calendars', 'aHome'));
});

Route::get('/eventi', function(){

    $news = News::where('id', -1)->get();

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }
    $videos = array();

    return view('events', compact('news', 'home', 'sections', 'sections_menu', 'regions', 'pages', 'breaking_news', 'videos', 'events', 'calendars', 'aHome'));
});

Route::get('/archivio', function() {
    $news = News::where('id', -1)->get();
    $home = Home::first();

    if ($home != null) {
        $home->loadData();
    }

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();
    $archivedCalendars = Calendar::where('archived', true)
    ->with(['category', 'group']) // Eager load relationships
    ->get();
    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    $seasons = Season::where('default', false)->orderBy('name', 'desc')->get();
    $sections = Section::where('type', '=', 'section')
        ->orderBy('position')
        ->get();
    $regions = Section::where('type', '=', 'region')
        ->orderBy('name')
        ->get();
    $categories = Category::orderBy('name')->get();
    $groups = Group::orderBy('name')->get();

    $seasonsForJs = $seasons->map(function($season) {
        return [
            'id' => $season->id,
            'name' => $season->name
        ];
    });

    return view('calendar_archive', compact(
        'news',
        'home',
        'sections',
        'sections_menu',
        'regions',
        'pages',
        'breaking_news',
        'seasons',
        'seasonsForJs',
        'categories',
        'groups',
        'archivedCalendars',
        'aHome',
        'calendars'
    ));

});

Route::get('/api/archive/calendars/search', function(Request $request) {
    $query = Calendar::with(['season', 'category', 'group']) // Eager load relationships
        ->where('archived', true);

    if ($request->season_id) {
        $query->where('season_id', $request->season_id);
    }

    if ($request->type) {
        $query->whereHas('category', function($q) use ($request) {
            $q->where('type', $request->type);
        });
    }

    if ($request->category_id) {
        $query->where('category_id', $request->category_id);
    }

    if ($request->group_id) {
        $query->where('group_id', $request->group_id);
    }

    $calendars = $query->orderBy('position')->get()
        ->map(function($calendar) {
            return [
                'id' => $calendar->id,
                'name' => $calendar->name,
                'season' => $calendar->season ? $calendar->season->name : '',
                'category' => $calendar->category ? $calendar->category->name : '',
                'group' => $calendar->group ? $calendar->group->name : '',
                'type' => $calendar->category ? $calendar->category->type : '',
                'position' => $calendar->position
            ];
        });

    return response()->json([
        'success' => true,
        'data' => $calendars
    ]);
});

Route::get('/video/{id}', function ($id) {

        $video = Video::findOrFail($id);
        if ($video->file != '')
        {
            $html = '<video width="640" height="480" controls>
            <source src="/files/videos/' . $video->file . '" type="video/mp4">
            Your browser does not support the video tag.
            </video>';
            print $html;
        }
        else
            print $video->embed;

    });

Route::get('/section/{id}', function ($id) {

    $home = Home::first();
    if ($home != null)
        $home->loadData();
    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }

    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }
    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    //$sections = Section::orderBy('position')->get();
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $sections = Section::where('layout', '!=', '')->orderBy('position')->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $news = News::where('section_id', '=', $id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }
    return view('section', compact('home', 'news', 'sections', 'sections_menu', 'pages', 'regions', 'events', 'breaking_news', 'calendars', 'aHome'));

});

Route::get('/admin', function () {

    if (Auth::check())
        return Redirect::to('/admin/dashboard');
    else
        return view('admin');

});

Route::get('/logout', function () {
	Auth::logout();
    return Redirect::to('/admin');
});

Route::post('/login', function(){

    if ($user = Auth::attempt(['email' => $_POST["email"], 'password' => $_POST["password"]]))
        return Redirect::to('/admin/dashboard');
    else
        return view('admin')->with('message', 'Errore login');

});

Route::group(['middleware' => 'auth'], function () {

    Route::prefix('admin')->group(function () {

        Route::get('/dashboard', function ()
        {

            $sections = Section::where('type', '=', 'section')->orderBy('position')->get();
            $regions = Section::where('type', '=', 'region')->orderBy('position')->get();
            return view('admin.dashboard', compact('sections', 'regions'));

        });

        Route::get('/home', function () {

            $home = Home::first();
            if ($home == null)
            {
                $home = new Home();
                $home->save();
            }
            $home->loadData();

            $aAssigned = array();
            if ($home->slide1 != '')
                $aAssigned[] = $home->slide1->id;
            if ($home->left1 != '')
                $aAssigned[] = $home->left1->id;
            if ($home->left2 != '')
                $aAssigned[] = $home->left2->id;
            if ($home->left3 != '')
                $aAssigned[] = $home->left3->id;
            if ($home->right1 != '')
                $aAssigned[] = $home->right1->id;
            if ($home->right2 != '')
                $aAssigned[] = $home->right2->id;
            if ($home->right3 != '')
                $aAssigned[] = $home->right3->id;

            $news = News::where('online', '=', 1)->whereNotIn('id', $aAssigned)->orderBy('date', 'DESC')->limit(1000)->get();

            return view('admin.home',compact('home', 'news'));

        })->name('home');


        Route::post('/home', function () {

            $home = Home::first();
            if ($home == null)
                $home = new Home();

            $slide1 = isset($_POST["slide1"]) ? $_POST["slide1"] : '';
            $left1 = isset($_POST["left1"]) ? $_POST["left1"] : '';
            $left2 = isset($_POST["left2"]) ? $_POST["left2"] : '';
            $left3 = isset($_POST["left3"]) ? $_POST["left3"] : '';
            $left4 = isset($_POST["left4"]) ? $_POST["left4"] : '';
            $left5 = isset($_POST["left5"]) ? $_POST["left5"] : '';
            $right1 = isset($_POST["right1"]) ? $_POST["right1"] : '';
            $right2 = isset($_POST["right2"]) ? $_POST["right2"] : '';
            $right3 = isset($_POST["right3"]) ? $_POST["right3"] : '';
            $right4 = isset($_POST["right4"]) ? $_POST["right4"] : '';
            $right5 = isset($_POST["right5"]) ? $_POST["right5"] : '';

            if (isset($_POST["delete_image"]))
            {
                $image = '';
                $home->image = $image;
            }
            else
            {
                if(isset($_POST["image"]))
                {

                    $file = $_POST["image"];
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    $_POST["image"]->move($path, $filename);

                    $image = $filename;
                    $home->image = $image;

                }
            }
            //$url = isset($_POST["url"]) ? $_POST["url"] : '';

            $home->slide1 = $slide1;
            $home->left1 = $left1;
            $home->left2 = $left2;
            $home->left3 = $left3;
            $home->left4 = $left4;
            $home->left5 = $left5;
            $home->right1 = $right1;
            $home->right2 = $right2;
            $home->right3 = $right3;
            $home->right4 = $right4;
            $home->right5 = $right5;

            //$home->url = $url;


            $home->save();

            return Redirect::to('/admin/home');

        })->name('home');

        Route::get('/home_adv', function () {

            $home = Home::first();
            if ($home == null)
            {
                $home = new Home();
                $home->save();
            }
            $home->loadData();

            return view('admin.home_adv',compact('home'));

        })->name('home_adv');


        Route::post('/home_adv', function () {

            $home = Home::first();
            if ($home == null)
                $home = new Home();

            if (isset($_POST["delete_image"]))
            {
                $image = '';
                $home->image = $image;
            }
            else
            {
                if(request()->image)
                {

                    $file = request()->image;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->image->move($path, $filename);

                    $image = $filename;
                    $home->image = $image;

                }
            }
            $url = isset($_POST["url"]) ? $_POST["url"] : '';
            $home->url = $url;

            if (isset($_POST["delete_image_2"]))
            {
                $image_2 = '';
                $home->image_2 = $image_2;
            }
            else
            {
                if(request()->image_2)
                {

                    $file = request()->image_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->image_2->move($path, $filename);

                    $image_2 = $filename;
                    $home->image_2 = $image_2;

                }
            }
            $url_2 = isset($_POST["url_2"]) ? $_POST["url_2"] : '';
            $home->url_2 = $url_2;

            if (isset($_POST["delete_image_3"]))
            {
                $image_3 = '';
                $home->image_3 = $image_3;
            }
            else
            {
                if(request()->image_3)
                {

                    $file = request()->image_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->image_3->move($path, $filename);

                    $image_3 = $filename;
                    $home->image_3 = $image_3;

                }
            }
            $url_3 = isset($_POST["url_3"]) ? $_POST["url_3"] : '';
            $home->url_3 = $url_3;

            if (isset($_POST["delete_image_4"]))
            {
                $image_4 = '';
                $home->image_4 = $image_4;
            }
            else
            {
                if(request()->image_4)
                {

                    $file = request()->image_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->image_4->move($path, $filename);

                    $image_4 = $filename;
                    $home->image_4 = $image_4;

                }
            }
            $url_4 = isset($_POST["url_4"]) ? $_POST["url_4"] : '';
            $home->url_4 = $url_4;

            if (isset($_POST["delete_image_5"]))
            {
                $image_5 = '';
                $home->image_5 = $image_5;
            }
            else
            {
                if(request()->image_5)
                {

                    $file = request()->image_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->image_5->move($path, $filename);

                    $image_5 = $filename;
                    $home->image_5 = $image_5;

                }
            }
            $url_5 = isset($_POST["url_5"]) ? $_POST["url_5"] : '';
            $home->url_5 = $url_5;

            if (isset($_POST["delete_banner_top"]))
            {
                $banner_top = '';
                $home->banner_top = $banner_top;
            }
            else
            {
                if(request()->banner_top)
                {

                    $file = request()->banner_top;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_top->move($path, $filename);

                    $banner_top = $filename;
                    $home->banner_top = $banner_top;

                }
            }
            $banner_top_url = isset($_POST["banner_top_url"]) ? $_POST["banner_top_url"] : '';
            $home->banner_top_url = $banner_top_url;

            if (isset($_POST["delete_banner_top_2"]))
            {
                $banner_top_2 = '';
                $home->banner_top_2 = $banner_top_2;
            }
            else
            {
                if(request()->banner_top_2)
                {

                    $file = request()->banner_top_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_top_2->move($path, $filename);

                    $banner_top_2 = $filename;
                    $home->banner_top_2 = $banner_top_2;

                }
            }
            $banner_top_2_url = isset($_POST["banner_top_2_url"]) ? $_POST["banner_top_2_url"] : '';
            $home->banner_top_2_url = $banner_top_2_url;

            if (isset($_POST["delete_banner_top_3"]))
            {
                $banner_top_3 = '';
                $home->banner_top_3 = $banner_top_3;
            }
            else
            {
                if(request()->banner_top_3)
                {

                    $file = request()->banner_top_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_top_3->move($path, $filename);

                    $banner_top_3 = $filename;
                    $home->banner_top_3 = $banner_top_3;

                }
            }
            $banner_top_3_url = isset($_POST["banner_top_3_url"]) ? $_POST["banner_top_3_url"] : '';
            $home->banner_top_3_url = $banner_top_3_url;

            if (isset($_POST["delete_banner_top_4"]))
            {
                $banner_top_4 = '';
                $home->banner_top_4 = $banner_top_4;
            }
            else
            {
                if(request()->banner_top_4)
                {

                    $file = request()->banner_top_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_top_4->move($path, $filename);

                    $banner_top_4 = $filename;
                    $home->banner_top_4 = $banner_top_4;

                }
            }
            $banner_top_4_url = isset($_POST["banner_top_4_url"]) ? $_POST["banner_top_4_url"] : '';
            $home->banner_top_4_url = $banner_top_4_url;

            if (isset($_POST["delete_banner_top_5"]))
            {
                $banner_top_5 = '';
                $home->banner_top_5 = $banner_top_5;
            }
            else
            {
                if(request()->banner_top_5)
                {

                    $file = request()->banner_top_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_top_5->move($path, $filename);

                    $banner_top_5 = $filename;
                    $home->banner_top_5 = $banner_top_5;

                }
            }
            $banner_top_5_url = isset($_POST["banner_top_5_url"]) ? $_POST["banner_top_5_url"] : '';
            $home->banner_top_5_url = $banner_top_5_url;

            $banner_top_google = isset($_POST["banner_top_google"]) ? $_POST["banner_top_google"] : '';
            $home->banner_top_google = $banner_top_google;

            if (isset($_POST["delete_banner_underb"]))
            {
                $banner_underb = '';
                $home->banner_underb = $banner_underb;
            }
            else
            {
                if(request()->banner_underb)
                {

                    $file = request()->banner_underb;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_underb->move($path, $filename);

                    $banner_underb = $filename;
                    $home->banner_underb = $banner_underb;

                }
            }
            $banner_underb_url = isset($_POST["banner_underb_url"]) ? $_POST["banner_underb_url"] : '';
            $home->banner_underb_url = $banner_underb_url;

            if (isset($_POST["delete_banner_underb_2"]))
            {
                $banner_underb_2 = '';
                $home->banner_underb_2 = $banner_underb_2;
            }
            else
            {
                if(request()->banner_underb_2)
                {

                    $file = request()->banner_underb_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_underb_2->move($path, $filename);

                    $banner_underb_2 = $filename;
                    $home->banner_underb_2 = $banner_underb_2;

                }
            }
            $banner_underb_2_url = isset($_POST["banner_underb_2_url"]) ? $_POST["banner_underb_2_url"] : '';
            $home->banner_underb_2_url = $banner_underb_2_url;

            if (isset($_POST["delete_banner_underb_3"]))
            {
                $banner_underb_3 = '';
                $home->banner_underb_3 = $banner_underb_3;
            }
            else
            {
                if(request()->banner_underb_3)
                {

                    $file = request()->banner_underb_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_underb_3->move($path, $filename);

                    $banner_underb_3 = $filename;
                    $home->banner_underb_3 = $banner_underb_3;

                }
            }
            $banner_underb_3_url = isset($_POST["banner_underb_3_url"]) ? $_POST["banner_underb_3_url"] : '';
            $home->banner_underb_3_url = $banner_underb_3_url;

            if (isset($_POST["delete_banner_underb_4"]))
            {
                $banner_underb_4 = '';
                $home->banner_underb_4 = $banner_underb_4;
            }
            else
            {
                if(request()->banner_underb_4)
                {

                    $file = request()->banner_underb_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_underb_4->move($path, $filename);

                    $banner_underb_4 = $filename;
                    $home->banner_underb_4 = $banner_underb_4;

                }
            }
            $banner_underb_4_url = isset($_POST["banner_underb_4_url"]) ? $_POST["banner_underb_4_url"] : '';
            $home->banner_underb_4_url = $banner_underb_4_url;

            if (isset($_POST["delete_banner_underb_5"]))
            {
                $banner_underb_5 = '';
                $home->banner_underb_5 = $banner_underb_5;
            }
            else
            {
                if(request()->banner_underb_5)
                {

                    $file = request()->banner_underb_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_underb_5->move($path, $filename);

                    $banner_underb_5 = $filename;
                    $home->banner_underb_5 = $banner_underb_5;

                }
            }
            $banner_underb_5_url = isset($_POST["banner_underb_5_url"]) ? $_POST["banner_underb_5_url"] : '';
            $home->banner_underb_5_url = $banner_underb_5_url;

            $banner_underb_google = isset($_POST["banner_underb_google"]) ? $_POST["banner_underb_google"] : '';
            $home->banner_underb_google = $banner_underb_google;

            if (isset($_POST["delete_banner_middle"]))
            {
                $banner_middle = '';
                $home->banner_middle = $banner_middle;
            }
            else
            {
                if(request()->banner_middle)
                {

                    $file = request()->banner_middle;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_middle->move($path, $filename);

                    $banner_middle = $filename;
                    $home->banner_middle = $banner_middle;

                }
            }
            $banner_middle_url = isset($_POST["banner_middle_url"]) ? $_POST["banner_middle_url"] : '';
            $home->banner_middle_url = $banner_middle_url;

            if (isset($_POST["delete_banner_middle_2"]))
            {
                $banner_middle_2 = '';
                $home->banner_middle_2 = $banner_middle_2;
            }
            else
            {
                if(request()->banner_middle_2)
                {

                    $file = request()->banner_middle_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_middle_2->move($path, $filename);

                    $banner_middle_2 = $filename;
                    $home->banner_middle_2 = $banner_middle_2;

                }
            }
            $banner_middle_2_url = isset($_POST["banner_middle_2_url"]) ? $_POST["banner_middle_2_url"] : '';
            $home->banner_middle_2_url = $banner_middle_2_url;

            if (isset($_POST["delete_banner_middle_3"]))
            {
                $banner_middle_3 = '';
                $home->banner_middle_3 = $banner_middle_3;
            }
            else
            {
                if(request()->banner_middle_3)
                {

                    $file = request()->banner_middle_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_middle_3->move($path, $filename);

                    $banner_middle_3 = $filename;
                    $home->banner_middle_3 = $banner_middle_3;

                }
            }
            $banner_middle_3_url = isset($_POST["banner_middle_3_url"]) ? $_POST["banner_middle_3_url"] : '';
            $home->banner_middle_3_url = $banner_middle_3_url;

            if (isset($_POST["delete_banner_middle_4"]))
            {
                $banner_middle_4 = '';
                $home->banner_middle_4 = $banner_middle_4;
            }
            else
            {
                if(request()->banner_middle_4)
                {

                    $file = request()->banner_middle_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_middle_4->move($path, $filename);

                    $banner_middle_4 = $filename;
                    $home->banner_middle_4 = $banner_middle_4;

                }
            }
            $banner_middle_4_url = isset($_POST["banner_middle_4_url"]) ? $_POST["banner_middle_4_url"] : '';
            $home->banner_middle_4_url = $banner_middle_4_url;

            if (isset($_POST["delete_banner_middle_5"]))
            {
                $banner_middle_5 = '';
                $home->banner_middle_5 = $banner_middle_5;
            }
            else
            {
                if(request()->banner_middle_5)
                {

                    $file = request()->banner_middle_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_middle_5->move($path, $filename);

                    $banner_middle_5 = $filename;
                    $home->banner_middle_5 = $banner_middle_5;

                }
            }
            $banner_middle_5_url = isset($_POST["banner_middle_5_url"]) ? $_POST["banner_middle_5_url"] : '';
            $home->banner_middle_5_url = $banner_middle_5_url;


            $banner_middle_google = isset($_POST["banner_middle_google"]) ? $_POST["banner_middle_google"] : '';
            $home->banner_middle_google = $banner_middle_google;

            if (isset($_POST["delete_banner_first"]))
            {
                $banner_first = '';
                $home->banner_first = $banner_first;
            }
            else
            {
                if(request()->banner_first)
                {

                    $file = request()->banner_first;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_first->move($path, $filename);

                    $banner_first = $filename;
                    $home->banner_first = $banner_first;

                }
            }
            $banner_first_url = isset($_POST["banner_first_url"]) ? $_POST["banner_first_url"] : '';
            $home->banner_first_url = $banner_first_url;

            if (isset($_POST["delete_banner_first_2"]))
            {
                $banner_first_2 = '';
                $home->banner_first_2 = $banner_first_2;
            }
            else
            {
                if(request()->banner_first_2)
                {

                    $file = request()->banner_first_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_first_2->move($path, $filename);

                    $banner_first_2 = $filename;
                    $home->banner_first_2 = $banner_first_2;

                }
            }
            $banner_first_2_url = isset($_POST["banner_first_2_url"]) ? $_POST["banner_first_2_url"] : '';
            $home->banner_first_2_url = $banner_first_2_url;

            if (isset($_POST["delete_banner_first_3"]))
            {
                $banner_first_3 = '';
                $home->banner_first_3 = $banner_first_3;
            }
            else
            {
                if(request()->banner_first_3)
                {

                    $file = request()->banner_first_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_first_3->move($path, $filename);

                    $banner_first_3 = $filename;
                    $home->banner_first_3 = $banner_first_3;

                }
            }
            $banner_first_3_url = isset($_POST["banner_first_3_url"]) ? $_POST["banner_first_3_url"] : '';
            $home->banner_first_3_url = $banner_first_3_url;

            if (isset($_POST["delete_banner_first_4"]))
            {
                $banner_first_4 = '';
                $home->banner_first_4 = $banner_first_4;
            }
            else
            {
                if(request()->banner_first_4)
                {

                    $file = request()->banner_first_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_first_4->move($path, $filename);

                    $banner_first_4 = $filename;
                    $home->banner_first_4 = $banner_first_4;

                }
            }
            $banner_first_4_url = isset($_POST["banner_first_4_url"]) ? $_POST["banner_first_4_url"] : '';
            $home->banner_first_4_url = $banner_first_4_url;

            if (isset($_POST["delete_banner_first_5"]))
            {
                $banner_first_5 = '';
                $home->banner_first_5 = $banner_first_5;
            }
            else
            {
                if(request()->banner_first_5)
                {

                    $file = request()->banner_first_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_first_5->move($path, $filename);

                    $banner_first_5 = $filename;
                    $home->banner_first_5 = $banner_first_5;

                }
            }
            $banner_first_5_url = isset($_POST["banner_first_5_url"]) ? $_POST["banner_first_5_url"] : '';
            $home->banner_first_5_url = $banner_first_5_url;

            $banner_first_google = isset($_POST["banner_first_google"]) ? $_POST["banner_first_google"] : '';
            $home->banner_first_google = $banner_first_google;

            if (isset($_POST["delete_banner_right_top"]))
            {
                $banner_right_top = '';
                $home->banner_right_top = $banner_right_top;
            }
            else
            {
                if(request()->banner_right_top)
                {

                    $file = request()->banner_right_top;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_top->move($path, $filename);

                    $banner_right_top = $filename;
                    $home->banner_right_top = $banner_right_top;

                }
            }
            $banner_right_top_url = isset($_POST["banner_right_top_url"]) ? $_POST["banner_right_top_url"] : '';
            $home->banner_right_top_url = $banner_right_top_url;

            if (isset($_POST["delete_banner_right_top_2"]))
            {
                $banner_right_top_2 = '';
                $home->banner_right_top_2 = $banner_right_top_2;
            }
            else
            {
                if(request()->banner_right_top_2)
                {

                    $file = request()->banner_right_top_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_top_2->move($path, $filename);

                    $banner_right_top_2 = $filename;
                    $home->banner_right_top_2 = $banner_right_top_2;

                }
            }
            $banner_right_top_2_url = isset($_POST["banner_right_top_2_url"]) ? $_POST["banner_right_top_2_url"] : '';
            $home->banner_right_top_2_url = $banner_right_top_2_url;

            if (isset($_POST["delete_banner_right_top_3"]))
            {
                $banner_right_top_3 = '';
                $home->banner_right_top_3 = $banner_right_top_3;
            }
            else
            {
                if(request()->banner_right_top_3)
                {

                    $file = request()->banner_right_top_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_top_3->move($path, $filename);

                    $banner_right_top_3 = $filename;
                    $home->banner_right_top_3 = $banner_right_top_3;

                }
            }
            $banner_right_top_3_url = isset($_POST["banner_right_top_3_url"]) ? $_POST["banner_right_top_3_url"] : '';
            $home->banner_right_top_3_url = $banner_right_top_3_url;

            if (isset($_POST["delete_banner_right_top_4"]))
            {
                $banner_right_top_4 = '';
                $home->banner_right_top_4 = $banner_right_top_4;
            }
            else
            {
                if(request()->banner_right_top_4)
                {

                    $file = request()->banner_right_top_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_top_4->move($path, $filename);

                    $banner_right_top_4 = $filename;
                    $home->banner_right_top_4 = $banner_right_top_4;

                }
            }
            $banner_right_top_4_url = isset($_POST["banner_right_top_4_url"]) ? $_POST["banner_right_top_4_url"] : '';
            $home->banner_right_top_4_url = $banner_right_top_4_url;

            if (isset($_POST["delete_banner_right_top_5"]))
            {
                $banner_right_top_5 = '';
                $home->banner_right_top_5 = $banner_right_top_5;
            }
            else
            {
                if(request()->banner_right_top_5)
                {

                    $file = request()->banner_right_top_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_top_5->move($path, $filename);

                    $banner_right_top_5 = $filename;
                    $home->banner_right_top_5 = $banner_right_top_5;

                }
            }
            $banner_right_top_5_url = isset($_POST["banner_right_top_5_url"]) ? $_POST["banner_right_top_5_url"] : '';
            $home->banner_right_top_5_url = $banner_right_top_5_url;

            $banner_right_top_google = isset($_POST["banner_right_top_google"]) ? $_POST["banner_right_top_google"] : '';
            $home->banner_right_top_google = $banner_right_top_google;

            if (isset($_POST["delete_banner_right_bottom"]))
            {
                $banner_right_bottom = '';
                $home->banner_right_bottom = $banner_right_bottom;
            }
            else
            {
                if(request()->banner_right_bottom)
                {

                    $file = request()->banner_right_bottom;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_bottom->move($path, $filename);

                    $banner_right_bottom = $filename;
                    $home->banner_right_bottom = $banner_right_bottom;

                }
            }
            $banner_right_bottom_url = isset($_POST["banner_right_bottom_url"]) ? $_POST["banner_right_bottom_url"] : '';
            $home->banner_right_bottom_url = $banner_right_bottom_url;

            if (isset($_POST["delete_banner_right_bottom_2"]))
            {
                $banner_right_bottom_2 = '';
                $home->banner_right_bottom_2 = $banner_right_bottom_2;
            }
            else
            {
                if(request()->banner_right_bottom_2)
                {

                    $file = request()->banner_right_bottom_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_bottom_2->move($path, $filename);

                    $banner_right_bottom_2 = $filename;
                    $home->banner_right_bottom_2 = $banner_right_bottom_2;

                }
            }
            $banner_right_bottom_2_url = isset($_POST["banner_right_bottom_2_url"]) ? $_POST["banner_right_bottom_2_url"] : '';
            $home->banner_right_bottom_2_url = $banner_right_bottom_2_url;

            if (isset($_POST["delete_banner_right_bottom_3"]))
            {
                $banner_right_bottom_3 = '';
                $home->banner_right_bottom_3 = $banner_right_bottom_3;
            }
            else
            {
                if(request()->banner_right_bottom_3)
                {

                    $file = request()->banner_right_bottom_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_bottom_3->move($path, $filename);

                    $banner_right_bottom_3 = $filename;
                    $home->banner_right_bottom_3 = $banner_right_bottom_3;

                }
            }
            $banner_right_bottom_3_url = isset($_POST["banner_right_bottom_3_url"]) ? $_POST["banner_right_bottom_3_url"] : '';
            $home->banner_right_bottom_3_url = $banner_right_bottom_3_url;

            if (isset($_POST["delete_banner_right_bottom_4"]))
            {
                $banner_right_bottom_4 = '';
                $home->banner_right_bottom_4 = $banner_right_bottom_4;
            }
            else
            {
                if(request()->banner_right_bottom_4)
                {

                    $file = request()->banner_right_bottom_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_bottom_4->move($path, $filename);

                    $banner_right_bottom_4 = $filename;
                    $home->banner_right_bottom_4 = $banner_right_bottom_4;

                }
            }
            $banner_right_bottom_4_url = isset($_POST["banner_right_bottom_4_url"]) ? $_POST["banner_right_bottom_4_url"] : '';
            $home->banner_right_bottom_4_url = $banner_right_bottom_4_url;

            if (isset($_POST["delete_banner_right_bottom_5"]))
            {
                $banner_right_bottom_5 = '';
                $home->banner_right_bottom_5 = $banner_right_bottom_5;
            }
            else
            {
                if(request()->banner_right_bottom_5)
                {

                    $file = request()->banner_right_bottom_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_bottom_5->move($path, $filename);

                    $banner_right_bottom_5 = $filename;
                    $home->banner_right_bottom_5 = $banner_right_bottom_5;

                }
            }
            $banner_right_bottom_5_url = isset($_POST["banner_right_bottom_5_url"]) ? $_POST["banner_right_bottom_5_url"] : '';
            $home->banner_right_bottom_5_url = $banner_right_bottom_5_url;

            $banner_right_bottom_google = isset($_POST["banner_right_bottom_google"]) ? $_POST["banner_right_bottom_google"] : '';
            $home->banner_right_bottom_google = $banner_right_bottom_google;

            if (isset($_POST["delete_banner_right_big"]))
            {
                $banner_right_big = '';
                $home->banner_right_big = $banner_right_big;
            }
            else
            {
                if(request()->banner_right_big)
                {

                    $file = request()->banner_right_big;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_big->move($path, $filename);

                    $banner_right_big = $filename;
                    $home->banner_right_big = $banner_right_big;

                }
            }
            $banner_right_big_url = isset($_POST["banner_right_big_url"]) ? $_POST["banner_right_big_url"] : '';
            $home->banner_right_big_url = $banner_right_big_url;

            if (isset($_POST["delete_banner_right_big_2"]))
            {
                $banner_right_big_2 = '';
                $home->banner_right_big_2 = $banner_right_big_2;
            }
            else
            {
                if(request()->banner_right_big_2)
                {

                    $file = request()->banner_right_big_2;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_big_2->move($path, $filename);

                    $banner_right_big_2 = $filename;
                    $home->banner_right_big_2 = $banner_right_big_2;

                }
            }
            $banner_right_big_2_url = isset($_POST["banner_right_big_2_url"]) ? $_POST["banner_right_big_2_url"] : '';
            $home->banner_right_big_2_url = $banner_right_big_2_url;

            if (isset($_POST["delete_banner_right_big_3"]))
            {
                $banner_right_big_3 = '';
                $home->banner_right_big_3 = $banner_right_big_3;
            }
            else
            {
                if(request()->banner_right_big_3)
                {

                    $file = request()->banner_right_big_3;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_big_3->move($path, $filename);

                    $banner_right_big_3 = $filename;
                    $home->banner_right_big_3 = $banner_right_big_3;

                }
            }
            $banner_right_big_3_url = isset($_POST["banner_right_big_3_url"]) ? $_POST["banner_right_big_3_url"] : '';
            $home->banner_right_big_3_url = $banner_right_big_3_url;

            if (isset($_POST["delete_banner_right_big_4"]))
            {
                $banner_right_big_4 = '';
                $home->banner_right_big_4 = $banner_right_big_4;
            }
            else
            {
                if(request()->banner_right_big_4)
                {

                    $file = request()->banner_right_big_4;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_big_4->move($path, $filename);

                    $banner_right_big_4 = $filename;
                    $home->banner_right_big_4 = $banner_right_big_4;

                }
            }
            $banner_right_big_4_url = isset($_POST["banner_right_big_4_url"]) ? $_POST["banner_right_big_4_url"] : '';
            $home->banner_right_big_4_url = $banner_right_big_4_url;

            if (isset($_POST["delete_banner_right_big_5"]))
            {
                $banner_right_big_5 = '';
                $home->banner_right_big_5 = $banner_right_big_5;
            }
            else
            {
                if(request()->banner_right_big_5)
                {

                    $file = request()->banner_right_big_5;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->banner_right_big_5->move($path, $filename);

                    $banner_right_big_5 = $filename;
                    $home->banner_right_big_5 = $banner_right_big_5;

                }
            }
            $banner_right_big_5_url = isset($_POST["banner_right_big_5_url"]) ? $_POST["banner_right_big_5_url"] : '';
            $home->banner_right_big_5_url = $banner_right_big_5_url;

            $banner_right_big_google = isset($_POST["banner_right_big_google"]) ? $_POST["banner_right_big_google"] : '';
            $home->banner_right_big_google = $banner_right_big_google;

            $home->save();

            return Redirect::to('/admin/home_adv');

        })->name('home_adv');

        Route::get('/home_radio', function () {

            $home = Home::first();
            if ($home == null)
            {
                $home = new Home();
                $home->save();
            }
            $home->loadData();

            return view('admin.home_radio',compact('home'));

        })->name('home_radio');


        Route::post('/home_radio', function () {

            $home = Home::first();
            if ($home == null)
                $home = new Home();

            if (isset($_POST["delete_radio1"]))
            {
                $radio1_file = '';
                $home->radio1_file = $radio1_file;
            }
            else
            {
                if(request()->radio1_file)
                {

                    $file = request()->radio1_file;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->radio1_file->move($path, $filename);

                    $radio1_file = $filename;
                    $home->radio1_file = $radio1_file;

                }
            }
            $radio1_url = isset($_POST["radio1_url"]) ? $_POST["radio1_url"] : '';
            $home->radio1_url = $radio1_url;
            $home->radio1_title = isset($_POST["radio1_title"]) ? $_POST["radio1_title"] : '';

            if (isset($_POST["delete_radio2"]))
            {
                $radio2_file = '';
                $home->radio2_file = $radio2_file;
            }
            else
            {
                if(request()->radio2_file)
                {

                    $file = request()->radio2_file;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->radio2_file->move($path, $filename);

                    $radio2_file = $filename;
                    $home->radio2_file = $radio2_file;

                }
            }
            $radio2_url = isset($_POST["radio2_url"]) ? $_POST["radio2_url"] : '';
            $home->radio2_url = $radio2_url;
            $home->radio2_title = isset($_POST["radio2_title"]) ? $_POST["radio2_title"] : '';

            if (isset($_POST["delete_radio3"]))
            {
                $radio3_file = '';
                $home->radio3_file = $radio3_file;
            }
            else
            {
                if(request()->radio3_file)
                {

                    $file = request()->radio3_file;
                    $filename  = time() . '_' . $file->getClientOriginalName();

                    $path = public_path('files');

                    request()->radio3_file->move($path, $filename);

                    $radio3_file = $filename;
                    $home->radio3_file = $radio3_file;

                }
            }
            $radio3_url = isset($_POST["radio3_url"]) ? $_POST["radio3_url"] : '';
            $home->radio3_url = $radio3_url;
            $home->radio3_title = isset($_POST["radio3_title"]) ? $_POST["radio3_title"] : '';

            $home->save();

            return Redirect::to('/admin/home_radio');

        })->name('home_radio');

        Route::get('/news/duplicate/{id}', function ($id) {

            $news = News::findOrFail($id);
            $new_news = $news->replicate();
            $new_news->title .= ' - COPY';
            $new_news->online = false;
            $new_news->save();

            return Redirect::to('/admin/news/' . $new_news->id . "/edit");
        })->name('news.duplicate');

        Route::get('/news/crop', function () {

            return view('news.crop');
        })->name('news.crop');

        Route::post('/news/crop', function () {

            $image = $_POST["imagebase64H"];
            $imageInfo = explode(";base64,", $image);
            $imgExt = str_replace('data:image/', '', $imageInfo[0]);
            $image = str_replace(' ', '+', $imageInfo[1]);
            $imageName = time().".".$imgExt;
            $path = public_path()."/files/news/".$imageName;
            file_put_contents($path, base64_decode($image));

            $imageV = $_POST["imagebase64V"];
            $imageInfoV = explode(";base64,", $imageV);
            $imgExtV = str_replace('data:image/', '', $imageInfoV[0]);
            $imageV = str_replace(' ', '+', $imageInfoV[1]);
            $imageNameV = "V_".time().".".$imgExt;
            $pathV = public_path()."/files/news/".$imageNameV;
            file_put_contents($pathV, base64_decode($imageV));

            if ($_POST["news_id"] > 0)
            {
                $news = News::findOrFail($_POST["news_id"]);
                $news->image = $imageName;
                $news->save();
                return Redirect::to('/admin/news/' . $_POST["news_id"] . "/edit");
            }
            else
                return Redirect::to('/admin/news/create?filename=' . $imageName);

        })->name('news.crop_save');

        Route::get('news/load_json', 'NewsController@load_json')->name('load_json');

        Route::get('news/status/{id}/{status}', function ($id, $status) {

            $n = News::findOrFail($id);
            $n->online = $status == 'online';

            if ($status == 'online')
            {
                if ($n->date <= date("Y-m-d H:i:s"))
                {

                    if ($n->section_position != '')
                    {
                        $s = Section::findOrFail($n->section_id);
                        $s[$n->section_position] = $n->id;
                        $s->save();
                        $n->section_position = '';

                    }
                    if ($n->region_1_position != '')
                    {
                        $s = Section::findOrFail($n->region_1_id);
                        $s[$n->region_1_position] = $n->id;
                        $s->save();
                        $n->region_1_position = '';
                    }
                    if ($n->region_2_position != '')
                    {
                        $s = Section::findOrFail($n->region_2_id);
                        $s[$n->region_2_position] = $n->id;
                        $s->save();
                        $n->region_2_position = '';
                    }
                    $n->save();
                    if (!$n->published)
                    {
                        // $n->notify(new FacebookPost());
                        $n->notify(new TwitterPost());
                        $n->published = true;
                    }

                }
            }
            else
            {

            }

            $n->save();

            return Redirect::to('/admin/news');

        });

        Route::resource('news','NewsController');
        Route::resource('breaking_news','BreakingNewsController');

        Route::get('/sections/sort/{ids}', function ($ids) {

            $idx = explode(",", $ids);
            foreach($idx as $x => $id)
            {
                $s = Section::findOrFail($id);
                $s->position = $x;
                $s->save();
            }

        });

        Route::get('/sections/layout/{id}', function ($id) {

            $section = Section::findOrFail($id);

            if (isset($_GET["layout"]))
            {
                $section->big = '';
                $section->small1 = '';
                $section->small2 = '';
                $section->small3 = '';
                $section->small4 = '';
                $section->small5 = '';
                $section->small6 = '';
                $section->save();
            }

            $section->loadLayout();

            $aAssigned = array();
            if ($section->big != '')
                $aAssigned[] = @$section->big->id;
            if ($section->small1 != '')
                $aAssigned[] = @$section->small1->id;
            if ($section->small2 != '')
                $aAssigned[] = @$section->small2->id;
            if ($section->small3 != '')
                $aAssigned[] = @$section->small3->id;
            if ($section->small4 != '')
                $aAssigned[] = @$section->small4->id;
            if ($section->small5 != '')
                $aAssigned[] = @$section->small5->id;
            if ($section->small6 != '')
                $aAssigned[] = @$section->small6->id;

            $news = News::whereNotIn('id', $aAssigned)->where(function ($q) use ($id) {
                $q->where('section_id', '=', $id)->orWhere('region_1_id', '=', $id)->orWhere('region_2_id', '=', $id);
            })->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();

            return view('sections.layout',compact('section', 'news'));

        })->name('sections.layout');

        Route::post('/sections/layout/{id}', function ($id) {

            $section = Section::findOrFail($id);

            $layout = isset($_POST["layout"]) ? $_POST["layout"] : '';
            $big = isset($_POST["big"]) ? $_POST["big"] : '';
            $small1 = isset($_POST["small1"]) ? $_POST["small1"] : '';
            $small2 = isset($_POST["small2"]) ? $_POST["small2"] : '';
            $small3 = isset($_POST["small3"]) ? $_POST["small3"] : '';
            $small4 = isset($_POST["small4"]) ? $_POST["small4"] : '';
            $small5 = isset($_POST["small5"]) ? $_POST["small5"] : '';
            $small6 = isset($_POST["small6"]) ? $_POST["small6"] : '';

            $aSel = array();
            if (isset($_POST["big"]))
                $aSel[] = $_POST["big"];
            if (isset($_POST["small1"]))
                $aSel[] = $_POST["small1"];
            if (isset($_POST["small2"]))
                $aSel[] = $_POST["small2"];
            if (isset($_POST["small3"]))
                $aSel[] = $_POST["small3"];
            if (isset($_POST["small4"]))
                $aSel[] = $_POST["small4"];
            if (isset($_POST["small5"]))
                $aSel[] = $_POST["small5"];
            if (isset($_POST["small6"]))
                $aSel[] = $_POST["small6"];

            // Riempio i vuoti
            $news = News::whereNotIn('id', $aSel)->where(function ($q) use ($id) {
                $q->where('section_id', '=', $id)->orWhere('region_1_id', '=', $id)->orWhere('region_2_id', '=', $id);
            })->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();

            $idx = 0;

            $section->layout = $layout;
            if ($big == '')
            {
                $section->big = @$news[$idx]->id;
                $idx++;
            }
            else
                $section->big = $big;

            if ($small1 == '')
            {
                $section->small1 = @$news[$idx]->id;
                $idx++;
            }
            else
                $section->small1 = $small1;

            if ($small2 == '')
            {
                $section->small2 = @$news[$idx]->id;
                $idx++;
            }
            else
                $section->small2 = $small2;

            if ($small3 == '')
            {
                $section->small3 = @$news[$idx]->id;
                $idx++;
            }
            else
                $section->small3 = $small3;

            if ($layout == 'layout_3' || $layout == 'layout_4' || $layout == 'layout_5' || $layout == 'layout_7')
            {
                if ($small4 == '')
                {
                    $section->small4 = @$news[$idx]->id;
                    $idx++;
                }
                else
                    $section->small4 = $small4;

                if ($layout == 'layout_4')
                {
                    if ($small5 == '')
                    {
                        $section->small5 = @$news[$idx]->id;
                        $idx++;
                    }
                    else
                        $section->small5 = $small5;

                    if ($small6 == '')
                    {
                        $section->small6 = @$news[$idx]->id;
                        $idx++;
                    }
                    else
                        $section->small6 = $small6;
                }
                else
                {
                    $section->small5 = '';
                    $section->small6 = '';
                }
            }
            else
            {
                $section->small4 = '';
                $section->small5 = '';
                $section->small6 = '';
            }

            $section->save();

            // CLEARLAYOUT
            // $section->clearLayout();

            return Redirect::to('/admin/sections');
        });

        Route::get('/events/layout/{id}', function ($id) {

            $event = Event::findOrFail($id);

            $event->loadLayout();

            $aAssigned = array();
            if ($event->big != '')
                $aAssigned[] = @$event->big->id;
            if ($event->small1 != '')
                $aAssigned[] = @$event->small1->id;
            if ($event->small2 != '')
                $aAssigned[] = @$event->small2->id;
            if ($event->small3 != '')
                $aAssigned[] = @$event->small3->id;
            if ($event->small4 != '')
                $aAssigned[] = @$event->small4->id;



            $news = News::whereNotIn('id', $aAssigned)->where('event_id', '=', $id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();

            return view('events.layout',compact('event', 'news'));

        })->name('events.layout');

        Route::post('/events/layout/{id}', function ($id) {

            $event = Event::findOrFail($id);

            $big = isset($_POST["big"]) ? $_POST["big"] : '';
            $small1 = isset($_POST["small1"]) ? $_POST["small1"] : '';
            $small2 = isset($_POST["small2"]) ? $_POST["small2"] : '';
            $small3 = isset($_POST["small3"]) ? $_POST["small3"] : '';
            $small4 = isset($_POST["small4"]) ? $_POST["small4"] : '';

            $aSel = array();
            if (isset($_POST["big"]))
                $aSel[] = $_POST["big"];
            if (isset($_POST["small1"]))
                $aSel[] = $_POST["small1"];
            if (isset($_POST["small2"]))
                $aSel[] = $_POST["small2"];
            if (isset($_POST["small3"]))
                $aSel[] = $_POST["small3"];
            if (isset($_POST["small4"]))
                $aSel[] = $_POST["small4"];

            $news = News::whereNotIn('id', $aSel)->where('event_id', '=', $id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();

            $idx = 0;

            if ($big == '')
            {
                $event->big = @$news[$idx]->id;
                $idx++;
            }
            else
                $event->big = $big;

            if ($small1 == '')
            {
                $event->small1 = @$news[$idx]->id;
                $idx++;
            }
            else
                $event->small1 = $small1;

            if ($small2 == '')
            {
                $event->small2 = @$news[$idx]->id;
                $idx++;
            }
            else
                $event->small2 = $small2;

            if ($small3 == '')
            {
                $event->small3 = @$news[$idx]->id;
                $idx++;
            }
            else
                $event->small3 = $small3;

            if ($small4 == '')
            {
                $event->small4 = @$news[$idx]->id;
                $idx++;
            }
            else
                $event->small4 = $small4;

            $event->save();

            return Redirect::to('/admin/events');
        });

        Route::get('/sections/to_event/{id}', function ($id) {

            $section = Section::findOrFail($id);

            $event = new Event();
            $event->title = $section->name;
            $event->text_short = '';
            $event->text = '';
            $event->image = '';
            $event->slug = $section->slug;
            $event->online = true;
            $event->save();

            $news = News::where('section_id', '=', $id)->get();
            foreach($news as $n)
            {
                $n->event_id = $event->id;
                $n->section_id = null;
                $n->save();
            }

            $news = News::where('region_1_id', '=', $id)->get();
            foreach($news as $n)
            {
                $n->event_id = $event->id;
                $n->region_1_id = null;
                $n->save();
            }

            $news = News::where('region_2_id', '=', $id)->get();
            foreach($news as $n)
            {
                $n->event_id = $event->id;
                $n->region_2_id = null;
                $n->save();
            }

            $advs = SectionAdv::where('section_id', '=', $id)->get();
            foreach($advs as $adv)
            {
                $adv->section_id = null;
                $adv->save();
            }

            // $section->slug = $section->slug . "_old";
            $section->delete();

            return Redirect::to('/admin/events/' . $event->id . '/edit');

        })->name('sections.to_event');

        Route::resource('sections.advs','SectionAdvController');
        Route::resource('sections','SectionController');

        Route::resource('categories.groups','GroupController');
        Route::resource('categories','CategoryController');

        Route::get('/adv/sort/{ids}', function ($ids) {

            $idx = explode(",", $ids);
            foreach($idx as $x => $id)
            {
                $s = PageAdv::findOrFail($id);
                $s->sort = $x;
                $s->save();
            }

        });

        Route::resource('pages.advs','PageAdvController');
        Route::resource('pages','PageController');

        Route::resource('events.advs','EventAdvController');
        Route::resource('events','EventController');

        Route::get('/calendars/sort/{ids}', function ($ids) {

            $idx = explode(",", $ids);
            foreach($idx as $x => $id)
            {
                $c = Calendar::findOrFail($id);
                $c->position = $x;
                $c->save();
            }

        });

        Route::resource('calendars','CalendarController');

        Route::get('/calendars/archive/{id}', function ($id) {
            $c = Calendar::findOrFail($id);
            $c->archived = true;
            $c->save();
            return Redirect::to('/admin/calendars');
        })->name('calendars.archive');

        Route::get('/calendars/restore/{id}', function ($id) {
            $c = Calendar::findOrFail($id);
            $c->archived = false;
            $c->save();
            return Redirect::to('/admin/calendars');
        })->name('calendars.restore');

        Route::get('/calendars/games/{id}', function ($id) {

            $calendar = CalendarGame::where('calendar_id', '=', $id)->get();;

            $games = array();

            foreach($calendar as $c)
            {
                $games[$c->day . " " . $c->type][] = $c;
            }
            $c = Calendar::findOrFail($id);
            $aRates = $c->getRates();
            $count = 1;
            foreach($aRates as $idx => $r)
            {
                if ($r["penality"] != '')
                {
                    $aRates[$idx]["team"] = $r["team"] . ' ' . str_repeat('*', $count);
                    $aRates[$idx]["penality"] = str_repeat('*', $count) . $r["penality"];
                    $count += 1;
                }
            }

            return view('calendars.games',compact('games', 'aRates'));

        })->name('calendars.games');

        Route::get('/calendars/games/{id}/{day}/{type}', function ($id, $day, $type) {

            $games = CalendarGame::where('calendar_id', '=', $id)->where('day', '=', $day)->where('type', '=', $type)->get();;

            return view('calendars.games_edit',compact('games', 'id', 'day', 'type'));

        })->name('calendars.games_edit');

        Route::post('/calendars/games/{id}/{day}/{type}', function ($id, $day, $type) {

            $games = CalendarGame::where('calendar_id', '=', $id)->where('day', '=', $day)->where('type', '=', $type)->get();;

            foreach($games as $g)
            {
                $date = isset($_POST["date_" . $g->id]) ? $_POST["date_" . $g->id] : '';
                list($day, $month, $year) = explode("/", $date);
                $g->date = $year . "-" . $month . "-" . $day;
                $g->save();
                $home_goals = isset($_POST["home_goals_" . $g->id]) ? $_POST["home_goals_" . $g->id] : '';
                $away_goals = isset($_POST["away_goals_" . $g->id]) ? $_POST["away_goals_" . $g->id] : '';
                $delete = isset($_POST["delete_" . $g->id]) ? true : false;
                if ($delete)
                {
                    $g->played = false;
                    $g->home_goals = null;
                    $g->away_goals = null;
                    $g->home_points = 0;
                    $g->away_points = 0;
                    $g->save();
                }
                else
                {
                    if ($home_goals != '' && $away_goals != '')
                    {
                        $home_points = 0;
                        $away_points = 0;
                        if ($home_goals > $away_goals)
                        {
                            $home_points = 3;
                            $away_points = 0;
                        }
                        else if ($home_goals == $away_goals)
                        {
                            $home_points = 1;
                            $away_points = 1;
                        }
                        else
                        {
                            $home_points = 0;
                            $away_points = 3;
                        }
                        $g->played = true;
                        $g->home_goals = $home_goals;
                        $g->away_goals = $away_goals;
                        $g->home_points = $home_points;
                        $g->away_points = $away_points;
                        $g->save();
                    }
                }

            }

            return Redirect::to('/admin/calendars/games/' . $id);

        });

        Route::resource('seasons','SeasonController');

        Route::resource('teams','TeamController');

        Route::get('/videos/sort/{ids}', function ($ids) {

            $idx = explode(",", $ids);
            foreach($idx as $x => $id)
            {
                $v = Video::findOrFail($id);
                $v->position = $x;
                $v->save();
            }

        });

        Route::resource('videos','VideoController');

        Route::resource('users','UserController');

        Route::get('/load_categories/{type}', function ($type) {

            $categories = Category::where('type', '=', $type)->get();
            return $categories->toJson();

        });

        Route::get('/load_groups/{category}', function ($category) {

            $groups = Group::where('category_id', '=', $category)->get();
            return $groups->toJson();

        });

    });

});

Route::get('/{slug}/elenco', function ($slug) {

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }

    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    $page = Page::where('slug', '=', $slug)->first();
    if ($page != null)
    {

        $section = $page;
        $news = News::where('page_id', '=', $page->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();

        return view('section', compact('home', 'news', 'sections', 'pages', 'section', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aHome'));

    }

});

Route::get('/eventi/{slug}', function ($slug) {

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }

    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    $event = Event::where('slug', '=', $slug)->first();
    if ($event != null)
    {


        $event->loadLayout();
        /*$aAssigned = array();
        if ($event->big != '')
            $aAssigned[] = @$event->big->id;
        if ($event->small1 != '')
            $aAssigned[] = @$event->small1->id;
        if ($event->small2 != '')
            $aAssigned[] = @$event->small2->id;
        if ($event->small3 != '')
            $aAssigned[] = @$event->small3->id;
        if ($event->small4 != '')
            $aAssigned[] = @$event->small4->id;*/


        $elements = News::where('event_id', '=', $event->id)->take(5)->get();

        return view('event', compact('home', 'event', 'elements', 'sections', 'pages', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aHome'));

    }

});

Route::get('/eventi/{slug}/elenco', function ($slug) {

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }

    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    $event = Event::where('slug', '=', $slug)->first();
    if ($event != null)
    {

        $section = $event;
        $news = News::where('event_id', '=', $event->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();
        return view('section', compact('home', 'news', 'sections', 'pages', 'section', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aHome'));

    }

});

Route::get('/{slug}/{slug2}', function ($slug, $slug2) {

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }
    $page = Page::where('slug', '=', $slug)->first();
    if ($page != null)
    {
        $news = News::where('slug', '=', $slug2)->first();
        $clicks = $news->clicks;
        if (!$clicks || $clicks == null)
            $clicks = 0;
        $news->clicks = $clicks + 1;
        $news->save();
        $aImages = array();
        if ($news->image1 != '')
            $aImages[] = $news->image1;
        if ($news->image2 != '')
            $aImages[] = $news->image2;
        if ($news->image3 != '')
            $aImages[] = $news->image3;
        if ($news->image4 != '')
            $aImages[] = $news->image4;
        if ($news->image5 != '')
            $aImages[] = $news->image5;
        $elements = News::where('page_id', '=', $page->id)->where('id', '<>', $news->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->limit(4)->get();
        return view('page', compact('home', 'page', 'elements', 'sections', 'pages', 'news', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aImages', 'regions', 'aHome'));
    }



});

Route::get('/calendario/{name}/{id}', function ($name, $id) {

    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }

    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();

    $calendar_games = CalendarGame::where('calendar_id', '=', $id)->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    $sel = '';
    $games = array();

    $d = '';
    $t = '';
    foreach($calendar_games as $c)
    {
        $games[$c->day . " " . $c->type][] = $c;
        if ($c->date <= date("Y-m-d 00:00:00"))
        {
            $d = $c->day;
            $t = $c->type;
        }
    }

    $c = Calendar::findOrFail($id);
    $aRates = $c->getRates();
    $count = 1;
    foreach($aRates as $idx => $r)
    {
        if ($r["penality"] != '')
        {
            $aRates[$idx]["team"] = $r["team"] . ' ' . str_repeat('*', $count);
            $aRates[$idx]["penality"] = str_repeat('*', $count) . $r["penality"];
            $count += 1;
        }
    }

    $categoryImage = [];
    if ($c->group)
    {
        $categoryImage = array('url' => $c->group->url, "file" => $c->group->image);
    }
    else
    {
        if ($c->category)
            $categoryImage = array('url' => $c->category->url, "file" => $c->category->image);
    }

    return view('calendar', compact('categoryImage', 'home', 'sections', 'pages', 'c',  'games', 'aRates', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aHome', 'd', 't', 'sel'));

});



Route::get('/{slug}', function ($slug) {


    $home = Home::first();
    if ($home != null)
        $home->loadData();

    $aHome = array();
    if ($home->image != '')
    {
        $aHome[] = ['image' => $home->image, 'url' => $home->url];
    }
    if ($home->image_2 != '')
    {
        $aHome[] = ['image' => $home->image_2, 'url' => $home->url_2];
    }
    if ($home->image_3 != '')
    {
        $aHome[] = ['image' => $home->image_3, 'url' => $home->url_3];
    }
    if ($home->image_4 != '')
    {
        $aHome[] = ['image' => $home->image_4, 'url' => $home->url_4];
    }
    if ($home->image_5 != '')
    {
        $aHome[] = ['image' => $home->image_5, 'url' => $home->url_5];
    }
    if (sizeof($aHome) > 0)
    {
        $rnd = rand (0, sizeof($aHome) - 1);
        $home->image = $aHome[$rnd]["image"];
        $home->url = $aHome[$rnd]["url"];
    }

    $pages = Page::where('online', '=', true)->orderBy('title')->get();
    $events = Event::where('online', '=', true)->orderBy('title')->get();
    $sections = Section::orderBy('position')->get();
    $breaking_news = BreakingNews::where('online', '=', true)->orderBy('date', "DESC")->get();
    //if($breaking_news->count() == 0)
    //    $breaking_news = News::where('breaking_news', '=', true)->orderBy('date', "DESC")->get();
    $sections_menu = Section::where('type', '=', 'section')->orderBy('position')->get();
    $regions = Section::where('type', '=', 'region')->orderBy('name')->get();
    $season_id = @Season::where('default', '=', true)->first()->id;
    $cals = Calendar::where('season_id', '=', $season_id)->orderBy('position')->get();

    $calendars = array();
    foreach($cals as $c)
    {

        if ($c->category->grp != '')
        {
            $type = $c->type == 'nation' ? 'Nazionale' : 'Regionale';
            if ($c->group_id > 0)
                $calendars[$type][$c->category->grp][$c->category->name . " - " . $c->group->name] = $c->id;
            else
                $calendars[$type][$c->category->grp][$c->category->name] = $c->id;
        }

    }

    // Controllo se è una sezione o regione, altrimenti news
    $section = Section::where('slug', '=', $slug)->first();
    if ($section != null)
    {

        if ($section->type == 'section')
            $news = News::where('section_id', '=', $section->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->get();
        else
        {
            $news = News::where('online', '=', true)->where(function ($q) use ($section) {
                $q->where('region_1_id', '=', $section->id)->orWhere('region_2_id', '=', $section->id);
            })->orderBy('date', 'DESC')->get();
        }

        return view('section', compact('home', 'news', 'sections', 'pages', 'section', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aHome'));
    }

    $news = News::where('slug', '=', $slug)->first();
    if ($news != null)
    {

        // Controllo se è online altrimenti vado alla home
        if (!$news->online || $news->date > date("Y-m-d H:i:s"))
            return Redirect::to('/');

        $clicks = $news->clicks;
        if (!$clicks || $clicks == null)
            $clicks = 0;
        $news->clicks = $clicks + 1;
        $news->save();
        $aImages = array();
        if ($news->image1 != '')
            $aImages[] = $news->image1;
        if ($news->image2 != '')
            $aImages[] = $news->image2;
        if ($news->image3 != '')
            $aImages[] = $news->image3;
        if ($news->image4 != '')
            $aImages[] = $news->image4;
        if ($news->image5 != '')
            $aImages[] = $news->image5;
        $elements = News::where('section_id', '=', $news->section_id)->where('id', '<>', $news->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->limit(5)->get();

        // Se la news è associata ad una pagina, carico gli advs di quella pagina
        $advs = array();
        if ($news->page_id > 0)
        {
            $page = $news->page;
            $advs = $news->page->getAdvs();
            $elements = News::where('page_id', '=', $news->page_id)->where('id', '<>', @$news->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->limit(4)->get();
            return view('page', compact('home', 'page', 'elements', 'sections', 'pages', 'news', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aImages', 'aHome', 'advs'));
        }
        else
            return view('news', compact('home', 'news', 'elements', 'sections', 'pages', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aImages', 'aHome', 'advs'));
    }

    $page = Page::where('slug', '=', $slug)->first();
    if ($page != null)
    {
        $news = News::where('page_id', '=', $page->id)->where('online', '=', true)->orderBy('date', 'DESC')->first();

        $aImages = array();
        if ($news)
        {
            if ($news->image1 != '')
                $aImages[] = $news->image1;
            if ($news->image2 != '')
                $aImages[] = $news->image2;
            if ($news->image3 != '')
                $aImages[] = $news->image3;
            if ($news->image4 != '')
                $aImages[] = $news->image4;
            if ($news->image5 != '')
                $aImages[] = $news->image5;
        }

        $elements = News::where('page_id', '=', $page->id)->where('id', '<>', @$news->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->limit(4)->get();
        // $news = $elements->first();

        $advs = $page->getAdvs();

        return view('page', compact('home', 'page', 'elements', 'sections', 'pages', 'news', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aImages', 'aHome', 'advs'));
    }

    /*$event = Event::where('slug', '=', $slug)->first();
    if ($event != null)
    {
        $event->loadLayout();
        $aAssigned = array();
        if ($event->big != '')
            $aAssigned[] = @$event->big->id;
        if ($event->small1 != '')
            $aAssigned[] = @$event->small1->id;
        if ($event->small2 != '')
            $aAssigned[] = @$event->small2->id;
        if ($event->small3 != '')
            $aAssigned[] = @$event->small3->id;
        if ($event->small4 != '')
            $aAssigned[] = @$event->small4->id;
        $elements = News::whereNotIn('id', $aAssigned)->where('event_id', '=', $event->id)->where('online', '=', true)->where('date', '<=', date("Y-m-d H:i:s"))->orderBy('date', 'DESC')->limit(5)->get();
        return view('event', compact('home', 'event', 'elements', 'sections', 'pages', 'sections_menu', 'regions', 'events', 'breaking_news', 'sections_menu', 'calendars', 'aHome'));
    }*/

});
