<?php
    $page = 1;
    require("inc_header.php");

    // ======================================================
    // SELECT TOTAL GAMES PLAYED
    // SELECT AVARAGE PLAY TIME
    // ======================================================
    
    $query = "SELECT COUNT(*) AS data, AVG(`play_time`) AS average 
              FROM `playdata` 
              WHERE DATE(`start_time`) = CURDATE()";

    $result_temp = mysqli_query($connection, $query);
    $result = mysqli_fetch_assoc($result_temp);

    $games_played = $result['data'];
    $avarage_time_temp = $result['average'];

    $avarage_time = format($avarage_time_temp);


    // ======================================================
    // SELECT HIGHEST SCORE OF TODAY
    // ======================================================
    
    $query = "SELECT MAX(`score`) AS score 
              FROM `highscore` 
              WHERE date=CURDATE()";

    $result_temp = mysqli_query($connection, $query);
    $result = mysqli_fetch_assoc($result_temp);

    $highest_score = $result['score'];
    if($highest_score==null)
    {
      $highest_score=0;
    }


    // ======================================================
    // SELECT MOST PLAYED SONG
    // ======================================================
    
    $query = "SELECT `songinstance`, `title`, COUNT(`songinstance`) as `num` FROM `playdata`, `songinstance`, `song` 
              WHERE playdata.songinstance=songinstance.id AND songinstance.song=song.id AND DATE(`start_time`)=CURDATE()
              GROUP BY `songinstance` 
              ORDER BY COUNT(`songinstance`) DESC 
              LIMIT 1";

    $result_temp = mysqli_query($connection, $query);
    if(mysqli_num_rows($result_temp) > 0)
    {
      $result = mysqli_fetch_assoc($result_temp);
      $most_played = $result['title'];
    }
    else
    {
      $most_played = "No songs played today";
    }
    

    // ======================================================
    // DATA POINTS FOR MOST PLAYED GRAPH
    // DATA POINTS FOR AVERAGE PLAY TIME GRAPH
    // ======================================================
    
    $most_played_array = array();
    $average_play_time_array = array();

    $query = "SELECT DATE(`start_time`) AS date, COUNT(*) AS data, AVG(`play_time`) AS average 
              FROM `playdata` 
              GROUP BY DATE(`start_time`) 
              ORDER BY `start_time` DESC
              LIMIT 0,7";

    $result_temp = mysqli_query($connection, $query);
    while($result = mysqli_fetch_assoc($result_temp))
    {
      $most_played_array[] = "{y: '" . $result['date'] . "', gp: " . $result['data'] . "}";
      $average_play_time_array[] = "{y: '" . $result['date'] . "', pt: " . format($result['average'])['tseconds'] . "}";
    }

    $most_played_array = array_reverse($most_played_array);
    $average_play_time_array = array_reverse($average_play_time_array);


    // ======================================================
    // DATA POINTS FOR SCORES GRAPH
    // ======================================================
    
    $scores_array = array();
    $scores_names_array = array();

    $query = "SELECT `date`, `score`, `username` 
              FROM highscore 
              ORDER BY `date` DESC
              LIMIT 0,28";

    $result_temp = mysqli_query($connection, $query);
    while($result = mysqli_fetch_assoc($result_temp))
    {
      $scores_array[] = "{y: '" . $result['date'] . "', sc: " . $result['score'] . "}";
      $scores_names_array[] = "'" . $result['username'] . "'";
    }

    $scores_array = array_reverse($scores_array);
    $scores_names_array = array_reverse($scores_names_array);


    // ======================================================
    // PERCENTAGE OF DIFFICULTY
    // ======================================================
    
    $easy = 0;
    $medium = 0;
    $hard = 0;
    $other = 0;

    $query = "SELECT `difficulty`, COUNT(1) as num, COUNT(1) / (SELECT COUNT(1) FROM `playdata` ) * 100 as avg
              FROM `songinstance` AS si, `playdata` as pd 
              WHERE si.id = pd.songinstance
              GROUP BY `difficulty`";

    $result_temp = mysqli_query($connection, $query);
    while($result = mysqli_fetch_assoc($result_temp))
    {
      if(strtolower($result['difficulty']) == "easy")
      {
        $easy = $easy + round($result['avg']);
      }
      else if(strtolower($result['difficulty']) == "medium")
      {
        $medium = $medium + round($result['avg']);
      }
      else if(strtolower($result['difficulty']) == "hard")
      {
        $hard = $hard + round($result['avg']);
      }
      else
      {
        $other = $other + $result['avg'];
      }
    }
    $other = round($other);

    
    // ======================================================
    // LATEST GAMES
    // ======================================================
    
    $table = "";

    $query = "SELECT `title`, `difficulty`, songinstance.id as siid, song.id as sid, (`enemies_hit` / (`enemies_missed` + `enemies_hit`)) * 100 as ratio, `start_time`, `play_time` 
              FROM `playdata`, `songinstance`, `song`
              WHERE playdata.songinstance = songinstance.id AND songinstance.song = song.id
              ORDER BY `start_time` DESC
              LIMIT 3";

    $result_temp = mysqli_query($connection, $query);
    while($result = mysqli_fetch_assoc($result_temp))
    {
      $ratio = round($result['ratio']);
      $label = "danger";
      if($ratio >= 40)
        $label = "warning";
      if($ratio >= 80)
        $label = "success";

      $table .= "<tr>";
      $table .= "<td><a href='" . returnurl('song.php?id=' . $result['sid']) . "'>" . $result['title'] . "</a></td>";
      $table .= "<td><a href='" . returnurl('songinstance.php?id=' . $result['siid']) . "'>" . $result['difficulty'] . "</a></td>";
      $table .= "<td><span class='label label-" . $label . "'>" . $ratio . "<small>%</small></span></td>";
      $table .= "<td>" . format($result['play_time'])['string'] . "</td>";
      $table .= "<td>" . $result['start_time'] . "</td>";
      $table .= "</tr>";
    }        
