<?php
/**
 * functions library relative to bets such as results, choice, etc..
 * remix of bib_showGames function : view and code separating
 *
 * @author flabadens
 * @version 1.0
 * @see bib/bib_showGames.php3
 * @todo loadResults()
 */

if ($versionmobile){
    include_once("../config.php3");
    $RACINE_DIR="../";
    $CORE="";
}
else {
    include_once("config.php3");
    $RACINE_DIR="";
}


//include_once($RACINE_DIR.$MOBILE_DIR."configMobile.php3");
include_once($RACINE_DIR.$BIB_DIR_FROM_RACINE."bib_db.php3");
include_once($RACINE_DIR.$BIB_DIR_FROM_RACINE."bib_showGames.php3");

/**
 * Load all bets containers running atm with a current user's bet
 * @param datetime $date
 * @param int $playerId
 * @return array of containers $containersResults
 */
function loadBetsCategoriesByPlayer ($date, $playerId){

    //$containers = main_db_query ("SELECT * FROM Containers WHERE ShowTime<'".$date."'  AND EndTime>'".$date."'");
    $prerowbets = " SELECT DISTINCT Categories.Container AS Id, Containers.Name AS Name
                    FROM Containers
                    LEFT JOIN Categories ON Containers.Id = Categories.Container
                    LEFT JOIN Matchs ON Matchs.Category = Categories.CategoryId
                    LEFT JOIN Paris ON Paris.MatchId = Matchs.MatchId
                    WHERE Paris.Playerid = '".$playerId."'
                    AND Paris.Done != '0'
                    AND Containers.ShowTime < '".$date.
                    "' AND Containers.EndTime > '".$date."' ORDER BY Containers.Name ASC";

    //$containers = main_db_query ("SELECT * FROM Containers WHERE ShowTime<'".$date."'  AND EndTime>'".$date."'");
    $containers = main_db_query ($prerowbets);
    $nbContainers = db_num_rows ($containers);
    $containersResults = array();

    while ($container = db_fetch_assoc($containers)){
        $containersResults[]=$container;
    }

    return $containersResults;

}

/**
 * Load all bets categories running atm with a current user's bet
 * @param datetime $date
 * @param int $playerId
 * @return array of containers $containersResults
 */
function loadBetsContainerAndCategoriesByPlayer ($date, $playerId){

    
    $prerowbets = " SELECT DISTINCT Categories.Container AS ContainerId, Containers.Name AS ContainerName, Categories.CategoryId AS CategoryId, Categories.Name AS CategoryName
                    FROM Containers
                    LEFT JOIN Categories ON Containers.Id = Categories.Container
                    LEFT JOIN Matchs ON Matchs.Category = Categories.CategoryId
                    LEFT JOIN Paris ON Paris.MatchId = Matchs.MatchId
                    WHERE Paris.Playerid = '".$playerId."'
                    AND Paris.Done != '0'
                    AND Containers.ShowTime < '".$date.
                    "' AND Containers.EndTime > '".$date."'
                    ORDER BY Containers.Name ASC";

    //$containers = main_db_query ("SELECT * FROM Containers WHERE ShowTime<'".$date."'  AND EndTime>'".$date."'");
    $containers = main_db_query ($prerowbets);
    $nbContainers = db_num_rows ($containers);
    $containersResults = array();

    while ($container = db_fetch_assoc($containers)){
        $containersResults[]=$container;
    }

    return $containersResults;

}

/**
 * Load all bets categories with bets running atm
 * @param datetime $date
 * @return array of containers $containersResults
 */
function loadPronosCategories ($date){

    $prerowbets = "SELECT DISTINCT Categories.Container AS Id, Containers.Name AS Name FROM Containers ".
                                                        " LEFT JOIN Categories ON Containers.Id=Categories.Container ".
							" LEFT JOIN Matchs ON Matchs.Category=Categories.CategoryId ".
							" WHERE Matchs.Date > '".$date."' ORDER BY Containers.Name ASC";
    
    //$containers = main_db_query ("SELECT * FROM Containers WHERE ShowTime<'".$date."'  AND EndTime>'".$date."'");
    $containers = main_db_query ($prerowbets);
    $nbContainers = db_num_rows ($containers);
    $containersResults = array();

    while ($container = db_fetch_assoc($containers)){
        $containersResults[]=$container;
    }

    return $containersResults;

}

