<?php

include '/var/www/phpLibs/databaseLib.php';
include '/var/www/phpLibs/oddsUpdateLib.php';

$odds = $_POST["odds"];

$mysqli = getMysqlliConn("BetRadarData");

if (mysqli_connect_errno()) {
    printf("<br />Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//  $odds = '<BetRadarData><Line0 User="24"><Odd0 MatchID="1380070" OddsType="10" Outcome="1" SpecialBetValue="">4.35</Odd0><Odd1 MatchID="1380070" OddsType="10" Outcome="X" SpecialBetValue="">3.45</Odd1><Odd2 MatchID="1380070" OddsType="10" Outcome="2" SpecialBetValue="">1.8</Odd2></Line0></BetRadarData>';

/*
<Line0 Delete="1" User="-5" MatchID="3672033" OddsType="52" SpecialBetValue="159.5" IsDynamic="1">
	<Odd0 Outcome="Over" Odds="0" GenericOdds="1.91"/>
	<Odd1 Outcome="Under" Odds="0" GenericOdds="2.1"/>
</Line0>
<Line1 Delete="1" User="-5" MatchID="3672033" OddsType="52" SpecialBetValue="156.5" IsDynamic="0">
	<Odd0 Outcome="Over" Odds="0" GenericOdds="1.68"/>
	<Odd1 Outcome="Under" Odds="0" GenericOdds="2.47"/>
</Line1>
*/


$odds = urldecode($odds);

$arr = xml2array($odds);

$handle = 0;

// Log file path
$logFilePath = '/var/www/html/phpHelpers/log.txt'; // __DIR__ gets the directory of the current script


//First, we need to delete all previous odds for game types that are "IsDeleteRequired = true"
foreach($arr as $line) {
	$delete     = $line["attributes"]["Delete"];
	$matchID    = $line["attributes"]["MatchID"];
	$oddsType   = $line["attributes"]["OddsType"];


	if($delete) {
		try {
			$deleteProcedure = "deleteOddsForType_gui('".$matchID."', '".$oddsType."')";
			$bool = executeFunction($mysqli, $deleteProcedure);
			if($bool != 1)
				throw new Exception('Execution of '.$updateProcedure.' failed.');
		} catch (Exception $e) {
			echo 'Caught exception: ',  $e->getMessage(), "\n";
			$mysqli->close();
			die();
		}
	}
}
$baseOdds = [];
if(count($arr)>0){
	$matchID    = $arr['Line0']["attributes"]["MatchID"];
	if(isset($matchID)){
		$niz = executeProcedure($mysqli, "getBaseMarketsForMatch(".$matchID.")");
		foreach($niz as $b){
			array_push($baseOdds,$b[0]);
		}
	}
	
}


foreach($arr as $line) {
    $user = $line["attributes"]["User"];
    
    $matchID    = $line["attributes"]["MatchID"];
    $oddsType   = $line["attributes"]["OddsType"];
    $sbv        = $line["attributes"]["SpecialBetValue"];
    $dynamic     = $line["attributes"]["IsDynamic"];
    $checked     = $line["attributes"]["IsChecked"];

    $sbv = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $sbv);
    $sbv = addslashes($sbv);

    $res = executeProcedure($mysqli, "getNextGroupID()");
    $groupID = $res[0][0];

    if($dynamic) {
		try {
			$insertDynamicProcedure = "insertDynamicSBV('".$matchID."', '".$oddsType."', '".$sbv."')";
			$bool = executeFunction($mysqli, $insertDynamicProcedure);
			if($bool != 1)
			throw new Exception('Execution of '.$updateProcedure.' failed.');
		} catch (Exception $e) {
			echo 'Caught exception: ',  $e->getMessage(), "\n";
			$mysqli->close();
			die();
		}
	}

    foreach($line["value"] as $oddInfo) {
        $outcome = $oddInfo["attributes"]["Outcome"];
        $odd = $oddInfo["attributes"]["Odds"];
        $genericOdd = $oddInfo["attributes"]["GenericOdds"];
	 	$oldOdd = $oddInfo["attributes"]["OldOdds"];
        $oldGenericOdd = $oddInfo["attributes"]["OldGenericOdds"];



        // Check if condition is fulfilled
		if ($oddsType === '9994' || $oddsType === '9995' || $oddsType === '9996') {
			
		    // Open or create the log file in append mode
		    $file = fopen($logFilePath, 'a');

		    // Get the current timestamp
		    $timestamp = date('Y-m-d H:i:s');

		    // Message to log
		    $message = 'Time: '.$timestamp.' - marketId: '.$oddsType.'; outcome: '.$outcome.'; odd: '.$odd.'; genericOdd: '.$genericOdd.'; oldOdd: '.$oldOdd.'; oldGenericOdd: '.$oldGenericOdd."\n";

		    // Write the message to the log file
		    fwrite($file, $message);

		    // Close the file
		    fclose($file);
		}

		if(!isset($oldGenericOdd))
			$oldGenericOdd = 0;

		if(!isset($oldOdd))
			$oldOdd = 0;

        //  matchID, oddsType.getOddsType(), outcome, sbv, 1, odd
        $updateProcedure = "appUpdateOdd('".$matchID."', '".$oddsType."', '".$outcome."', '".$sbv."', '".$odd."', '".$genericOdd."')";
        //$logProcedure = "writeIntoLog('".$matchID."', '".$oddsType."', '".$outcome."', '".$sbv."', '".$odd."', '".$genericOdd."', 'update', '".$user."', '".$groupID."')";
	 	$logProcedure = "Logs.writeIntoLog('".$matchID."', '".$oddsType."', '".$outcome."', '".$sbv."', '".$oldOdd."', '".$oldGenericOdd."', '".$odd."', '".$genericOdd."', 'user update', '".$groupID."', 'GUI', '".$user."')";

        try {
	        if($handle == 0) {
	            $setExportedProcedure = "appUpdateExportedFieldOfMatch('".$matchID."', '-1')";
	            $bool = executeFunction($mysqli, $setExportedProcedure);
	            $handle = 1;
	            if($bool != 1) {
	            	$file = fopen($logFilePath, 'a');
	            	$message = 'Execution of '.$setExportedProcedure.' failed for marketId: '.$oddsType.' outcome: '.$outcome."\n";

				    // Write the message to the log file
				    fwrite($file, $message);

				    // Close the file
				    fclose($file);
	                throw new Exception($message);
	        	}
        	}

        	$bool = executeFunction($mysqli, $updateProcedure);
        	if ($oddsType === '9994' || $oddsType === '9995' || $oddsType === '9996') {
        		$file = fopen($logFilePath, 'a');
	            	$message = 'Function '.$updateProcedure." executed. \n";

				    // Write the message to the log file
				    fwrite($file, $message);

				    // Close the file
				    fclose($file);
        	}

        	if($bool != 1) {
	        	$file = fopen($logFilePath, 'a');
	        	$message = 'Execution of '.$updateProcedure.' failed for marketId: '.$oddsType.' outcome: '.$outcome."\n";

			    // Write the message to the log file
			    fwrite($file, $message);

			    // Close the file
			    fclose($file);
	            throw new Exception($message);
        	}

			if(in_array($oddsType,$baseOdds) || (!in_array($oddsType,$baseOdds) && $odd != 0 && $odd != $oldOdd && $checked)){
				$bool = executeFunction($mysqli, $logProcedure);
				if($bool != 1) {
					$file = fopen($logFilePath, 'a');
		        	$message = 'Execution of '.$logProcedure.' failed for marketId: '.$oddsType.' outcome: '.$outcome."\n";

				    // Write the message to the log file
				    fwrite($file, $message);

				    // Close the file
				    fclose($file);
		            throw new Exception($message);
				}
			}
	        } catch (Exception $e) {
	        	$file = fopen($logFilePath, 'a');
	        	$message = 'Caught exception: '.$e.getMessage." \n";

			    // Write the message to the log file
			    fwrite($file, $message);

			    // Close the file
			    fclose($file);
	            echo 'Caught exception: ',  $e->getMessage(), "\n";
	            $mysqli->close();
	            die();
	        }
    }
}

echo "OK";

$mysqli->close();

?>
