<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/


Route::get('/', function()
{
    $gesehen = Film::zuletztGesehen()->get();
    $abgelehnt = Film::zuletztAbgelehnt()->get();
    $vorgeschlagen = Film::neuesteVorschlage()->get();
    $mg = Film::meistgewunschteVorschlage()->take(5)->get();
    //$x = DB::getQueryLog();
    //dd(end($x));

    $news = News::aktuell()->get();
    $nextfilm = Dumbo::find(1)->film;

    $tmdb = new TMDb(Config::get('constants.tvdb.apikey'), 'de', TRUE, TMDb::API_SCHEME_SSL);
    foreach(array("top" => $mg[0], "neu" => $vorgeschlagen[0], "alt" => $gesehen[0], "declined" => $abgelehnt[0]) as $key => $val) {
        $tmovie = $tmdb->getMovie($val->tvdbid);
        $images[$key] = $tmdb->getImageUrl($tmovie['poster_path'], TMDb::IMAGE_POSTER, 'w342');
    }

    if(is_object($nextfilm)) {
        $tmovie = $tmdb->getMovie($nextfilm->tvdbid);
        $images["next"] = $tmdb->getImageUrl($tmovie['poster_path'], TMDb::IMAGE_POSTER, 'w342');
    } else {
        $images["next"] = "img/no-poster-w92.jpg";
    }

    $kommentare = Comment::neueste()->get();

    $labels = array("", "danger", "danger", "warning", "warning", "info", "info", "primary", "primary", "success", "success");

    return View::make('index')
        ->with('gesehen', $gesehen)
        ->with('abgelehnt', $abgelehnt)
        ->with('vorgeschlagen', $vorgeschlagen)
        ->with('meistgw', $mg)
        ->with('images', $images)
        ->with('news', $news)
        ->with('kommentare', $kommentare)
        ->with('labels', $labels)
        ->with('nextfilm', $nextfilm);
});

Route::get('film/{id}', array('as' => 'film', function($id) {
    $film = Film::findOrFail($id);

    $tmdb = new TMDb('b187f8d9c5e72b1faecb741d5d04239a', 'de', TRUE);
    $tmovie = $tmdb->getMovie($film->tvdbid);
    $tcast = $tmdb->getMovieCast($film->tvdbid);
    $ttrail = $tmdb->getMovieTrailers($film->tvdbid);
    $image = $tmdb->getImageUrl($tmovie['poster_path'], TMDb::IMAGE_POSTER, 'w342');

    $votes = $film->votes()->count();
    $vposi = $film->votes()->where('stimme', true)->count();

    $pv = array();
    foreach($film->votes()->where('stimme', true)->get() as $v) {
        $pv[] = $v->voter;
    }

    $nv = array();
    foreach($film->votes()->where('stimme', false)->get() as $v) {
        $nv[] = $v->voter;
    }

    if(!is_null(Auth::user()) && $film->votes()->where('user', Auth::user()->id)->count() > 0) {
        $uvote[0] = true;
        $uvote[1] = $film->votes()->where('user', Auth::user()->id)->first()->stimme;
    } else {
        $uvote[0] = false;
    }


    $comments = $film->comments()->orderBy('id', 'DESC')->get();


    $labels = array("", "danger", "danger", "warning", "warning", "info", "info", "primary", "primary", "success", "success");

    return View::make('film')
        ->with('film', $film)
        ->with('tfilm', $tmovie)
        ->with('poster', $image)
        ->with('comments', $comments)
        ->with('cast', $tcast)
        ->with('trail', $ttrail)
        ->with('votes', $votes)
        ->with('uvote', $uvote)
        ->with('pv', $pv)
        ->with('nv', $nv)
        ->with('vposi', $vposi)
        ->with('labels', $labels)
        ->with('tmdb', $tmdb);
}));

Route::get('vote/{stimme}/{user}/{film}', function($stimme, $user, $film) {
    $v = Vote::where('user', $user)->where('film', $film)->first();

    if(!is_null($v)) {
        $v->stimme = $stimme == "yes" ? true : false;
    } else {
        $v = new Vote();
        $v->user = $user;
        $v->film = $film;
        $v->stimme = $stimme == "yes" ? true : false;
    }

    $v->save();

    return Redirect::to('film/' . $film);
});

