<?php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

//$analytics = initializeAnalytics();
//$response = getReport($analytics, '2020-09-29', '2020-09-29' );
//printResults($response);

/**
 * Initializes an Analytics Reporting API V4 service object.
 *
 * @return An authorized Analytics Reporting API V4 service object.
 */
function initializeAnalytics(){
  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/aid2020-dd2bf-a9161df80e54.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("AID 2020 admin");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_AnalyticsReporting($client);
  return $analytics;
}

/**
 * Queries the Analytics Reporting API V4.
 *
 * @param service An authorized Analytics Reporting API V4 service object.
 * @return The Analytics Reporting API V4 response.
 */
function getReport($analytics, $star_date, $end_date) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "230668120";

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate( $star_date );
  $dateRange->setEndDate( $end_date );

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:pageviews");
  $sessions->setAlias("pageviews");
    
    //Create the Dimensions object.
   $browser = new Google_Service_AnalyticsReporting_Dimension();
   $browser->setName("ga:pagePath");

  // Create the Metrics object.
  $pagePath = new Google_Service_AnalyticsReporting_Metric();
  $pagePath->setExpression("ga:pageviews");
  $pagePath->setAlias("pageviews");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setMetrics(array($sessions));
  $request->setDimensions(array($browser));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}

/**
 * Parses and prints the Analytics Reporting API V4 response.
 *
 * @param An Analytics Reporting API V4 response.
 */

function printResults($reports) {
    $arrayDimesiones = array();
    
    /*
    for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
        $report = $reports[ $reportIndex ];
        $header = $report->getColumnHeader();
        $dimensionHeaders = $header->getDimensions();
        $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
        $rows = $report->getData()->getRows();

        //INICIA EL CICLO
        for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
            $fila = array();
            $row = $rows[ $rowIndex ];
            $dimensions = $row->getDimensions();
            $metrics = $row->getMetrics();
            for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
                array_push($fila, $dimensions[$i] );
            }

            for ($j = 0; $j < count($metrics); $j++) { 
                  $values = $metrics[$j]->getValues();
                  for ($k = 0; $k < count($values); $k++) {
                      $entry = $metricHeaders[$k];
                      array_push($fila, $values[$k] );
                      //$total_dia += $values[$k];
                  }
            }
            array_push($arrayDimesiones, $fila );
        }
    }
    */

  //print($arrayDimesiones);
  return $arrayDimesiones; 
}


function Total_Dia($arr){
    $total = 0;
    foreach($arr as $item){
        $total += $item[1];
    }
    return $total;
}

function Total_Live($arr){
    $total = 0;
    foreach($arr as $item){
        if($item[0] == '/live'){
            $total += $item[1];
        }
    }
    return $total;
}

function Total_Muestra($arr){
    $total = 0;
    foreach($arr as $item){
        if($item[0] == '/muestra'){
            $total += $item[1];
        }
    }
    return $total;
}

function Total_Stand($arr){
    $total_1 = 0;
    $total_2 = 0;
    $total_3 = 0;
    $total_4 = 0;
    $total_5 = 0;
    $total_6 = 0;
    $total_7 = 0;
    $total_8 = 0;
    $total_9 = 0;
    $total_10 = 0;
    $total_11 = 0;
    $total_12 = 0;
    $total_13 = 0;
    $total_14 = 0;
    
    foreach($arr as $item){
        if($item[0] == '/info/1'){
            $total_1 += $item[1];
        }
        if($item[0] == '/info/2'){
            $total_2 += $item[1];
        }
        if($item[0] == '/info/3'){
            $total_3 += $item[1];
        }
        if($item[0] == '/info/4'){
            $total_4 += $item[1];
        }
        if($item[0] == '/info/5'){
            $total_5 += $item[1];
        }
        if($item[0] == '/info/6'){
            $total_6 += $item[1];
        }
        if($item[0] == '/info/7'){
            $total_7 += $item[1];
        }
        if($item[0] == '/info/8'){
            $total_8 += $item[1];
        }
        if($item[0] == '/info/9'){
            $total_9 += $item[1];
        }
        if($item[0] == '/info/10'){
            $total_10 += $item[1];
        }
        if($item[0] == '/info/11'){
            $total_11 += $item[1];
        }
        if($item[0] == '/info/12'){
            $total_12 += $item[1];
        }
        if($item[0] == '/info/13'){
            $total_13 += $item[1];
        }
        if($item[0] == '/info/14'){
            $total_14 += $item[1];
        }
    }
    
    $arreglo = array( $total_1 , $total_2, $total_3, $total_4, $total_5, $total_6, $total_7, $total_8, $total_9, $total_10, $total_11, $total_12, $total_13, $total_14 );
    return $arreglo;
}

