<?php

ini_set("log_errors", 1);
ini_set('error_reporting', E_ALL);

define("MYSQLSERVER","127.0.0.1");
define("MYSQLLOGIN","webbike");
define("MYSQLPASSWORD","honda");
define("BASE_DE_DONNEES","webbike");

require_once "functions.php";
/*
$TRUNCATE ="TRUNCATE service_suivis";
$TRresult = mysql_query($TRUNCATE) or die('Erreur SQL !<br>'.$TRUNCATE.'<BR>'.Connection::getConnection()->errorInfo());
*/
$requette = "SELECT DISTINCT NoChasis FROM `atelier1` WHERE (( Date < NOW() - INTERVAL 20 MONTH ) AND NOT ( Date < NOW() - INTERVAL 30 MONTH)) AND Id_Service !='0' AND NoClient != '1260' ORDER BY NoAtelier DESC ";
$resultat = Connection::executeRawQueryWithfetchAll($requette) or die('Erreur SQL !<br>'.$requette.'<BR>'.Connection::getConnection()->errorInfo());
$numrows = count($resultat);

for($i=0; $i < $numrows;$i++){
  $ligne = $resultat[ $i ];
  $query2="SELECT * FROM `atelier1` WHERE NoChasis='".$ligne['NoChasis']."' AND Id_Service !='0' AND NoClient != '1260' ORDER BY NoAtelier DESC LIMIT 1";//error_log($query2);
  $result2 = Connection::executeRawQueryWithfetchAll($query2) or die('Erreur SQL !<br>'.$query2.'<BR>'.Connection::getConnection()->errorInfo());
	$numrows2 = count($result2);

	for($p=0; $p < $numrows2;$p++){
		$ligne2 = $result2[ $p ];

    	$Rachat = ChckRachat($ligne2['NoChasis']);
		$CameBack = ChKifCameBk($ligne2['NoChasis']);
		$AlreadyAnEntry = ChckIfAlreadyAnEntry($ligne2['NoChasis']);

		if((!$CameBack) && (!$Rachat) && (!$AlreadyAnEntry) ){
        $LastSrvKM = GetLastSrvKM($ligne2['Id_Service']);
        $NxtSrv = VrfNxtSrvc($ligne2["Id_Vhc"], $LastSrvKM);
        $vhcInfos = GetVehiculeInfos($ligne2['NoChasis']);
        
		$Email = GetEmailSVC($ligne2['NoClient']);
		if(!$Email)$Email = "NoEmail";
		
	    $query = "INSERT INTO `service_suivis` ( S_ID, S_Date, S_Chassis,S_Vehicule, S_status, S_Commande, S_NoClient, S_Nom, S_Prenom, S_phone, S_email, S_vhc, S_srvID , S_Km , S_Nxsrvc)
	       VALUE ( '".$ligne2['NoAtelier']."', '".$ligne2['Date']."' ,'".$ligne2['NoChasis']."','".$vhcInfos["Model"]."', 'OnHold' , '".$ligne2['NoCommande']."','".$ligne2['NoClient']."','".Connection::getConnection()->quote($ligne2['Nom'])."','".Connection::getConnection()->quote($ligne2['Prenom'])."','".$ligne2['Telephone']."','".$Email."','".$ligne2['Id_Vhc']."', '".$ligne2['Id_Service']."', '".$ligne2['Km']."', '".$NxtSrv."' )" ;//error_log($query);

	    $result = Connection::executeRawQuery($query) or die('Erreur SQL !<br>'.$query.'<BR>'.Connection::getConnection()->errorInfo());
	    }
	}
}

?>