/**
 * Load all bets categories with bets running atm
 * @param datetime $date
 * @return array of containers $containersResults
 */
function loadPronosContainersAndCategories ($date, $playerId){

    /*$prerowbets = "SELECT DISTINCT Categories.Container AS ContainerId, Containers.Name AS ContainerName, Categories.CategoryId AS CategoryId, Categories.Name AS CategoryName
                                                        FROM Containers
                                                        LEFT JOIN Categories ON Containers.Id=Categories.Container
                                                        LEFT JOIN Matchs ON Matchs.Category=Categories.CategoryId
                                                        WHERE (Matchs.Date > '".$date."' OR EXISTS (SELECT * FROM Matchs WHERE Etat = '1'))
                                                        ORDER BY Containers.Name ASC, Categories.Name ASC";*/
    $prerowbets = " SELECT DISTINCT Categories.Container AS ContainerId, Containers.Name AS ContainerName,
                    Categories.Image AS ContainerImage, Categories.CategoryId AS CategoryId,
                    Categories.Name AS CategoryName, Matchs.*
                    FROM Categories
                    LEFT JOIN Containers ON Containers.Id=Categories.Container
                    LEFT JOIN Matchs ON Matchs.Category=Categories.CategoryId
                    WHERE Categories.EndTime > '".$date."' AND Categories.ShowTime < '".$date."'
                    ORDER BY Containers.Name ASC, Matchs.Date ASC";

    

    //$containers = main_db_query ("SELECT * FROM Containers WHERE ShowTime<'".$date."'  AND EndTime>'".$date."'");
    /*$containers = main_db_query ($prerowbets);
    $nbContainers = db_num_rows ($containers);
    $containersResults = array();

    while ($container = db_fetch_assoc($containers)){

        

        $temp = getInfosCategory($container['CategoryId'], $playerId);
        $container['FirstMatch']=$temp['FirstMatch'];
        $container['Color']=$temp['Color'];
        
        $containersResults[]=$container;
    }

    return $containersResults;*/

    $matchs = main_db_query ($prerowbets);
    $nbmatchs = db_num_rows ($matchs);
    $containersResults = array();
    $memCategoryId = null;
    $memCategory = null;

    $current_european_date = date("d/m/Y H:i:s", my_local_time());
    $current_european_date = substr($current_european_date,0,10);
    $date = date("Y-m-d H:i:s", my_local_time());

    $tabAllBets = array();
    $tabAllAmounts = array();
    
	if ($sess->memberid != -1)
	{
		$rowsAllBets = main_db_query("SELECT MatchId, Bet, Amount FROM Paris WHERE PlayerId='".$player[Id]."' AND Done = 0");
		getKTabFromRows($rowsAllBets, $tabAllBets, $tabAllAmounts);
	}


    while ($match = db_fetch_assoc($matchs)){

        if ($memCategory[$match['CategoryId']]['CategoryId'] != $match['CategoryId']){

            $memCategory[$match['CategoryId']]['CategoryId'] = $match['CategoryId'];
            $memCategory[$match['CategoryId']]['ContainerImage'] = $match['ContainerImage'];
            $memCategory[$match['CategoryId']]['ContainerId'] = $match['ContainerId'];
            $memCategory[$match['CategoryId']]['CategoryName'] = $match['CategoryName'];
            $memCategory[$match['CategoryId']]['ContainerName'] = $match['ContainerName'];
            $memCategory[$match['CategoryId']]['FirstMatch'] = $match['Date'];

            $memCategory[$match['CategoryId']]['allBet'] = true;
            $memCategory[$match['CategoryId']]['todayGame'] = false;
            $memCategory[$match['CategoryId']]['waiting'] = true;
        }
        else {
            
            if ($memCategory[$match['CategoryId']]['FirstMatch'] > $match['Date']) {

                $memCategory[$match['CategoryId']]['FirstMatch'] = $date;
            }
        }
        
        // each match
        // date management
        $matchTime = time_diff($date, $match['Date']);
        
        // first match of the day
        //$memCategory[$match['CategoryId']]['FirstMatch'] = $match['Date'];

        $memCategory[$match['CategoryId']]['aAfficher'] = true;

        if ($memCategory[$match['CategoryId']]['FirstMatch'] == 'NULL'){
            $memCategory[$match['CategoryId']]['aAfficher'] = false;
        }


        // if match already bet, get back the prono
        if ($tabAllBets[$match['MatchId']] != "")
        {
            $matchPronos = "(".$tabAllBets[$match['MatchId']].")";
        }
        else
            $matchPronos = "";

        // display color of the category
        // waiting results
        if ($matchTime >= -7200)
        {
            $memCategory[$match['CategoryId']]['waiting'] = false;

            // during the match (2h), display live
            if ($matchTime < 0){
                $memCategory[$match['CategoryId']]['todayGame'] = true;
            }

            if ($matchTime >= 0 )
            {
                
                // day of the match
                if ($current_european_date==date_mysql($match['Date'])) {
                    
                    $memCategory[$match['CategoryId']]['todayGame'] = true;
                }
                else {
                    // waiting pronos
                    if( $matchPronos == "" )
                        $memCategory[$match['CategoryId']]['allBet'] = false;
                }
            }
        }

        // Colors of bets choice
        $WAITING_RESULTS = "#9f9f9f";
        $LIVE_MATCH = "#ff9933";
        $TODAY_MATCH = "#FF0000";
        $ALREADY_BET = "#008000";
        $NOT_ALREADY_BET = "#0000FF";

        if ($memCategory[$match['CategoryId']]['todayGame'])
            $memCategory[$match['CategoryId']]['Color'] = $TODAY_MATCH;
        elseif ($memCategory[$match['CategoryId']]['waiting'])
            $memCategory[$match['CategoryId']]['Color'] = $WAITING_RESULTS;
        elseif ($memCategory[$match['CategoryId']]['allBet'])
            $memCategory[$match['CategoryId']]['Color'] = $ALREADY_BET;
        elseif (!$memCategory[$match['CategoryId']]['allBet'])
            $memCategory[$match['CategoryId']]['Color'] = $NOT_ALREADY_BET;


        
    }

    //return $containersResults;
    return $memCategory;

}