?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">

  <!-- Content Header (Page header) -->
  <section class="content-header">
    <h1>
      Dashboard
      <small>All activity in one quick overview</small>
    </h1>
    <ol class="breadcrumb">
      <li class="active"><a href="#"><i class="fa fa-dashboard"></i> Dashboard</a></li>
    </ol>
  </section>

  <section class="content">

    <!--==================================================
    // HEADER BOXES 
    ===================================================-->
    
    <!-- Small boxes (Stat box) -->
    <div class="row">

      <div class="col-lg-3 col-sm-6 col-xs-12">
        <!-- small box -->
        <div class="small-box bg-aqua">
          <div class="inner">
            <h3><?php echo $games_played; ?></h3>
            <p>Games Played</p>
          </div>
          <div class="icon">
            <i class="ion ion-ios-game-controller-a"></i>
          </div>
          <a href="<?php url('games.php') ?>" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div><!-- ./col -->

      <div class="col-lg-3 col-sm-6 col-xs-12">
        <!-- small box -->
        <div class="small-box bg-green">
          <div class="inner">
            <h3><?php echo $avarage_time['minutes'] . ":" . $avarage_time['seconds']; ?><sup style="font-size: 20px">:<?php echo $avarage_time['usec']; ?></sup></h3>
            <p>Minutes played on avarage</p>
          </div>
          <div class="icon">
            <i class="ion ion-clock"></i>
          </div>
          <a href="<?php url('games.php') ?>" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div><!-- ./col -->

      <div class="clearfix visible-sm-block"></div>

      <div class="col-lg-3 col-sm-6 col-xs-12">
        <!-- small box -->
        <div class="small-box bg-yellow">
          <div class="inner">
            <h3><?php echo $highest_score; ?><sup style="font-size: 20px"> points</sup></h3>
            <p>Highscore</p>
          </div>
          <div class="icon">
            <i class="ion ion-ribbon-b"></i>
          </div>
          <a href="<?php url('scores.php') ?>" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div><!-- ./col -->

      <div class="col-lg-3 col-sm-6 col-xs-12">
        <!-- small box -->
        <div class="small-box bg-red">
          <div class="inner">
            <h3><?php echo $most_played; ?></h3>
            <p>Most Played Song</p>
          </div>
          <div class="icon">
            <i class="ion ion-music-note"></i>
          </div>
          <a href="<?php url('songs.php') ?>" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div><!-- ./col -->
    </div><!-- /.row -->

    <div class="row">
      <div class="col-lg-6">
        <!-- games played graph -->
        <div class="box box-solid bg-teal">
          <div class="box-header">
            <i class="fa fa-gamepad"></i>
            <h3 class="box-title">Games played</h3>
          </div>

          <div class="box-body border-radius-none">
            <div class="chart" id="games-played-chart" style="height: 245px;"></div>
          </div><!-- /.box-body -->

          <!-- gamemodes -->
          <div class="box-footer no-border hidden-xs">
            <div class="row">
              <div class="col-xs-3 text-center" style="border-right: 1px solid #f4f4f4">
                <input type="text" class="knob" data-readonly="true" value="<?php echo $easy; ?>" data-width="60" data-height="60" data-fgColor="#39CCCC"/>
                <div class="knob-label">Easy</div>
              </div><!-- ./col -->
              <div class="col-xs-3 text-center" style="border-right: 1px solid #f4f4f4">
                <input type="text" class="knob" data-readonly="true" value="<?php echo $medium; ?>" data-width="60" data-height="60" data-fgColor="#39CCCC"/>
                <div class="knob-label">Medium</div>
              </div><!-- ./col -->
              <div class="col-xs-3 text-center" style="border-right: 1px solid #f4f4f4">
                <input type="text" class="knob" data-readonly="true" value="<?php echo $hard; ?>" data-width="60" data-height="60" data-fgColor="#39CCCC"/>
                <div class="knob-label">Hard</div>
              </div><!-- ./col -->
              <div class="col-xs-3 text-center">
                <input type="text" class="knob" data-readonly="true" value="<?php echo $other; ?>" data-width="60" data-height="60" data-fgColor="#39CCCC"/>
                <div class="knob-label">Other</div>
              </div><!-- ./col -->
            </div><!-- /.row -->
          </div><!-- /.box-footer -->
        </div><!-- /.box -->

        <div class="box">
          <div class="box-header with-border">
            <i class="fa fa-gamepad"></i>
            <h3 class="box-title">Latest Games</h3>
          </div><!-- /.box-header -->
          <div class="box-body">
            <div class="table-responsive">
              <table class="table no-margin">
                <thead>
                  <tr>
                    <th>Song Name</th>
                    <th>Difficulty</th>
                    <th>Hit Ratio</th>
                    <th>Length</th>
                    <th>Time</th>
                  </tr>
                </thead>
                <tbody>
                  <?php echo $table; ?>
                </tbody>
              </table>
            </div><!-- /.table-responsive -->
          </div><!-- /.box-body -->
          <!--
          <div class="box-footer clearfix">
            <a href="<?php url('songs.php') ?>" class="btn btn-sm btn-default btn-flat pull-right">View All Songs</a>
          </div><!-- /.box-footer -->
        </div><!-- /.box -->
      </div><!-- /.column -->

      <div class="col-lg-6">
        <!-- TABLE: LATEST SONGS -->

        <!-- games played graph -->
        <div class="box box-solid bg-purple">
          <div class="box-header">
            <i class="ion ion-ribbon-b"></i>
            <h3 class="box-title">Scores</h3>
          </div>

          <div class="box-body border-radius-none">
            <div class="chart" id="scores-chart" style="height: 245px;"></div>
          </div><!-- /.box-body -->
        </div><!-- /.box -->

        <div class="box box-solid bg-orange">
          <div class="box-header">
            <i class="ion ion-clock"></i>
            <h3 class="box-title">Average Play Time</h3>
          </div>

          <div class="box-body border-radius-none">
            <div class="chart" id="average-play-time-chart" style="height: 255px;"></div>
          </div><!-- /.box-body -->
        </div><!-- /.box -->
      </div><!-- /.col -->
    </div>

  </section><!-- /.content -->
</div><!-- /.content-wrapper -->

<!-- Morris.js charts -->
    <script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
    <script src="plugins/morris/morris.min.js" type="text/javascript"></script>
<!-- jQuery Knob Chart -->
    <script src="plugins/knob/jquery.knob.js" type="text/javascript"></script>
<!-- Page specific javascript -->
    <script type="text/javascript">
        var most_played_data = [ <?php
             foreach ($most_played_array as $value)
             {
                echo $value . ",\n";
             }
        ?> ];

        var average_play_time_data = [ <?php
             foreach ($average_play_time_array as $value)
             {
                echo $value . ",\n";
             }
        ?> ];

        var scores_data = [ <?php
             foreach ($scores_array as $value)
             {
                echo $value . ",\n";
             }
        ?> ];

        var scores_names_data = [ <?php
             foreach ($scores_names_array as $value)
             {
                echo $value . ",\n";
             }
        ?> ];

    </script>
    <script src="dist/js/pages/dashboard.js" type="text/javascript"></script> 

<?php
    require("inc_footer.php");
?>