Route::post('comment', array('as' => 'comment', function() {
    $c = new Comment();
    $c->film = Input::get('film');
    $c->user = Input::get('user');
    $c->text = Input::get('text');
    $c->bewertung = !is_null(Input::get('rate')) ? Input::get('rate') : 0;
    $c->save();
    return Redirect::to('film/' . Input::get('film'));
}));

Route::post('comment/edit', array('as'=> 'modcomment', function () {
    $c = Comment::findOrFail(Input::get('id'));
    $c->text = Input::get('text');
    $c->bewertung = Input::get('rate');
    $c->save();
    return Redirect::to('film/' . $c->film);
}));

Route::get('login', array('as' => 'login', function() {
    return View::make('login');
}));

Route::post('login', function() {
    $userdata = array(
        'name' => Input::get('user'),
        'password' => Input::get('password'));
    if(Auth::attempt($userdata, true)) {
        return Redirect::intended('/');
    } else {
        echo "Login gescheitert.";
        var_dump($userdata);
        return Redirect::to('login')
            ->with('login_errors', true);
    }
});

Route::get('logout', array('as' => 'logout', function() {
    Auth::logout();
    return Redirect::to('/');
}));

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

    $filme = Film::meistgewunschteVorschlage()->paginate(25);

    return View::make('suggest')
        ->with('filme', $filme)
        ->with('titel', 'Vorschl&auml;ge nach Wertung');

});

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

    $filme = DB::table(DB::raw('film_films'))
        ->select(DB::raw('film_films.*, COUNT(case when film_votes.stimme IS TRUE then 1 end) as upvotes,
		COUNT(case when film_votes.stimme IS FALSE then 1 end) as downvotes,
		COUNT(case when film_votes.stimme IS TRUE then 1 end) as vcount'))
        ->leftJoin('votes', 'votes.film', '=', 'films.id')
        ->leftJoin('users', 'users.id', '=', 'votes.user')
        ->whereNull('films.gesehen')
        ->whereNull('films.abgelehnt')
        ->where('users.settings', 'NOT LIKE', '%disabled":true%')
        ->groupBy('id')
        ->orderBy('vorgeschlagen', 'DESC')
        ->paginate(25);

    return View::make('suggest')
        ->with('filme', $filme)
        ->with('titel', 'Vorschl&auml;ge nach Datum');

});

Route::get('abgelehnt/{field?}/{order?}', function($field = "abgelehnt", $order = "desc") {
    $filme = Film::whereNotNull('abgelehnt')->orderBy($field, $order)->paginate(25);
    $labels = array("", "danger", "danger", "warning", "warning", "info", "info", "primary", "primary", "success", "success");

    return View::make('abgelehnt')
        ->with('labels', $labels)
        ->with('filme', $filme);

})->where(array('field' => '[a-z]+', 'order' => 'asc|desc'));

Route::get('gesehen/{field?}/{order?}', function($field = "gesehen", $order = "desc") {
    $filme = Film::whereNotNull('gesehen')->orderBy($field, $order)->paginate(25);
    $labels = array("", "danger", "danger", "warning", "warning", "info", "info", "primary", "primary", "success", "success");

    return View::make('seen')
        ->with('labels', $labels)
        ->with('filme', $filme);

})->where(array('field' => '[a-z]+', 'order' => 'asc|desc'));

Route::get('neu', array('before' => 'auth', function() {

    return View::make('new');

}));

Route::post('neu', array('before' => 'auth', function() {
    $tmdb = new TMDb('b187f8d9c5e72b1faecb741d5d04239a', 'de', TRUE);
    $r = $tmdb->searchMovie(Input::get('search'));

    return View::make('new')->with('result', $r)->with('tmdb', $tmdb);
}));

Route::get('vorschlag/{id}', array('before' => 'auth', function($id) {
    $ef = Film::where('tvdbid', '=', $id)->whereNull('gesehen')->whereNull('abgelehnt')->first();
    if(is_null($ef)) {
        $tmdb = new TMDb('b187f8d9c5e72b1faecb741d5d04239a', 'de', TRUE);
        $f = $tmdb->getMovie($id);
        $film = new Film();
        $film->name = $f['title'];
        $film->tvdbid = $id;
        $film->vorgeschlagen = \Carbon\Carbon::today();
        $film->user = Auth::user()->id;
        $film->save();
        Session::put('message', 'Film hinzugefügt.');
        return Redirect::to('film/' . $film->id);
    } else {
        if(is_null($ef->abgelehnt)) {
            Session::put('message', 'Film bereits vorgeschlagen von ' . $ef->besitzer->name . '.');
        } else {
            Session::put('message', 'Film bereits abgelehmt.'); 
        }
        return Redirect::to('film/' . $ef->id);
    }
}));