/**
 * Load category by id
 * @param int id
 * @return category
 */
function loadCategoryById($id){

    $prerowbets = " SELECT DISTINCT Categories.Container AS ContainerId, Categories.Image AS ContainerImage, Containers.Name AS ContainerName, Categories.CategoryId AS CategoryId, Categories.Name AS CategoryName
                    FROM Containers
                    LEFT JOIN Categories ON Containers.Id=Categories.Container
                    LEFT JOIN Matchs ON Matchs.Category=Categories.CategoryId
                    WHERE Categories.CategoryId = '".$id."'";

    //$containers = main_db_query ("SELECT * FROM Containers WHERE ShowTime<'".$date."'  AND EndTime>'".$date."'");
    $containers = main_db_query ($prerowbets);
    $nbContainers = db_num_rows ($containers);
    $containersResults = array();

    while ($container = db_fetch_assoc($containers)){
        $containersResults=$container;
    }

    return $containersResults;

}

/**
 *
 * Load results of a container defined by it id
 *
 * @param int $containerId
 * @param datetime $date
 * @param int $player
 * @return array of results $results
 */
function loadResultsByContainer($containerId, $date, $nbMatchsToShow = 10, $playerId){

    $prerowbets = "SELECT Paris.PlayerId, Paris.Bet, Paris.MatchId, Paris.Amount, Paris.Done, Matchs.Result, Matchs.Team1, Matchs.Team2, Matchs.Rate1, Matchs.Rate2, Categories.Name, Matchs.Result, Matchs.MatchId, Matchs.Date AS Date, Containers.Name AS Container, Categories.Image AS Image FROM Paris ".
							" LEFT JOIN Matchs ON Matchs.MatchId=Paris.MatchId ".
							" LEFT JOIN Categories ON Matchs.Category=Categories.CategoryId ".
							" LEFT JOIN Containers ON Containers.Id=Categories.Container ".
							" WHERE Paris.Done!='0' AND PlayerId='".$playerId."' AND Categories.Container = '".$containerId."' ORDER BY Matchs.Date DESC LIMIT 0, ".$nbMatchsToShow;

    //$tour = db_fetch_array(main_db_query ("SELECT * FROM Tours WHERE ShowTime<'".$date."' AND EndTime>'".$date."'"));
    //$endSession = false;
    $rowbets = main_db_query($prerowbets);
    //$nb_paris = 0;

    
    $nb_paris = db_num_rows($rowbets);

    $results = array ();
    $i=0;
    
    if ($nb_paris != 0) {
        while ($bet = db_fetch_array($rowbets))
        {
            $results[$i]=$bet;
            $results[$i]['gain'] = calcule_gain_prono($bet[Result],$bet[Bet],1,$bet[Rate1],$bet[Rate2]);
            $results[$i]['gain_points'] = calcule_gain_prono($bet[Result],$bet[Bet],$bet[Amount],$bet[Rate1],$bet[Rate2]);
            $i++;
        }
    }
    else {
        $results = 0;
    }

    return $results;
}