$total_dia = 0;
$total_live = 0;
$total_muestra = 0;

if($_POST["dia"]){
    $dias = explode(" ", $_POST["dia"]);
    $response = getReport($analytics, $dias[0], $dias[1] );
    $estadisticasArray = printResults($response);
    $total_dia = Total_Dia($estadisticasArray);
    $total_live = Total_Live($estadisticasArray);
    $total_muestra = Total_Muestra($estadisticasArray);
    $stands = Total_Stand($estadisticasArray);
}



/*
function printResults___($reports) {
$arrayDimesiones = array();
    
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();
      
    $fila = array();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      echo '<div>';

      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        array_push($fila, $dimensions[$i] );
        //print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");

        //echo($dimensions[$i] . "\n");

        echo '<div class="ruta">'.$dimensions[$i]."</div>";

      }

      for ($j = 0; $j < count($metrics); $j++) { 
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];

        array_push($fila, $values[$k] );
          echo '<div class="valor">'.$values[$k]."</div>";

          $total_dia += $values[$k];



          //print( $values[$k] . "\n");

          //array_push($metricas, array( "metrica_1"=> $entry->getName(), "valor_2"=> $values[$k] ));
          //print($entry->getName() . ": " . $values[$k] . "\n");
        }
      }
      echo '</div>';
        array_push($arrayDimesiones, $fila );

    }


    echo '
      <script>
        $("#total_dia").html('.$total_dia.');
      </script>
    ';
  }

  //print($arrayDimesiones);
  return $arrayDimesiones; 
}

*/

?>


<?php
  session_start();
  //VALIDACION DE SESION
  if($_SESSION['id_user_admin'] == ""){
    header('Location: log.php' );
  }
  include("models/connect.php");
?>


<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Administrador AID 2020</title>
    
    <link rel="stylesheet" href="css/bootstrap.css" crossorigin="anonymous">
    <link rel="stylesheet" href="css/style.css" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="js/bootstrap.bundle.js" crossorigin="anonymous"></script>
    <script src="js/bootstrap.js" crossorigin="anonymous"></script>
    <script src="js/papaparse.js"></script>

    
    
    <style>
                .ti_ficha{
                    line-height: 16px;
                    margin-top: 15px;
                    font-size: 15px;
                    margin-bottom: -5px;
                }
                .numero_ficha{
                    font-size: 50px;
                    font-weight: bold;
                    margin-bottom: 10px;
                }
    </style>


</head>

