<?php
set_time_limit(0);

/*	! ATTENTION ! NE PAS FAIRE DE REFERENCE A UNE DONNEE DU FICHIER BDD.PHP OU
 *	DE L'UTILISATEUR COURANT CAR LE SCRIPT EST LANCE PAR L'ATTAQUANT ET PAR
 *	L'ATTAQUé.
 */

require_once(_FCORE."../game/Class/class.rapport.php");

function resteVaisseau($tableau){
$ct = count($tableau);
	for ($i = 0; $i < $ct; $i++) {
		if (!empty($tableau[$i])) return true;
	}
	return false;
}

$Hgalaxie = $queryPlanete["galaxie"];
$Hss = $queryPlanete["ss"];
$Hposition = $queryPlanete["position"];

$bdd->connexion();
$queryFlottes = $bdd->query("SELECT * FROM $table_flottes WHERE id_user = '$id_user' OR (end_galaxie = '$Hgalaxie' AND end_ss = '$Hss' AND end_position = '$Hposition');");
$bdd->deconnexion();
$nbFlottes = $bdd->num_rows;
for ($i = 0; $i < $nbFlottes; $i++) {
	//Récupération des principales variables de la flotte
	$id_flotte = $queryFlottes[$i]['id'];
	$mission = $queryFlottes[$i]['mission'];
	$end_galaxie = $queryFlottes[$i]['end_galaxie'];
	$end_ss = $queryFlottes[$i]['end_ss'];
	$end_position = $queryFlottes[$i]['end_position'];
	$end_time = $queryFlottes[$i]['start_time'] + $queryFlottes[$i]['end_time'];
	//On vérifie que la planète cible existe

	$bdd->connexion();
	$queryEN = $bdd->unique_query("SELECT * FROM $table_planete WHERE galaxie = '$end_galaxie' AND ss = '$end_ss' AND position = '$end_position';");
	if (!$queryEN && $mission != 3 && $mission != 6 && time() > $end_time) {
		$bdd->query("UPDATE $table_flottes SET effectue = '1', mission = '6', ret_time = '".($end_time + $queryFlottes[$i]['end_time'])."' WHERE id = $id_flotte;");
		$titreA = 'Impossible d\'effectuer la mission';
		$bdd->escape($titreA);
		$rapportA = 'La flotte '.$queryFlottes[$i]['nom_flotte'].' n\'a pas pu effectuer sa mission correctement car lorsqu\'elle est arrivée sur place, la planète était déserte.';
		$bdd->escape($rapportA);
		$db->query("INSERT INTO $table_mail (destinataire, expediteur, sujet, contenu, temps) VALUES(".$queryFlottes[$i]['id_user'].", '', '$titreA', '$rapportA', '".$end_time."')");
		$bdd->deconnexion();
		continue;
	}
	elseif (!$queryEN && $mission != 3 && $queryFlottes[$i]['effectue'] != 1) {
		$bdd->deconnexion();
		continue;
	}
	$bdd->deconnexion();
	$ENidPlan = $queryEN['id'];

	//La flotte est prête a effectuer une action
	if ($queryFlottes[$i]['effectue'] != 1 && time() >= $queryFlottes[$i]['start_time'] + $queryFlottes[$i]['end_time'] && !empty($queryFlottes[$i]['end_time'])) {
		//Mission Attaquer
		if ($mission == 1) {
			require_once(_FCORE."../game/Class/class.combat.php");
			$bdd->connexion();
			//On regarde si le combat a déjà commencé
			if ($queryFlottes[$i]['effectue'] == 2) {
				if ($queryCombat = $bdd->unique_query("SELECT * FROM $table_flottes_combats WHERE refflotte = '$id_flotte';")) {
					//On vérifie si on lance le tour suivant ou non
					if (time() >= $queryCombat['timestamp']) {
						//On modifie le timestamp pour ne pas que le combat se déroule deux fois
						$timebloque = time() + 5;
						$bdd->query("UPDATE $table_flottes_combats SET timestamp = '$timebloque' WHERE refflotte = '$id_flotte';");

						//Récupération du combat
						$combat = unserialize($queryCombat['serialize']);
						//Mise à jour des tactiques
						if (!empty($queryFlottes[$i]['tactiqueAT'])) $combat->changerTactiqueAT($queryFlottes[$i]['tactiqueAT']);
						if (!empty($queryFlottes[$i]['tactiqueEN'])) $combat->changerTactiqueEN($queryFlottes[$i]['tactiqueEN']);
					}
					else continue;
				}
				else {
					$time = time();
					$bdd->query("UPDATE $table_flottes SET effectue = '1', ret_time = end_time + $time WHERE id = '$id_flotte';");
					file_log("Erreur dans le script de combat, la flotte de ".trouvNom($queryFlottes[$i]['id_user'])."(".$queryFlottes[$i]['id_user'].") a été renvoyé au point de départ.", 1);
					header('Location: ./?erreurcombat');
					exit;
				}
			}
			else {
				//On génére un nouveau combat
				$combat = new Combat($queryFlottes[$i], $queryEN, $queryEN, array(trouvInfo($queryFlottes[$i]['id_user'], 'blindage'), trouvInfo($queryEN['id_user'], 'blindage')));
				$bdd->query("UPDATE $table_flottes SET effectue = '2' WHERE id = '$id_flotte';");
			}
			$bdd->deconnexion();

			while($combat->timestamp <= time()) {
				//Préparation du rapport
				$rapport = new Rapport($mission, $queryFlottes[$i]['id_user'], $queryEN['id_user'], $combat->timestamp);

				$combat->Ntour++;
				$rapport->addInfo($combat->ATvais, 0);
				$rapport->addInfo($combat->ENvais, 1);
				$rapport->addInfo($combat->ENdef, 2);
				$rapport->addInfo($combat->Ntour, 3);
				$rapport->addInfo($queryEN, 4);
				$rapport->addInfo($queryFlottes[$i], 5);

				//Récupération des paramètres de la tactique de l'attaquant
				$arraytactique = tactique($combat->ATtactique);
				//On régénére les boucliers de l'attaquant et on calcul l'attaque de l'attaquant
				$ATattaque = $combat->calcAttaque($arraytactique[2] + $combat->regenereBC($arraytactique[1], true, !$arraytactique[3], trouvInfo($queryFlottes[$i]['id_user'], 'blindage')), true, trouvInfo($queryFlottes[$i]['id_user'], 'armement'));

				//Récupération des paramètres de la tactique du défenseur
				$arraytactique = tactique($combat->ENtactique);
				//On régénére les boucliers de l'attaquant et on calcul l'attaque de l'attaquant
				$ENattaque = $combat->calcAttaque($arraytactique[2] + $combat->regenereBC($arraytactique[1], false, !$arraytactique[3], trouvInfo($queryEN['id_user'], 'blindage')), false, trouvInfo($queryEN['id_user'], 'armement'));

				//On lance l'attaque
				@$ATresult = $combat->attaquerVais($ATattaque, true);
				@$ENresult = $combat->attaquerVais($ENattaque, false);

				if (!$ATresult && $ENresult) { //Attaquant vainqueur
					$combat->ENres['metal'] = $queryEN['metal'];
					$combat->ENres['cristal'] = $queryEN['cristal'];
					$combat->ENres['hydrogene'] = $queryEN['hydrogene'];

					$exportAT = $combat->exportAT(true); $ret_time = $combat->timestamp;
					$exportEN = $combat->exportEN(); $pillm = $combat->pillage[0]; $pillc = $combat->pillage[1]; $pillh = $combat->pillage[2];
					$bdd->connexion();
					$bdd->query("UPDATE $table_flottes SET $exportAT, effectue = '1', ret_time = '$ret_time' + end_time WHERE id = '$id_flotte';");
					$bdd->query("UPDATE $table_planete SET $exportEN, metal = metal - '$pillm', cristal = cristal - '$pillc', hydrogene = hydrogene - '$pillh' WHERE id = '$ENidPlan';");
					$bdd->query("DELETE FROM $table_flottes_combats WHERE refflotte = '$id_flotte';");
					$bdd->deconnexion();
					$rapport->addInfo(array(true, true, false), 6);
				}
				elseif ($ATresult && !$ENresult) { //Défenseur vainqueur
					$exportEN = $combat->exportEN();
					$bdd->connexion();
					$bdd->query("DELETE FROM $table_flottes_combats WHERE refflotte = '$id_flotte';");
					$bdd->query("DELETE FROM $table_flottes WHERE id = '$id_flotte';");
					$bdd->query("UPDATE $table_planete SET $exportEN WHERE id = '$ENidPlan';");
					$bdd->deconnexion();
					$rapport->addInfo(array(true, false, false), 6);
				}
				elseif (!$ATresult && !$ENresult) { //Match nul
					$exportEN = $combat->exportEN();
					$bdd->connexion();
					$bdd->query("DELETE FROM $table_flottes_combats WHERE refflotte = '$id_flotte';");
					$bdd->query("DELETE FROM $table_flottes WHERE id = '$id_flotte';");
					$bdd->query("UPDATE $table_planete SET $exportEN WHERE id = '$ENidPlan';");
					$bdd->deconnexion();
					$rapport->addInfo(array(true, false, true), 6);
				}
				elseif ($combat->Ntour >= 250) { //Match nul
					$exportAT = $combat->exportAT(false); $ret_time = $combat->timestamp;
					$exportEN = $combat->exportEN(); $pillm = $combat->pillage[0]; $pillc = $combat->pillage[1]; $pillh = $combat->pillage[2];
					$bdd->connexion();
					$bdd->query("UPDATE $table_flottes SET $exportAT, effectue = '1', ret_time = '$ret_time' + end_time WHERE id = '$id_flotte';");
					$bdd->query("UPDATE $table_planete SET $exportEN, metal = metal - '$pillm', cristal = cristal - '$pillc', hydrogene = hydrogene - '$pillh' WHERE id = '$ENidPlan';");
					$bdd->query("DELETE FROM $table_flottes_combats WHERE refflotte = '$id_flotte';");
					$bdd->deconnexion();
					$rapport->addInfo(array(true, false, true), 6);
				}
				else $rapport->addInfo(array(false, false, false), 6);

				$rapport->addInfo($combat->ATvais, 7);
				$rapport->addInfo($combat->ENvais, 8);
				$rapport->addInfo($combat->ENdef, 9);

				//Prévision du prochain tour
				$combat->timestamp += 300;
				$rapport->addInfo($combat->timestamp, 10);
				$rapport->addInfo($combat->pillage, 11);

				//On envoie les rapports aux joueurs concernés
				$rapport->send();

				//On arrête la boucle si le combat est terminé
				if ($rapport->var[6][0]) break;
			}
			$debriM = $combat->debriM + $queryEN['debris_met'];
			$debriC = $combat->debriC + $queryEN['debris_cri'];

			$bdd->connexion();
			$bdd->escape($debriM);
			$bdd->escape($debriC);

			$bdd->query("UPDATE $table_planete SET debris_met = $debriM, debris_cri = $debriC WHERE galaxie = '$end_galaxie' AND ss = '$end_ss' AND position = '$end_position';");

			$combat->debriM = 0;
			$combat->debriC = 0;
			if (!$rapport->var[6][0]) { //Si le combat n'est pas terminé
				//On sérialise la classe pour l'exporter
				$serialise = serialize($combat);
				$bdd->escape($serialise);

				//On enregistre le combat dans la base de données
				$timesuite = $combat->timestamp;
				$idFleet = $queryFlottes[$i]['id'];
				if ($queryFlottes[$i]['effectue']) $bdd->query("UPDATE $table_flottes_combats SET serialize = '$serialise', tactiqueAT = '0', tactiqueEN = '0', timestamp = '$timesuite' WHERE refflotte = '$id_flotte';");
				else $bdd->query("INSERT INTO $table_flottes_combats (refflotte, timestamp, serialize, tactiqueAT, tactiqueEN) VALUES('$idFleet', '$timesuite', '$serialise', '0', '0');");
			}
			$bdd->deconnexion();
		}
		//Mission Transporter
		elseif ($mission == 2) {
			$Cmetal = $queryFlottes[$i]['contenu_metal'];
			$Ccristal = $queryFlottes[$i]['contenu_cristal'];
			$Chydrogene = $queryFlottes[$i]['contenu_hydrogene'];
			$bdd->connexion();
			$bdd->query("UPDATE $table_planete SET metal = metal + '$Cmetal', cristal = cristal + '$Ccristal', hydrogene = hydrogene + '$Chydrogene' WHERE galaxie = '$end_galaxie' AND ss = '$end_ss' AND position = '$end_position';");
			$bdd->query("UPDATE $table_flottes SET effectue = '1', contenu_metal = '0', contenu_cristal = '0', contenu_hydrogene = '0' WHERE id = '$id_flotte';");
			$bdd->deconnexion();

			$rapport = new Rapport($mission, $queryFlottes[$i]['id_user'], $queryEN['id_user'], $end_time);
			$rapport->addInfo($queryEN, 0);
			$rapport->addInfo(array($queryFlottes[$i]['contenu_metal'], $queryFlottes[$i]['contenu_cristal'], $queryFlottes[$i]['contenu_hydrogene']), 1);
			$rapport->send();
		}
		//Mission Coloniser
		elseif ($mission == 3) {
			$rapport = new Rapport($mission, $queryFlottes[$i]['id_user'], 0, $end_time);
			$rapport->addInfo(array($end_galaxie, $end_ss, $end_position), 0);

			$rapport->addInfo(true, 1);
			$time = time();
			$cases = mt_rand(125,222);
			$image = mt_rand(1,15);
			$Cmetal = $queryFlottes[$i]['contenu_metal'] + 1000;
			$Ccristal = $queryFlottes[$i]['contenu_cristal'] + 700;
			$Chydrogene = $queryFlottes[$i]['contenu_hydrogene'];

			//Calcul de l'isolement
			$nbPlan = count($queryPlanetes);
			if ($nbPlan >= 11) {
				switch($nbPlan){
					case 11: $tps = 2; break;
					case 12: $tps = 4; break;
					case 13: $tps = 6; break;
					case 14: $tps = 8; break;
					case 15: $tps = 12; break;
					case 16: $tps = 16; break;
					case 17: $tps = 20; break;
					default: $tps = 24;
				}
			}
			else $tps = 0;
			$debut = mktime(rand(0, 24-$tps), 0, 0, date('n'), date('j'), date('Y'));
			$fin = $debut + $tps * 3600;

			$idFlo = $queryFlottes[$i]['id_user'];
			$bdd->connexion();
			if ($bdd->query("INSERT INTO $table_planete (id_user, isolement, nom_planete, galaxie, ss, position, image, cases, timestamp, metal, cristal, hydrogene, hash_planete) VALUES ('$idFlo', '$debut $fin', 'Planète colonisée', '$end_galaxie', '$end_ss', '$end_position', '$image', '$cases', '$time', '$Cmetal', '$Ccristal', '$Chydrogene', SHA1(CONCAT('g',planete.galaxie,'s',planete.ss,'p',planete.position)));") === false) {
				$rapport->addInfo(false, 1);
				$bdd->query("UPDATE $table_flottes SET effectue = 1 WHERE id = $id_flotte;");
				$bdd->deconnexion();
			}
			else {
				if ($queryFlottes[$i]['nb_vais'] == 1) {
					$queryFlottes[$i]['nb_vais'] = -1;
					$bdd->query("DELETE FROM $table_flottes WHERE id = $id_flotte");
				}
				else $bdd->query("UPDATE $table_flottes SET effectue = 1, vaisseau_3 = vaisseau_3 - 1, nb_vais = nb_vais - 1, contenu_metal = 0, contenu_cristal = 0, contenu_hydrogene = 0 WHERE id = $id_flotte;");
				$bdd->deconnexion();
			}
			$rapport->send();
		}
		//Mission Recycler
		elseif ($mission == 4) {
			$capacite = $queryFlottes[$i]['contenu_max'] - (vais_conso($queryFlottes[$i]['end_time'], count($queryFlottes[$i]['nb_vais']))*$queryFlottes[$i]['vitesse']*5) + $queryFlottes[$i]['contenu_metal'] + $queryFlottes[$i]['contenu_cristal'] + $queryFlottes[$i]['contenu_hydrogene'];

			$debris_met = $queryEN['debris_met'];
			$debris_cri = $queryEN['debris_cri'];

			if ($debris_met+$debris_cri > $capacite) {
				$a = floor($capacite/2);
				$b = floor($capacite/2);
				if ($a > $debris_met && $b > $debris_cri) {
					$a = $debris_met;
					$b = $debris_cri;
				}
				else if ($a > $debris_met) {
					$a = $debris_met;
					$b = ($capacite - $a);
					if ($b > $debris_cri) $b = $debris_cri;
				}
				else if ($b > $debris_cri) {
					$b = $debris_cri;
					$a = ($capacite - $b);
					if ($a > $debris_met) $a = $debris_met;
				}
			}
			else {
				$a = $debris_met;
				$b = $debris_cri;
			}
			$Cmetal = $a + $queryFlottes[$i]['contenu_metal'];
			$Ccristal = $b + $queryFlottes[$i]['contenu_cristal'];

			$bdd->connexion();
			$bdd->query("UPDATE $table_flottes SET effectue = '1', contenu_metal = '$Cmetal', contenu_cristal = '$Ccristal' WHERE id = '$id_flotte';");
			$bdd->query("UPDATE $table_planete SET debris_met = debris_met - '$a', debris_cri = debris_cri - '$b' WHERE galaxie = '$end_galaxie' AND ss = '$end_ss' AND position = '$end_position';");
			$bdd->deconnexion();

			$rapport = new Rapport($mission, $queryFlottes[$i]['id_user'], $queryEN['id_user'], $end_time);
			$rapport->addInfo($queryEN, 0);
			$rapport->addInfo(array($a, $b), 1);
			$rapport->send();
		}
		//Mission Espionnage
		elseif ($mission == 5) {
			$nbsondes = $queryFlottes[$i]['vaisseau_3'];
			$id_userT = $queryEN['id_user'];
			$id_att = $queryFlottes[$i]['id_user'];

			$bdd->connexion();
			$bdd->query("UPDATE $table_flottes SET effectue = 1 WHERE id = $id_flotte;");
			$resultatUD = $bdd->unique_query("SELECT * FROM $table_user WHERE id = $id_userT;");
			$resultatUA = $bdd->unique_query("SELECT * FROM $table_user WHERE id = $id_att;");
			$bdd->deconnexion();

			$diffNiveau = $resultatUA['detection'] - $resultatUD['detection'] + floor($nbsondes/2);
			$rapport = new Rapport($mission, $id_att, $id_userT, $end_time);

			if ($diffNiveau < 0) {
				$rapport->addInfo($queryEN, 0);
				$rapport->addInfo(false, 1);
			}
			if ($diffNiveau >= 0) $rapport->addInfo($queryEN, 0);
			if ($diffNiveau >= 1) $rapport->addInfo(true, 1);
			if ($diffNiveau >= 2) $rapport->addInfo(true, 2);
			if ($diffNiveau >= 3) $rapport->addInfo(true, 3);
			if ($diffNiveau >= 4) $rapport->addInfo($resultatUD, 4);
			if ($diffNiveau >= 5) $rapport->addInfo(true, 5);

			$rapport->send();
		}
	}

	//Si la flotte a terminé son retour
	if (($queryFlottes[$i]['mission'] == 0 && $queryFlottes[$i]['start_time'] + $queryFlottes[$i]['end_time'] <= time()) || ($queryFlottes[$i]['effectue'] == 1 && ((!empty($queryFlottes[$i]['ret_time']) && $queryFlottes[$i]['ret_time'] <= time()) || ($queryFlottes[$i]['start_time'] + $queryFlottes[$i]['end_time']*2 <= time())))) {
		if ($queryFlottes[$i]['mission'] == 0) {
			$fin_galaxie = $queryFlottes[$i]['end_galaxie'];
			$fin_systeme = $queryFlottes[$i]['end_ss'];
			$fin_potision = $queryFlottes[$i]['end_position'];
		}
		elseif (!empty($queryFlottes[$i]['ret_position'])) {
			$fin_galaxie = $queryFlottes[$i]['ret_galaxie'];
			$fin_systeme = $queryFlottes[$i]['ret_ss'];
			$fin_potision = $queryFlottes[$i]['ret_position'];
		}
		else {
			$fin_galaxie = $queryFlottes[$i]['start_galaxie'];
			$fin_systeme = $queryFlottes[$i]['start_ss'];
			$fin_potision = $queryFlottes[$i]['start_position'];
		}

		$bdd->connexion();
		if ($bdd->unique_query("SELECT * FROM $table_planete WHERE galaxie = '$fin_galaxie' AND ss = '$fin_systeme' AND position = '$fin_potision';")) {
			$export = '';
			$nbvais = 12;
			for($j = 1; $j <= $nbvais; $j++) {
				$export .= ', vaisseau_'.$j.' = vaisseau_'.$j.' + '.$queryFlottes[$i]['vaisseau_'.$j];
			}
			$Cmetal = $queryFlottes[$i]['contenu_metal'];
			$Ccristal = $queryFlottes[$i]['contenu_cristal'];
			$Chydrogene = $queryFlottes[$i]['contenu_hydrogene'];
			$bdd->query("UPDATE $table_planete SET metal = metal + '$Cmetal', cristal = cristal + '$Ccristal', hydrogene = hydrogene + '$Chydrogene'$export WHERE galaxie = '$fin_galaxie' AND ss = '$fin_systeme' AND position = '$fin_potision';");
		}
		$idUserFlotte = $queryFlottes[$i]['id_user'];
		$bdd->query("DELETE FROM $table_flottes WHERE id_user = '$idUserFlotte' AND id = '$id_flotte';");
		$bdd->query("DELETE FROM $table_flottes_combats WHERE refflotte = '$id_flotte';");
		$bdd->deconnexion();
	}
}
?>