/**
 *
 * Load Pronos by container
 * 
 * @param int $containerId
 * @param int $playerId
 * @return array $results
 */
function loadGamesToPronoByContainer($containerId, $playerId, &$tabAllBets, &$tabAllAmounts){



    #################### PATCH SEREI #######################
    $matchs = unserialize(base64_decode(getExploitationFile("afficher_container_".$containerId)));
    #$matchs = unserialize(getExploitationFile("afficher_patch", true));
    $nbMatchsPatch = count($matchs);
    ####################  END PATCH  #######################

    ####################    OPTIM    #######################
    $tabAllBets = array();
    if ($sess->memberid != -1)
    {
            $rowsAllBets = main_db_query("SELECT MatchId, Bet, Amount FROM Paris WHERE PlayerId='".$playerId."' AND Done = 0");
            getKTabFromRows($rowsAllBets, $tabAllBets, $tabAllAmounts);
    }
    ####################  END OPTIM  #######################

    if ($nbMatchsPatch == 0){
        return $matchs = 0;
    }

    return $matchs;
}

function get_club_classement($name){
    $classement_clubs = main_db_query("SELECT * FROM Classement_Clubs WHERE Name='".addslashes($name)."' LIMIT 0,1");
    return db_fetch_array($classement_clubs);
}

function get_club_rank($classement_club)
{
    $total = db_fetch_array(main_db_query("SELECT Count(Id) AS Total FROM Classement_Clubs WHERE Name!='".$classement_club['Name']."' AND ContainerId='".$classement_club['ContainerId']."' AND (Points>'".$classement_club['Points']."' OR (Points = '".$classement_club['Points']."' AND ButsDifference>'".$classement_club['ButsDifference']."'))"));
    return $total[Total]+1;
}

/**
 *
 * Load Pronos by container
 *
 * @param int $containerId
 * @param int $playerId
 * @return array $results
 */
