<?php
use Carbon\Carbon;
class DashboardController extends AdminController
{
    public function index()
    {
        $settings = LSetting::getSettings();

        try {
            $siteID = Analytics::getSiteIdByUrl(url());

            $totalWebsites = LStats::getTotalWebsitesCount();
            $todayAnalyzedWebsite = LStats::getTodayAnalyzedWebsitesCount();
            $todayUniqueVisitors  = LStats::getTodayUniqueVisitors($siteID);
            $todayPageviews = LStats::getTodayPageviews($siteID);
            $visitData = LStats::getLastMonthVisitors($siteID);
            $pageviewData = LStats::getLastMonthPageViews($siteID);
            $browsers = LStats::getLastMonthBrowsers($siteID);
            $os = LStats::getLastMonthOs($siteID);
            $screens = LStats::getLastMonthScreens($siteID);
            $keywords = LStats::getLastMonthKeywords($siteID);
            $cities = LStats::getLastMonthCities($siteID);
            $referers = LStats::getLastMonthReferers($siteID);
            $totalVisitors = LStats::getTotalVisitors($siteID);
            $totalPageviews = LStats::getTotalPageviews($siteID);



            $visits = [];
            $pageviews = [];
            $days = [];
            if($visitData){
                foreach($visitData as $key => $visit){
                    $visits[] = $visit[1];
                    $days[] = substr($visit[0],6,2). '-' . substr($visit[0],4,2). '-' . substr($visit[0],0,4);
                    $pageviews[] = $pageviewData[$key][1];
                }
            }

            return View::make('admin.dashboard.index')
                ->with('totalWebsites', $totalWebsites)
                ->with('todayAnalyzedWebsite', $todayAnalyzedWebsite)
                ->with('todayUniqueVisitors', $todayUniqueVisitors)
                ->with('todayPageviews', $todayPageviews)
                ->with('days', $days)
                ->with('visits', $visits)
                ->with('pageviews', $pageviews)
                ->with('browsers', $browsers)
                ->with('os', $os)
                ->with('screens', $screens)
                ->with('keywords', $keywords)
                ->with('cities', $cities)
                ->with('referers', $referers)
                ->with('totalVisitors', $totalVisitors)
                ->with('totalPageviews', $totalPageviews);

        } catch (Exception $e) {
            if (!$settings->api_google_analytics_client_id || !$settings->api_google_analytics_service_email) {
                $messages = 'There are missing API keys that you DID NOT entered. Please enter the missing API keys from the <a href="'.route('api.key.settings').'">\'Api Key Settings\'</a> page.';
            } else {
                $messages = $e->getMessage();
            }

            return View::make('admin.dashboard.warning')
                    ->with('messages', $messages);
        }
    }
}