<?php

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;

class FrontEndController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('@isBand', array('only' => 'reserved'));
        $this->beforeFilter('@status');
        View::share('displayNav', Contest::hasBegun() || Contest::inTeaser());
        Asset::json('messages', trans('js'));

        Asset::json('status', Contest::status());
        Asset::json('edition', Contest::getEdition());

        switch (Contest::getEdition()) {
            case 'pt-BR':
                $edpLogo = url('/assets/img/logo-edp-br.png');
                break;
            case 'es':
                $edpLogo = url('/assets/img/logo-edp-es.png');
                break;
            default:
            $edpLogo = url('/assets/img/logo-edp-pt.png');
                break;
        }
        View::share('edpLogo', $edpLogo);


        //        $addThisLangs = [
        //            'pt' => 'pt',
        //            'pt-BR' => 'pt',
        //            'es' => 'es',
        //        ];
        //        $addThisLang = $addThisLangs[Contest::getEdition()];
        //        View::share('addThisLang', $addThisLang);
        View::share('editionUrls', Contest::editionUrls(Contest::getEdition()));
        View::share('status', Contest::status());
        //        $environment = App::environment();
        //        if ($environment === 'production') {
        //
        //            if (!Contest::hasBegun() && Contest::getEdition() == 'es') {
        //                exit();
        //            }
        //        }
    }

    public function isBand()
    {
        if (!BandAuth::check()) {
            return Redirect::to(route('home'));
        }
    }

    public function status()
    {




        $winner = false;
        $has_shortlist = false;
        $has_finalists = false;

        if (Contest::hasEnded()) {

            $winner = Band::with('votes')->ofType('approved')->where('winner', true)->first();

            if (Contest::getDate('show-finalists')->isPast()) {
                $has_finalists = (bool) Band::ofType('approved')->where('final', true)->first();
            }
        }

        if (Contest::getDate('show-semi-finalists')->isPast() && Band::ofType('approved')->where('shortlist', true)->first()) {
            $has_shortlist = true;
        }

        View::share('winner', $winner);
        View::share('has_shortlist', $has_shortlist);
        View::share('has_finalists', $has_finalists);
    }

    public function topBands()
    {
        if (Contest::votingHasClosed() || is_null(Vote::first())) {
            return false;
        }

        return Band::with('votes')
            ->ofType('approved')
            ->join('votes', 'votes.band_id', '=', 'bands.id')
            ->select('bands.*', DB::raw('count(`votes`.`band_id`) as `votes_count`'))
            ->groupBy('votes.band_id')
            ->orderBy('votes_count', 'desc')
            ->orderBy('bands.created_at', 'asc')
            ->take(10)
            ->get();
    }

    public function home()
    {


        //if in the the teaser stage, display it instead
        if (Contest::inTeaser()) {
            date_default_timezone_set('Europe/Lisbon');
            $endTeaserParam = Contest::getContestOption('date_end_teaser');
            $endTeaserDate = new Carbon($endTeaserParam);
            $endTeaserDate->setTimezone('Europe/Lisbon');
            $endTeaserDate = $endTeaserDate->diffInSeconds(\Carbon\Carbon::now('Europe/Lisbon'));
            $remaining = $endTeaserDate;
            $params = [
                'remaining' => $remaining,
            ];
            Asset::json('endTeaser', $endTeaserDate);
            Asset::json('endTeaserParam', $endTeaserParam);

            Asset::json('endTeaserLanguage', [
                'portugal' => 'Portuguese',
                'espana' => 'Spanish',
                'brasil' => 'Portuguese',
            ][($_REQUEST['lang'] ?? 'portugal')] ?? 'English'); // TODO: use CURRENT_LANGUAGE on the merge

            return View::make('teaser', $params);
        }
        $latest_bands = Band::with('votes')
            ->ofType('approved')
            ->orderBy('created_at', 'desc')
            ->take(10)
            ->get();


        $top_bands = $this->topBands();

        return View::make('home', compact('latest_bands', 'top_bands'));
    }

    public function contest()
    {
        return View::make('contest');
    }

    public function pastEditions($year)
    {
        $edition = Contest::getEdition();


        return View::make('past-editions', compact('year', 'edition'));
    }

    public function participate()
    {
        $band = new Band;
        $adminOverride = false;
        Asset::json('participate', array(
            'url' => route('post-participate')
        ));
        $discoverMethods = array(
            'Facebook' => 'Facebook',
            'Instagram' => 'Instagram',
            'Twitter' => 'Twitter',
            'Youtube' => 'Youtube',
            'Google' => 'Google',
            'E-mail marketing' => 'E-mail marketing',
            'Amigos' => 'Amigos',
            'Site' => 'Site',
            'Cartaz/folheto' => 'Cartaz/folheto',
            'Outro' => 'Outro',
        );
        return View::make('participate', compact('band', 'discoverMethods', 'adminOverride'));
    }

    public function adminParticipate()
    {
        $band = new Band;
        $adminUser = Sentry::getUSer();
        $admin = Sentry::findGroupByName('Administrators');
        $body_class = 'participate';
        if (!$adminUser->inGroup($admin)) {
            die('Forbidden');
        }

        $status = 'participate';
        Asset::json('participate', array(
            'url' => route('post-participate')
        ));
        $adminOverride = true;
        $discoverMethods = array(
            'Facebook' => 'Facebook',
            'Instagram' => 'Instagram',
            'Twitter' => 'Twitter',
            'Youtube' => 'Youtube',
            'Google' => 'Google',
            'E-mail marketing' => 'E-mail marketing',
            'Amigos' => 'Amigos',
            'Site' => 'Site',
            'Cartaz/folheto' => 'Cartaz/folheto',
            'Outro' => 'Outro',
        );
        return View::make('participate', compact('band', 'discoverMethods', 'adminOverride', 'body_class', 'status'));
    }

    public function vote()
    {
        $paginate = true; // If pagination is optional, set to false

        $bands = Band::with('votes', 'semiFinalVotes')->ofType('approved');

        if (Contest::hasEnded()) {

            // If there are finalists, filter only finalists, except when winner has been chosen
            if (Contest::getDate('show-finalists')->isPast() && Band::ofType('approved')->orWhere('final', true)->first()) {
                if (!Band::with('votes')->ofType('approved')->where('winner', true)->first()) {
                    $bands->where('final', true);
                }
            } else {
                $bands->where('shortlist', true);
            }
        } elseif (Contest::getDate('show-semi-finalists')->isPast()) {


            // If shortlist has been created, filter only shortlist entries
            if (Band::ofType('approved')->where('shortlist', true)->first()) {
                $bands->where('shortlist', true);
            }
        } else {
            $paginate = true;
        }

        $search = Input::get('pesquisa');
        if ($search) {
            $bands->where('name', 'like', "%{$search}%");
        }

        $bands->orderBy('name', 'asc');

        $bands = $paginate ? $bands->paginate(12) : $bands->get();

        $route = (Route::getCurrentRoute()->getName());

        $bands->setBaseUrl(route($route));

        return View::make('vote', compact('bands', 'paginate'));
    }

    public function band($slug, $token = false)
    {
        if ($token) {
            $voter = Voter::where('token', $token)->first();
            if ($voter) {

                Auth::loginUsingId($voter->id);

                return Redirect::to(route('band', array('slug' => $slug)));
            }
        }

        $band = Band::with('votes', 'semiFinalVotes')
            ->ofType('approved')
            ->where('slug', $slug)
            ->first();

        if (!$band) {

            return App::abort(404);
        }

        Session::put('viewing_band', $band->id);

        $top_bands = $this->topBands();

        if (Session::has('fail')) {
            Asset::json('vote', array(
                'result' => 'error',
            ));
        }

        if (Auth::check()) {
            $votes = Contest::status() === 'semi-final' ? $band->semiFinalVotes : $band->votes;
            $votes = $votes->lists('voter_id');
        }

        //changing the text just for the spanish versions.
        //Quick fix is to change the band bio for display
        $bio = substr($band->bio, 0, 160);
        if (\Support\Facades\Contest::getEdition() == 'es') {
            $strBio = "Conoce al grupo " . $band->name . " en el concurso musical #EDPLiveBands.
                        EDP, la energía oficial de la música.
                        ¡Entra y vota! ";
            $bio = $strBio;
        }
        View::share('bio', $bio);


        return View::make('band', compact('band', 'top_bands', 'votes'));
    }

    public function faqs()
    {
        return View::make('faqs');
    }

    public function reserved()
    {
        $band = BandAuth::user();

        return View::make('reserved', compact('band'));
    }
}