function loadGamesToPronoByCategory($containerId, $categoryId, $playerId, &$tabAllBets, &$tabAllAmounts, &$classement_clubs = null){

    #################### PATCH SEREI #######################
    $matchs = unserialize(base64_decode(getExploitationFile("afficher_container_".$containerId)));
    #$matchs = unserialize(getExploitationFile("afficher_patch", true));
    $nbMatchsPatch = count($matchs);
    ####################  END PATCH  #######################

    ####################    OPTIM    #######################
    $tabAllBets = array();
    $tabAllAmounts = array();
    if ($sess->memberid != -1)
    {
            $rowsAllBets = main_db_query("SELECT Matchs.MatchId, Bet, Amount FROM Paris ".
                    " LEFT JOIN Matchs ON Matchs.MatchId=Paris.MatchId ".
                    " WHERE PlayerId='".$playerId."' AND Matchs.Category = ".$categoryId." AND Done = 0");
            
            if (db_num_rows($rowsAllBets) != 0){
                getKTabFromRows($rowsAllBets, $tabAllBets, $tabAllAmounts);
            }
    }
    
    ####################  END OPTIM  #######################

    $results = array();
    $classement_clubs = array();
    
    for ($i=0; $i < $nbMatchsPatch; $i++){
        if ($matchs[$i][Category] == $categoryId)
            $results[] = $matchs[$i];

        if (($matchs[$i][Category] == 1 ||$matchs[$i][Category] == 2) || $classement_clubs != null ){
            $classement_clubs[$matchs[$i]['Team1']]=get_club_classement($matchs[$i]['Team1']);
            $classement_clubs[$matchs[$i]['Team1']]['rank']=get_club_rank($matchs[$i]['Team1']);
            $classement_clubs[$matchs[$i]['Team2']]=get_club_classement($matchs[$i]['Team2']);
            $classement_clubs[$matchs[$i]['Team2']]['rank']=get_club_rank($matchs[$i]['Team2']);
        }
    }

    return $results;
}



/**
 *
 * calc stats about players bets
 *
 * @param int $MatchId
 * @param int $victoire1
 * @param int $victoire2
 * @param int $matchNul
 * @return array of stats
 */
function calcStats ($MatchId, &$victoire1, &$victoire2, &$matchNul){

    $stats = array ();

    // get back bets stats of players
    $stats =  db_fetch_array(main_db_query("SELECT * FROM MatchsStats WHERE MatchId='".$MatchId."'"));

    // calc stats
    if ($stats[Win1] + $stats[Win2] + $stats[NullGame] != 0)
    {
            $victoire1 = 100. * $stats[Win1] / ($stats[Win1] + $stats[Win2] + $stats[NullGame]);
            $victoire2 = 100. * $stats[Win2] / ($stats[Win1] + $stats[Win2] + $stats[NullGame]);
            $matchNul = 100. * $stats[NullGame] / ($stats[Win1] + $stats[Win2] + $stats[NullGame]);
    }
    else
    {
            $victoire1 = $victoire2 = $matchNul = 100./3;
    }
    
    return $stats;
}

function flag($equip)
{
	global $TEAMS,$TEAM_NAMES,$TEAM_LIST;
	
	$res = "x.gif";
	//for ($i=0;$i<$TEAMS;$i++)
	foreach($TEAM_NAMES AS $Id=>$Name)
	{
		if (strcmp($equip,$Name)==0)
		{
			$res = $TEAM_LIST[$Id];
			break;
		}
	}
	
	return $res;
}



/**
 * Build some parameters of the match & the player
 *
 * @param int $matchId
 * @param int $playerId
 * @param bool $betIsClosed
 * @param bool $matchIsClosed
 * @param int $consumed_points
 * @param int $remaining_points
 * @param date $current_european_date
 * @param date $matchDate
 * @param array $once
 */
