<?php
	// ini_set('display_errors',1);
	// ini_set('display_startup_erros',1);
	// error_reporting(E_ALL);
	session_start();
	include $_SERVER["DOCUMENT_ROOT"].'/inc/conexao.php'; 
	include $_SERVER["DOCUMENT_ROOT"].'/inc/functions.php'; 
	function geraDataEvento($data){
		$data = date('Y-m-d H:i:s', $data);

		$data = date('Y-m-d H:i:s', strtotime('+0 hours', strtotime($data)));
		$data = explode(' ', $data);
		$hora = $data[1];
		$data = explode('-', $data[0]);
		$data = $data[2].'/'.$data[1].'/'.$data[0].' '.substr($hora, 0, 5);
		return $data;
	}
?>
<div class="page">
  <div class="navbar" style="background: #141e28 !important;">
    <div class="navbar-inner sliding"> 
      <div class="left">
        <a href="#" class="link back">
          <i class="icon icon-back"></i>
          <span class="ios-only">Voltar</span>
        </a>
      </div>
      <div class="title">Detalhes</div>
    </div>
    
    <?php
      $t = explode(' x ', $_GET["name"]);
      if($x = simplexml_load_file('http://www.sysfbet.com.br/cdn/xml/apostas/'.$_GET["match"].'.xml')){

      }
      else {
        $x = simplexml_load_file('http://sysfbet.com.br/live/aovivosbopcoes.php?jogo_id='.$_GET["match"]);
      }

      $t0in = definePaisNomeTimeInverso($t[0]);
      $t1in = definePaisNomeTimeInverso($t[1]);

      if(!isset($_GET['casaescudo']) || $_GET['casaescudo'] == ''){
        $_GET['casaescudo'] = $x->attributes()->t1i;
      }

      if(!isset($_GET['visitanteescudo']) || $_GET['visitanteescudo'] == ''){
        $_GET['visitanteescudo'] = $x->attributes()->t2i;
      }

      if($_GET['casaescudo'] == '' || $_GET['visitanteescudo'] == ''){
        $sql = $mysqli->query("SELECT time_imagem, time_nome FROM times WHERE (time_nome = '".$t0in."' OR time_nome = '".$t1in."') AND time_imagem <> ''");

        while($shield = $sql->fetch_assoc()){
          if($shield["time_nome"] == $t0in){ $_GET['casaescudo'] = $shield["time_imagem"]; }
          if($shield["time_nome"] == $t1in){ $_GET['visitanteescudo'] = $shield["time_imagem"]; }
        }
      }
    ?>

    <div class="subnavbar submatchbar">
        <div class="teams">
          <div class="team1">
            <?php if($_GET['casaescudo'] <> ''){ ?>
            <img src="https://assets.b365api.com/images/team/b/<?php echo $_GET['casaescudo']; ?>.png" alt="">
            <?php } else { ?>
            <img src="/img/no-shield.png" alt="">
            <?php } ?>
            <div class="teamname"><?php echo $t[0]; ?></div>
          </div>
          <div class="versus-navbar" id="versus-navbar">
            <span id="match_time"></span>
            <b id="match_ss">-:-</b>
            <span id="match_ht"></span>
          </div>
          <div class="team2">
            <?php if($_GET['visitanteescudo'] <> ''){ ?>
            <img src="https://assets.b365api.com/images/team/b/<?php echo $_GET['visitanteescudo']; ?>.png" alt="">
            <?php } else { ?>
            <img src="/img/no-shield.png" alt="">
            <?php } ?>
            <div class="teamname"><?php echo $t[1]; ?></div>
          </div>
        </div>
    </div>
  </div>
  <div class="toolbar tabbar tabbar-scrollable hasSubnavMatchTopbar">
    <div class="toolbar-inner">
      <a href="#tab-general" class="tab-link tab-link-active">Visão Geral</a>
      <a href="#tab-events" class="tab-link">Eventos</a>
      <a href="#tab-odds" class="tab-link">Odds</a>
      <a href="#tab-matches" class="tab-link">Partidas</a>
      <a href="#tab-stats" class="tab-link">Estatísticas</a>
    </div>
  </div>
  <div class="page-content hasSubnavMatch">
    <div class="tabs-swipeable-wrap">
      <div class="tabs">
        <!-- TAB -->
        <div id="tab-general" class="page-content tab fscores-tab tab-active">
          <div class="fscores_content">
            <div class="match_info_header">
              <b class="name_event"><?php echo $_GET["eventname"]; ?></b>
              <h2 id="match_name_h"><?php echo $_GET["name"]; ?></h2>

              <div class="match_info_date" id="match_info_date">
                <b class="name_event">A partida inicia em:</b>
                <h3><?php echo $_GET["data"]; ?></h3>
              </div>
            </div>

            <?php
              // Pesquisa informações da enquete
              $mid = $_GET["match"];
              $sql = $mysqli->query("SELECT * FROM enquetes WHERE enq_match = '$mid'");
              $total = 19; $enq_casa = 9; $enq_empate = 3; $enq_fora = 7;

              if(mysqli_num_rows($sql) > 0){
                $enq = $sql->fetch_assoc();
                $total = $enq["enq_casa"] + $enq["enq_empate"] + $enq["enq_fora"];
                $total_1p = $total / 100;
                $enq_casa = (int)$enq["enq_casa"];
                $enq_empate = (int)$enq["enq_empate"];
                $enq_fora = (int)$enq["enq_fora"];
              }

              $btn1 = '1';
              $btnX = 'X';
              $btn2 = '2';
              $btn1_style = '';
              $btnX_style = '';
              $btn2_style = '';
              $classe = '';

              if(in_array($mid, $_SESSION["enquetes"])){
              	$btn1 = (int)(($enq_casa / $total_1p)).'% ('.$enq_casa.')';
              	$btnX = (int)(($enq_empate / $total_1p)).'% ('.$enq_empate.')';
              	$btn2 = (int)(($enq_fora / $total_1p)).'% ('.$enq_fora.')';
				$btn1_style = 'max-width: '.(int)(($enq_casa / $total_1p)).'% !important; ';
				$btnX_style = 'max-width: '.(int)(($enq_empate / $total_1p)).'% !important; ';
				$btn2_style = 'max-width: '.(int)(($enq_fora / $total_1p)).'% !important; ';
              	$classe = 'survey_answered';
              }
            ?>

            <div class="match_survey <?php echo $classe; ?>" id="match_survey1">
                <b class="name_event">Quem vai ganhar?</b>
                <div class="survey_options" id="survey_options">
                  <button id="surveyBtn1" style="<?php echo $btn1_style; ?>" onClick="respondeEnquete(this, '<?php echo $_GET["match"]; ?>', '1');" votos="<?php echo $enq_casa; ?>" percent="<?php echo number_format(($enq_casa / $total_1p), 2); ?>" class="col button button-fill button-round bg-color-blue"><?php echo $btn1; ?></button>
                  <button id="surveyBtnX" style="<?php echo $btnX_style; ?>" onClick="respondeEnquete(this, '<?php echo $_GET["match"]; ?>', 'X');" votos="<?php echo $enq_empate; ?>" percent="<?php echo number_format(($enq_empate / $total_1p), 2); ?>" class="col button button-fill button-round bg-color-gray"><?php echo $btnX; ?></button>
                  <button id="surveyBtn2" style="<?php echo $btn2_style; ?>" onClick="respondeEnquete(this, '<?php echo $_GET["match"]; ?>', '2');" votos="<?php echo $enq_fora; ?>" percent="<?php echo number_format(($enq_fora / $total_1p), 2); ?>" class="col button button-fill button-round bg-color-green"><?php echo $btn2; ?></button>
                </div>
            </div>
            
            <?php if(isset($_GET["choicename"])){ ?>
            <div class="match_survey" style="margin-bottom: -15px;">
                <b class="name_event">Sua aposta foi:</b>
                <div class="survey_options" style="margin: 0;">
                  <h2 style="margin: 0;"><?php echo $_GET["choicename"]; ?></h2>
                </div>
                <center><?php echo $_GET["betname"]; ?></center>
            </div>
            <?php } ?>

            <div class="match_survey">
                <b class="name_event">Vencedor do Encontro</b>
                <div class="survey_options">
                  <button class="col button button-fill home_odds" id="vg_odd_home"><?php echo $_GET["oddcasa"]; ?></button>
                  <button class="col button button-fill home_odds" id="vg_odd_draw"><?php echo $_GET["oddempate"]; ?></button>
                  <button class="col button button-fill home_odds" id="vg_odd_away"><?php echo $_GET["oddvisitante"]; ?></button>
                </div>
                <button class="col button button-fill more_odds tab-link" href="#tab-odds">Opções disponíveis</button>
            </div>

            <div class="match_survey">
                <b class="name_event"><?php echo $_GET["match"]; ?></b>
            </div>
          </div>
        </div>
        <!-- TAB -->
        <!-- TAB -->
        <div id="tab-events" class="page-content tab fscores-tab">
          <div class="fscores_content">
            <div class="list simple-list">
              <ul id="match-events">
                <li>
                  <div class="item-inner">
                    <div class="item-subtitle">Aguardando início da partida...</div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <!-- TAB -->
        <!-- TAB -->
        <div id="tab-odds" class="page-content tab fscores-tab">
          <div class="fscores_content">
            <b>* Em breve serão permitidas apostas ao vivo neste aplicativo.</b> <br /><br />
            
            <div id="matchOddsLive"></div>
            
            <div id="matchOddsPre">
              <?php
                  $bapiId = $x->attributes()->bapi_id;

                  foreach ($x as $b) {
                    echo '<div class="boption">'.(string)$b->attributes()->name.'</div>';

                    foreach ($b as $o) {
                      echo '<div class="ooption"><span class="option_name">'.(string)$o->attributes()->name.'</span> <button class="col button button-small button-outline">'.(string)$o->attributes()->odd.'</button></div>';
                    }
                  }
              ?>
            </div>
          </div>
        </div>
        <!-- TAB -->
        <!-- TAB -->
        <div id="tab-matches" class="page-content tab fscores-tab">
          <div class="fscores_content">
              <p class="segmented segmented-raised">
                <button id="changeH2H" onclick="changeMatchesView(this, 'home');" data-type="home" class="changeH2H button"><?php echo $t[0]; ?></button>
                <button id="changeH2H" onclick="changeMatchesView(this, 'h2h');" data-type="h2h" class="changeH2H button button-active">H2H</button>
                <button id="changeH2H" onclick="changeMatchesView(this, 'away');" data-type="away" class="changeH2H button"><?php echo $t[1]; ?></button>
              </p>

              <div class="last_matches">
                  <?php
                    if($bapiId == ''){
                      echo '<br /> <br /><b>Informações não disponíveis.</b> <br /><br />';
                    } else {
                      $j = file_get_contents('https://api.betsapi.com/v1/event/history?token=3540-bSjOGcM8ep8Tvg&event_id='.$bapiId);
                      $info = json_decode($j, true);

                      foreach ($info["results"] as $type => $i) {
                        foreach ($i as $m) {
                        $d = explode(' ', geraDataEvento($m["time"]));
                        $d = $d[0];
                        $d = str_replace('/20', '/', $d);
                        $s = explode('-', $m["ss"]);

                        $r = 'E';
                        $rclass = 'bg-color-gray';

                        $type_team = 'OFF';
                        if(definePaisNomeTime($m["home"]["name"]) == definePaisNomeTime($t[0])){
                          $type_team = 'home';
                        }
                        if(definePaisNomeTime($m["home"]["name"]) == definePaisNomeTime($t[1])){
                          $type_team = 'home';
                        }

                        if(definePaisNomeTime($m["away"]["name"]) == definePaisNomeTime($t[0])){
                          $type_team = 'away';
                        }
                        if(definePaisNomeTime($m["away"]["name"]) == definePaisNomeTime($t[1])){
                          $type_team = 'away';
                        }

                        switch ($type_team) {

                          case 'h2h':
                            $rclass = 'displayNone';
                            break;

                          case 'home':
                            if($s[0] > $s[1]){
                              $r = 'G';
                              $rclass = 'bg-color-green';
                            }
                            elseif($s[0] == $s[1]){
                              $r = 'E';
                              $rclass = 'bg-color-gray';
                            }
                            else {
                              $r = 'P';
                              $rclass = 'bg-color-red';
                            }
                            break;

                          case 'away':
                            if($s[0] < $s[1]){
                              $r = 'G';
                              $rclass = 'bg-color-green';
                            }
                            elseif($s[0] == $s[1]){
                              $r = 'E';
                              $rclass = 'bg-color-gray';
                            }
                            else {
                              $r = 'P';
                              $rclass = 'bg-color-red';
                            }
                            break;
                          
                          default:
                            $rclass = 'displayNone';
                            break;
                        }

                        if($type == 'h2h'){
                            $rclass = 'displayNone';
                        }

                        echo '<div class="match_list types_comparation type_'.$type.'">
                                <a href="" class="item-link item-content">
                                  <div class="match_date">'.$d.'</div>
                                  <div class="match_list_item">
                                    <div class="match_list_team '; if($s[0] > $s[1]){ echo 'match_winner_list'; } echo '"><span class="team_score">'.$s[0].'</span> &nbsp; '.definePaisNomeTime($m["home"]["name"]).'</div>
                                    <div class="match_list_team '; if($s[1] > $s[0]){ echo 'match_winner_list'; } echo '"><span class="team_score">'.$s[1].'</span> &nbsp; '.definePaisNomeTime($m["away"]["name"]).'</div>
                                  </div>
                                  <div class="match_result"><button class="col button button-fill button-small button-round '.$rclass.'">'.$r.'</button></div>
                                </a>
                              </div>';
                        }
                      }
                    }
                  ?>
              </div>
          </div>
        </div>
        <!-- TAB -->
        <!-- TAB -->
        <div id="tab-stats" class="page-content tab fscores-tab">
          <div class="fscores_content">
              <div class="stats_item_title">Cartões Amarelos</div>
              <div class="stats_item">
                <div id="statbar_yellow_1" class="progressbar inversebar stat_bar color-blue" data-progress="0"></div>
                <div id="statbar_yellow_2" class="progressbar stat_bar color-green" data-progress="0"></div>
                <span id="statinfo_yellow_1" class="statinfo1">0</span>
                <span id="statinfo_yellow_2" class="statinfo2">0</span>
              </div>

              <div class="stats_item_title">Cartões Vermelhos</div>
              <div class="stats_item">
                <div id="statbar_red_1" class="progressbar inversebar stat_bar color-blue" data-progress="0"></div>
                <div id="statbar_red_2" class="progressbar stat_bar color-green" data-progress="0"></div>
                <span id="statinfo_red_1" class="statinfo1">0</span>
                <span id="statinfo_red_2" class="statinfo2">0</span>
              </div>

              <div class="stats_item_title">Escanteios</div>
              <div class="stats_item">
                <div id="statbar_corner_1" class="progressbar inversebar stat_bar color-blue" data-progress="0"></div>
                <div id="statbar_corner_2" class="progressbar stat_bar color-green" data-progress="0"></div>
                <span id="statinfo_corner_1" class="statinfo1">0</span>
                <span id="statinfo_corner_2" class="statinfo2">0</span>
              </div>

              <div class="stats_item_title">Substituições</div>
              <div class="stats_item">
                <div id="statbar_subs_1" class="progressbar inversebar stat_bar color-blue" data-progress="0"></div>
                <div id="statbar_subs_2" class="progressbar stat_bar color-green" data-progress="0"></div>
                <span id="statinfo_subs_1" class="statinfo1">0</span>
                <span id="statinfo_subs_2" class="statinfo2">0</span>
              </div>

              <div class="stats_item_title">Pênaltis</div>
              <div class="stats_item">
                <div id="statbar_pen_1" class="progressbar inversebar stat_bar color-blue" data-progress="0"></div>
                <div id="statbar_pen_2" class="progressbar stat_bar color-green" data-progress="0"></div>
                <span id="statinfo_pen_1" class="statinfo1">0</span>
                <span id="statinfo_pen_2" class="statinfo2">0</span>
              </div>
          </div>
        </div>
        <!-- TAB -->
      </div>
    </div>
</div>