Route::get('mark-declined/{id}', array('before' => 'auth', function($id) {
    $film = Film::findOrFail($id);
    $film->abgelehnt = \Carbon\Carbon::today();
    $film->save();
    if(Dumbo::find(1)->nextfilm == $film->id) {
        $system = Dumbo::findOrFail(1);
        $system->nextfilm = 0;
        $system->save();
    }
    return Redirect::to('film/' . $film->id);
}));

Route::get('mark-read/{id}', array('before' => 'auth', function($id) {
    $film = Film::findOrFail($id);
    $film->gesehen = \Carbon\Carbon::today();
    $film->save();
    if(Dumbo::find(1)->nextfilm == $film->id) {
        $system = Dumbo::findOrFail(1);
        $system->nextfilm = 0;
        $system->save();
    }
    return Redirect::to('film/' . $film->id);
}));

Route::get('view-next/{id}', array('before' => 'auth', function($id) {
    $system = Dumbo::findOrFail(1);
    $system->nextfilm = $id;
    $system->save();
    return Redirect::to('film/' . $id);
}));

Route::get('register', function() {
    return View::make('register');
});

Route::post('register', function() {
    $vrules = array(
        'name' => 'required|unique:users',
        'email' => 'required|email',
        'password' => 'required|confirmed',
        'fire' => array('required', 'regex:/^Kreis$/i')
    );

    $vfields = array(
        'name' => Input::get('user'),
        'email' => Input::get('email'),
        'password' => Input::get('password'),
        'password_confirmation' => Input::get('pw-confirm'),
        'fire' => Input::get('fire')
    );

    $val = Validator::make($vfields, $vrules);

    if($val->fails()) {
        return View::make('register')->with('errors', $val->messages());
    } else {
        $u = new User();
        $u->name = Input::get('user');
        $u->email = Input::get('email');
        $u->password = Hash::make(Input::get('password'));
        $u->save();
        return Redirect::to('/')->with('message', 'Registriert!');
    }
});

Route::get('settings', array('before' => 'auth', function() {
    return View::make('settings');
}));

Route::post('settings/{mode}', array('before' => 'auth', function($mode) {
    Validator::extend('pass', function($attribute, $value, $parameters) {
        return Hash::check($value, Auth::user()->password);
    });
    if($mode == 'password') {
        var_dump(Hash::check(Input::get('oldpw'), Auth::user()->password));
        $vfields = array('oldpw' => Input::get('oldpw'), 'newpw' => Input::get('newpw'), 'newpw_confirmation' => Input::get('newpw2'));
        $vrules = array( 'oldpw' => 'required|pass', 'newpw' => 'required|confirmed' );
        $val = Validator::make($vfields, $vrules);
        if($val->passes()) {
            $u = Auth::user();
            $u->password = Hash::make(Input::get('newpw'));
            $u->save();
            return View::make('settings')->with('message', 'Passwort geändert.');
        } else {
            return View::make('settings')->with('errors', $val->messages());
        }
    }

    if($mode == 'email') {
        $vfields = array('pw' => Input::get('pw'), 'email' => Input::get('email'), 'email_confirmation' => Input::get('email2'));
        $vrules = array('pw' => 'required|pass', 'email' => 'required|confirmed');
        $val = Validator::make($vfields,  $vrules);
        if($val->passes()) {
            $u = Auth::user();
            $u->email = Input::get('email');
            $u->save();
            return View::make('settings')->with('message', 'Email geändert.');
        } else {
            return View::make('settings')->with('errors', $val->messages());
        }
    }

    if($mode == 'avatar-reset') {
        /** @var User $u */
        $u = Auth::user();
        $u->setSetting('avatar', false);
        $u->save();

        /* Delete old Avatars */
        array_map('unlink', glob(public_path("img/avatars/". Auth::user()->id . "-*")));
        return View::make('settings')->with('message', 'Avatar gelöscht.');
    }

    if($mode == 'avatar-upload') {
        $vfields = array('avatar' => Input::file('avatar'));
        $vrules = array('avatar' => 'required|image|max:5000');
        $val = Validator::make($vfields, $vrules);
        if($val->passes()) {
            /* Delete old Avatars */
            //array_map('unlink', glob(public_path("img/avatars/". Auth::user()->id . "-*")));

            /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
            $file = Input::file('avatar');
            $file = $file->move( public_path("img/avatars/"), Auth::user()->id . "-". Str::slug($file->getFilename()) . "." . $file->guessExtension() );

            exec('/usr/bin/gm convert -size 100x100 ' . $file->getRealPath() . ' -thumbnail 100x100^ -gravity center -extent 100x100 +profile "*" ' . $file->getRealPath());

            //$i = new Imagick();
            //$i->readImage($file->getRealPath());
            //$i->cropThumbnailImage(100, 100);
            //$i->writeImage();

            /** @var User $u */
            $u = Auth::user();
            $u->setSetting('avatar', $file->getFilename());
            $u->save();
            return View::make('settings')->with('message', 'Avatar gespeichert.');
        } else {
            return View::make('settings')->with('errors', $val->messages());
        }
    }
}));