function getOldMatchBetById ($matchId, $playerId, $current_european_date, $matchDate, &$betIsClosed, &$matchIsClosed, &$consumed_points, &$remaining_points, &$once){
    
    # si c'est une modification du pari, on récupère les infos du pari
    $once = db_fetch_array(main_db_query("SELECT * FROM Paris WHERE MatchId='".$matchId."' AND PlayerId='". $playerId."'"));

    //echo "$current_european_date , $matchDate, $once";
    # vérif si on peut encore jouer
    $betIsClosed = checkBetIsClosed($current_european_date , $matchDate, $once);
    $matchIsClosed = checkMatchIsClosed($current_european_date , $matchDate, $once);
    
    # si le pari existe deja, on est soit en reload (cas ou validate n'est pas vide)
    # soit en revue du pari (cas validate vide)
    # dans les deux cas un update sera effectué, on peut donc remettre les points Ã  l'état précédent
    /*if (($once[MatchId]==$matchId)&&($once[PlayerId]==$playerId) && !$betIsClosed && !$matchIsClosed)
    {
            $consumed_points = $consumed_points - $once[Amount];
            $remaining_points = $remaining_points + $once[Amount];
    }*/
}

/**
 * Get infos about category by id to display it with the right color and date
 * 
 * @param int $CategoryId
 * @param int $playerId
 * @return array
 */
function getInfosCategory ($CategoryId, $playerId) {

    $rqt_infosMatchCategory = " SELECT DISTINCT Matchs.*
                                FROM  Matchs
                                WHERE Matchs.Category= ".$CategoryId."
                                ORDER BY Matchs.Date DESC";

    $res_infosMatchCategoy = main_db_query($rqt_infosMatchCategory);

    $rowsAllBets = main_db_query(   "SELECT Matchs.MatchId, Bet, Amount FROM Paris ".
                                    " LEFT JOIN Matchs ON Matchs.MatchId=Paris.MatchId ".
                                    " WHERE PlayerId='".$playerId."' AND Matchs.Category = ".$CategoryId." AND Done = 0");
    $tabAllBets=array();
    getKTabFromRows($rowsAllBets, $tabAllBets, $tabAllAmounts);

    $nb_res = db_num_rows($res_infosMatchCategoy);

    $allBet = true;
    $todayGame = false;
    $waiting = true;

    $current_european_date = date("d/m/Y H:i:s", my_local_time());
    $current_european_date = substr($current_european_date,0,10);
    $date = date("Y-m-d H:i:s", my_local_time());

    if ($nb_res != 0){
        $result = array();
        while ($myMatch = db_fetch_array($res_infosMatchCategoy) ){
            
            // date management
            $matchTime = time_diff($date, $myMatch['Date']);

            // first match of the day
            $result['FirstMatch'] = $myMatch['Date'];

            // if match already bet, get back the prono
            if ($tabAllBets[$myMatch[MatchId]] != "")
            {
                $matchPronos = "(".$tabAllBets[$myMatch[MatchId]].")";
            }
            else
                $matchPronos = "";

            // display color of the category
                    // waiting results
            if ($matchTime >= -7200)
            {
                $waiting = false;

                // during the match (2h), display live
                if ($matchTime < 0){
                    $todayGame = true;
                }

                if ($matchTime >= 0 )
                {

                    // day of the match
                    if ($current_european_date==date_mysql($myMatch[Date])) {
                        $todayGame = true;
                    }
                    else {
                        // waiting pronos
                        if( $matchPronos == "" )
                            $allBet = false;
                    }
                }
            }


            

        }
    }

    // Colors of bets choice
$WAITING_RESULTS = "#9f9f9f";
$LIVE_MATCH = "#ff9933";
$TODAY_MATCH = "#FF0000";
$ALREADY_BET = "#008000";
$NOT_ALREADY_BET = "#0000FF";

    if ($todayGame)
        $result['Color'] = $TODAY_MATCH;
    elseif ($waiting)
        $result['Color'] = $WAITING_RESULTS;
    elseif ($allBet)
        $result['Color'] = $ALREADY_BET;
    elseif (!$allBet)
        $result['Color'] = $NOT_ALREADY_BET;



    return $result;
  
}

function getContainerByCategoryId ($id){
    $rqt_container = "Select Container From Categories Where CategoryId ='".$id."'";
    $res_container = db_fetch_array(main_db_query($rqt_container));

    return $res_container['Container'];
}



?>