<body>

  <noscript>
    <div class="alert alert-success" role="alert">
        Para utilizar las funcionalidades completas de este sitio es necesario tener
        JavaScript habilitado. Aquí están las <a href="https://www.enable-javascript.com/es/">
        instrucciones para habilitar JavaScript en tu navegador web</a>.
    </div>
  </noscript>


  <div class="container-fluid">
    <div class="row">
      <?php include("views/layouts/lateral.php"); ?>
      <div class="col-md-9 col-xl-10">


        <div class="row" style="padding-top: 15px;">
    


          <!-- FICHA -->
          <!-- FICHA -->
          <!-- FICHA -->
          <div class="col-md-12" style="display: none">
              <table width="100%" style="background-color: #ff5a23; color: #ffffff;">
              <tr>
                <td width="100" style="padding: 15px; background-color: rgba(0,0,0,0.2);">
                  <i class="fa fa-user btn-left" style=" font-size: 60px "></i>
                </td>
                <td align="center" style="font-size: 20px; line-height: 35px;">
                  <div style="line-height: 20px; margin-top: 15px;">
                    En vivo Ahora<br>
                    <span style="font-size: 12px">(Solo registra usuarios únicos)</span>
                  </div>
                  <b style="font-size: 50px;" id="en_vivo__"></b>
                </td>
                <td align="center" style="width: 100px">
                    <a href="<?php echo $url_admin; ?>/?pg=analitica/en_vivo&cant=<?php echo $total_live; ?>">
                    <button type="button" class="btn btn-light">Ver</button>
                    </a>
                    
                    <a href="<?php echo $url_admin; ?>/?pg=conectados_ahora">
                    <button type="button" class="btn btn-light" style="display: none">Ver</button>
                    </a>
                </td>
              </tr>
            </table>
          </div>
            
            
            <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script>
      // Your web app's Firebase configuration
        var firebaseConfig = {
            apiKey: "AIzaSyAonc5lmGp-3qb-RjoBQE4-gzA2YvwN5fU",
            authDomain: "acrosst2d.firebaseapp.com",
            databaseURL: "https://acrosst2d.firebaseio.com",
            projectId: "acrosst2d",
            storageBucket: "acrosst2d.appspot.com",
            messagingSenderId: "890863731017",
            appId: "1:890863731017:web:4ff6a45c42e81adb195a98"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        var database = firebase.database();
       
        
        //2. ESCUCHAMOS SI UN USUARIO SE CONECTA 
        var tb_live = database.ref('participants');
        tb_live.on('value', EnVivo);
        
        var snapShot = '';
        function EnVivo(data){
          traza = data.val() ;
          var keyCount  = Object.keys(traza).length;

            $("#en_vivo").html( keyCount );
            console.log( keyCount );
            snapShot = JSON.stringify( data.val() );
            //GuardarData( JSON.stringify( data.val() ) )
        }
        
        
        function GuardarData( ) {

          jQuery.ajax({
            url: "https://acrossco2020.com/admin/api/guardar_dato.php",
            type:'post',
            data: { dato: snapShot},
            }).done(function (resp){
              
            
            })
            .fail(function(resp) {
              console.log(resp);
            })
            .always(function(resp){
            }
          );


        }
        
        
    </script>


          <!-- FICHA -->
          <!-- FICHA -->
          <!-- FICHA -->
          <div class="col-md-12" style="margin-top: 15px">

            <div class="card" style="margin-top: 15px">
              <div class="card-body">

                <form action="" method="post">
                  <select class="form-control" name="dia" style=" margin-bottom: 10px; font-size: 35px; border: 0;">
                      <option value="">Selecciona día...</option>
                      <?php
                      $diasArr = array(
                          array('2020-10-19 2020-10-19', 'Todos los días'),
                          array('2020-10-21 2020-10-21', 'Día 1 - 21 de Octubre'),
                          array('2020-10-22 2020-10-22', 'Día 2 - 22 de Octubre'),

                          
                      );
                      
                        foreach($diasArr as $dia){
                            if($_POST["dia"] == $dia[0]){
                                echo '<option value="'.$dia[0].'" selected>'.$dia[1].'</option>';
                            }
                            else{
                                echo '<option value="'.$dia[0].'">'.$dia[1].'</option>';
                            }
                        }
                      ?>
                  </select>
                  <input type="submit" value="Filtrar" class="btn btn-success btn-block">
                </form>

              </div>
            </div>
          </div>

         
            <!-- FICHA -->
          <!-- FICHA -->
          <!-- FICHA -->
          <div class="col-md-12" style="margin-top: 15px">
              <table width="100%" style="background-color: #ff5a23; color: #ffffff;">
              <tr>
                <td width="100" style="padding: 15px; background-color: rgba(0,0,0,0.2);">
                  <i class="fa fa-user btn-left" style=" font-size: 60px "></i>
                </td>
                <td align="center" style="font-size: 20px; line-height: 35px;">
                  <div style="line-height: 20px; margin-top: 15px;">
                    Live Streaming<br>
                    <span style="font-size: 12px">Personas que asistieron a los en vivo</span>
                  </div>
                  <b style="font-size: 50px;" id="en_vivo"></b>
                </td>
                  
               
                <td align="center" style="width: 100px">
                    <a href="<?php echo $url_admin; ?>/?pg=analitica/en_vivo&cant=<?php echo $total_live; ?>">
                    <button type="button" class="btn btn-light">Ver</button>
                    </a>
                    
                    <a href="<?php echo $url_admin; ?>/?pg=conectados_ahora">
                    <button type="button" class="btn btn-light" style="display: none">Ver</button>
                    </a>
                </td>
              </tr>
            </table>
          </div>
            

          <div class="col-md-4" style="margin-top: 15px">
            <table width="100%" style="background-color: #28a745; color: #ffffff;">
              <tr>
                <td width="100" style="padding: 15px; background-color: rgba(0,0,0,0.2);">
                  <i class="fa fa-user btn-left" style=" font-size: 60px "></i>
                </td>
                <td align="center">
                    <div class="ti_ficha"> Total de interacciones en plataforma </div>
                    <div class="numero_ficha"><?php echo $total_dia; ?></div>
                </td>
              </tr>
            </table>
          </div>
            
            

          <div class="col-md-4" style="margin-top: 15px">
            <table width="100%" style="background-color: #03A9F4; color: #ffffff;">
              <tr>
                <td width="100" style="padding: 15px; background-color: rgba(0,0,0,0.2);">
                  <i class="fa fa-eye btn-left" style=" font-size: 60px "></i>
                </td>
                <td align="center">
                    <div class="ti_ficha"> Total de interacciones en transmisión en vivo </div>
                    <div class="numero_ficha"><?php echo $total_live; ?></div>
                </td>
              </tr>
            </table>
          </div>

          <div class="col-md-4" style="margin-top: 15px">
            <table width="100%" style="background-color: #673AB7; color: #ffffff;">
              <tr>
                <td width="100" style="padding: 15px; background-color: rgba(0,0,0,0.2);">
                  <i class="fa fa-shopping-bag btn-left" style=" font-size: 60px "></i>
                </td>
                <td align="center">
                    <div class="ti_ficha"> Total de interacciones en Muestra Comercial </div>
                    <div class="numero_ficha"><?php echo $total_muestra; ?></div>
                </td>
              </tr>
            </table>
          </div>


          <!-- FICHA -->
          <!-- FICHA -->
          <!-- FICHA -->
          <div class="col-md-12" style="margin-top: 15px">

            <div class="card" style="margin-top: 15px">
              <div class="card-header" align="center">
                <h3 align="center" style="margin-bottom: 0">Muestra Comercial</h3>
                <div>Visitas a los stands</div>
              </div>
            </div>
          </div>


          <div class="col-md-3" style="margin-top: 15px">
            <table width="100%" style="background-color: #9C27B0; color: #ffffff;">
              <tr>
                <td align="center" >
                    
                    <div class="ti_ficha"> Trayenta </div>
                    <div class="numero_ficha"><?php echo $stands[0]; ?></div>
                    <a href="<?php echo $url_admin; ?>/?pg=analitica/producto&id=1&cant=<?php echo $stands[0]; ?>">
                        <button type="button" class="btn btn-light" style="margin-bottom: 15px; margin-top: -18px;">Ver</button>
                    </a>
                </td>
              </tr>
            </table>
          </div>


          <div class="col-md-3" style="margin-top: 15px">
            <table width="100%" style="background-color: #9C27B0; color: #ffffff;">
              <tr>
                <td align="center">
                    <div class="ti_ficha"> Jardiance </div>
                    <div class="numero_ficha"><?php echo $stands[1]; ?></div>
                    <a href="<?php echo $url_admin; ?>/?pg=analitica/producto&id=2&cant=<?php echo $stands[0]; ?>">
                        <button type="button" class="btn btn-light" style="margin-bottom: 15px; margin-top: -18px;">Ver</button>
                    </a>
                </td>
              </tr>
            </table>
          </div>

        </div>

        
        <input type="button" value="Guardar SnapShot" class="btn btn-secondary btn-sm" onclick="GuardarData()" style="width: 160px; margin-top: 25px;">
        

        
          
      </div>
    </div>
  </div>
    
  <div id="xscript"></div>

<style>
  .ruta{display: inline-table;
    width: 30%;
    background-color: #e6e6e6;
    padding: 10px;
    margin: 5px;
  }
  .valor{
    display: inline-table;
    width: 30%;
    background-color: #CDDC39;
    padding: 10px;
    margin: 5px;
  }
        .ficha_preguntas{
            background-color: #ffffff;
            padding: 10px;
            margin-bottom: 10px;
        }
        
        .pregunta{
            text-align: center;
            font-weight: bold;
            font-size: 15px;
            margin-bottom: 10px;
        }
        
        .opcion{
            background-color: #CDDC39;
            padding: 3px;
        }
        .grupo{
            margin-bottom: 10px;
        }
        .marco{
            border: 1px solid #ccc;
            margin-top: 5px;
        }
</style>




 
<style>

.btn-left{
  margin-right:10px;
}

.wrapper {
    display: flex;
    width: 100%;
    align-items: stretch;
}

#sidebar {
    min-width: 270px;
    max-width: 270px;
  min-height: 100vh;
    color: #000000;
  background-color:#ffffff;
}

#sidebar.active {
    margin-left: -250px;
}

body {
  font-family: 'Montserrat', sans-serif;
  background: <?php echo $cfondo; ?>;
  color: <?php echo $cfuente; ?>;
  font-size: 12px;
}

a, a:hover, a:focus {
    color: inherit;
    text-decoration: none;
    transition: all 0.3s;
}

.list-group-item{
  background-color:<?php echo $cmenu; ?>;
}

.list-group-item:hover{
  background-color:rgba(0,0,0,0.3);
}

svg{
  margin-right:8px;
}

.titulos{
  color: <?php echo $cseparador; ?>; 
  font-size: 15px; 
  font-weight: 600;
}

h5{
  color:<?php echo $ctitulos; ?>;
}



@media (max-width: 768px) {
    #sidebar {
        margin-left: -250px;
    display:none;
    }
    #sidebar.active {
        margin-left: 0;
    }
}

</style>
    

<script>
$(document).ready(function () {

    $('#sidebarCollapse').on('click', function () {
        $('#sidebar').toggleClass('active');
    });

});
</script>

</body>

</html>