Route::get('users', array('before' => 'auth', function() {
    if(Auth::user()->admin) {
        $u = User::orderBy('name')->paginate();

        return View::make('users')->with('users', $u);
    } else {
        App::abort(401, 'Diese Seite ist nicht für Dich.');
    }
}));

Route::get('users/{operation}/{id}', array('before' => 'auth', function($operation, $id) {
    if(!Auth::user()->admin) App::abort(401, 'Diese Seite ist nicht für Dich.');
    /** @var User $u */
    $u = User::findOrFail($id);
    switch($operation) {
        case 'mkadm':
            $u->admin = true;
            $u->save();
            $msg = $u->name . " ist jetzt ein Admin.";
            break;
        case 'rmadm':
            $u->admin = false;
            $u->save();
            $msg = $u->name . " ist kein Admin mehr.";
            break;
        case 'rmusr':
            $msg = $u->name . " wurde gelöscht.";
            $u->delete();
            break;
        case 'inact':
            $msg = $u->name. " ist inaktiv.";
            $u->setSetting("disabled",  true);
            $u->save();
            break;
        case 'act':
            $msg = $u->name. " ist aktiv.";
            $u->setSetting("disabled",  false);
            $u->save();
            break;
    }

    return Redirect::to('users')->with('message', $msg);
}));


Route::get('news', array('before' => 'auth',  function() {
    return View::make('news');
}));

Route::post('news', array('before' => 'auth', function() {
    $vrules = array(
        'headline' => 'required',
        'body' => 'required'
    );

    $vfields = array(
        'headline' => Input::get('headline'),
        'body' => Input::get('body')
    );

    $val = Validator::make($vfields, $vrules);

    if($val->fails()) {
        return View::make('news')->with('errors', $val->messages());
    } else {
        $n = new News();
        $n->author = Auth::user()->id;
        $n->headline = Input::get('headline');
        $n->body = Input::get('body');
        $n->save();
        return Redirect::to('/')->with('message', 'News erstellt!');
    }
}));

Route::get('passwort-vergessen', function() {
    return View::make('pwform');
});

Route::post('passwort-vergessen', function() {
    $credentials = array('email' => Input::get('email'));
    return Password::remind($credentials, function($message, $user) {
        $message->subject('Passwort für Dumbo zurücksetzen.');
    });
});

Route::get('passwort-reset/{token}', function($token) {
    return View::make('pwreset')->with('token', $token);
});

Route::post('passwort-reset', function() {
    $credentials = array(
        'email' => Input::get('email'),
        'password' => Input::get('password'),
        'password_confirmation' => Input::get('password_confirmation')
    );

    return Password::reset($credentials, function($user, $password) {
        $user->password = Hash::make($password);

        $user->save();

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

Route::get('stats', function() {
    $stats = [
        array(
            'name' => 'Meiste Vorschl&auml;ge',
            'entr' => array('Vorschlag', 'Vorschl&auml;ge'),
            'vals' => Film::addSelect(DB::raw("film_films.*, COUNT(`id`) as count"))
                ->groupBy('user')->orderBy('count', 'DESC')->take(3)->get(),
            'prop' => 'besitzer',
            'type' => 'User'
        ),

        array(
            'name' => 'Meiste angenommene Vorschl&auml;ge',
            'entr' => array('Vorschlag', 'Vorschl&auml;ge'),
            'vals' => Film::addSelect(DB::raw("film_films.*, COUNT(`id`) as count"))
                ->whereNotNull('gesehen')->groupBy('user')->orderBy('count', 'DESC')->take(3)->get(),
            'prop' => 'besitzer',
            'type' => 'User'
        ),
        array(
            'name' => 'Meiste abgelehnte Vorschl&auml;ge',
            'entr' => array('Vorschlag', 'Vorschl&auml;ge'),
            'vals' => Film::addSelect(DB::raw("film_films.*, COUNT(`id`) as count"))
                ->whereNotNull('abgelehnt')->groupBy('user')->orderBy('count', 'DESC')->take(3)->get(),
            'prop' => 'besitzer',
            'type' => 'User'
        ),

        array(
            'name' => 'Meiste Kommentare',
            'entr' => array('Kommentar', 'Kommentare'),
            'vals' => Comment::addselect(DB::raw('film_comments.*, COUNT(`id`) as count'))
                ->where('text', '!=', '')->groupBy('user')->orderBy('count', 'DESC')->take(3)->get(),
            'prop' => 'autor',
            'type' => 'User'
        ),

        array(
            'name' => 'Meiste Bewertungen',
            'entr' => array('Bewertung', 'Bewertungen'),
            'vals' => Comment::addselect(DB::raw('film_comments.*, COUNT(`id`) as count'))
                ->where('bewertung', '!=', 0)->groupBy('user')->orderBy('count', 'DESC')->take(3)->get(),
            'prop' => 'autor',
            'type' => 'User'
        ),

        array(
            'name' => 'Bewertet am besten',
            'entr' => array('', ''),
            'vals' => Comment::addselect(DB::raw('film_comments.*, ROUND(AVG(`bewertung`),1) as count, COUNT(*) as no'))
                ->where('bewertung', '!=', 0)->groupBy('user')->orderBy('count', 'DESC')->orderBy('no', 'DESC')->take(3)->get(),
            'prop' => 'autor',
            'type' => 'User'
        ),
        array(
            'name' => 'Bewertet am schlechtesten',
            'entr' => array('', ''),
            'vals' => Comment::addselect(DB::raw('film_comments.*, ROUND(AVG(`bewertung`),1) as count, COUNT(*) as no'))
                ->where('bewertung', '!=', 0)->groupBy('user')->orderBy('count', 'ASC')->orderBy('no', 'ASC')->take(3)->get(),
            'prop' => 'autor',
            'type' => 'User'
        ),
        array(
            'name' => 'Meiste Filme wider Willen gesehen',
            'entr' => array('Film', 'Filme'),
            'vals' => Vote::addSelect(DB::raw('film_films.*, film_votes.*, COUNT(*) as count'))
                ->leftJoin('films', 'films.id', '=', 'votes.film')->whereNotNull('gesehen')
                ->whereRaw('stimme IS FALSE')->groupBy('votes.user')->orderBy('count', 'DESC')
                ->take(3)->get(),
            'prop' => 'voter',
            'type' => 'User'
        ),
        array(
            'name' => 'Unbeliebtester Film',
            'entr' => array('Stimme', 'Stimmen'),
            'prop' => 'oFilm',
            'type' => 'Film',
            'vals' => Vote::addSelect(DB::raw('film_votes.*, film_films.*, COUNT(*) as count'))
                ->leftJoin('films', 'films.id', '=', 'votes.film')
                ->whereRaw('stimme IS FALSE')->groupBy('film')->orderBy('count', 'DESC')
                ->take(3)->get()
        ),
        array(
            'name' => 'Schlechtbewertetster Film',
            'entr' => array('', ''),
            'prop' => 'objekt',
            'type' => 'Film',
            'vals' => Comment::addSelect(DB::raw('film_comments.*, film_films.*, ROUND(AVG(`bewertung`),1) as count'))
                ->leftJoin('films', 'films.id', '=', 'comments.film')->whereNotNull('gesehen')
                ->where('bewertung', '>', 0)->groupBy('film')->orderBy('count', 'ASC')
                ->take(3)->get()
        ),
        array(
            'name' => 'Bestbewertetster Film',
            'entr' => array('', ''),
            'prop' => 'objekt',
            'type' => 'Film',
            'vals' => Comment::addSelect(DB::raw('film_comments.*, film_films.*, ROUND(AVG(`bewertung`),1) as count'))
                ->leftJoin('films', 'films.id', '=', 'comments.film')->whereNotNull('gesehen')
                ->where('bewertung', '>', 0)->groupBy('film')->orderBy('count', 'DESC')
                ->take(3)->get()
        ),
    ];

    return View::make('stats')->with('stats', $stats);
});
