<?php
	session_start();
	
    if(!isset($_SESSION["idEtablissement"]) OR empty($_SESSION["idEtablissement"]) OR !isset($_SESSION["etudiant_i"]) OR empty($_SESSION["etudiant_i"]))
    {
    	header('Location: ./');
    	exit();
    }
	//**********
    $idEtablissement = $_SESSION['idEtablissement'];

	include_once('payment_function.php');

    ini_set("include_path", '/home/africawebstudent/php:' . ini_get("include_path") );
    
    require_once 'HTTP/Request2.php'; // Only when installed with PEAR
    
    require_once '/home/africawebstudent/public_html/gs/progicielgeststudent/uuid/vendor/autoload.php';
    
    use Ramsey\Uuid\Uuid;
    
    include_once('PayementLibrary/getaccesstoken.php');
    
    include_once('PayementLibrary/requestepayement.php');
    
	include('/home/africawebstudent/public_html/gs/progicielgeststudent/notifierErreur2.php');
	
	include('/home/africawebstudent/public_html/gs/progicielgeststudent/Admin/config_g.php');
	
	include('/home/africawebstudent/public_html/gs/progicielgeststudent/configuration_etabli.php');

    include_once('Library/Basededonnees.php');
    
    $DB_DATABASE = $_SESSION["DB_DATABASE"];
    
    $database = new Basededonnees($DB_DATABASE);
    $bdd = $database->getBdd();
    
    include('Library/Identite.php');
	//**********
	date_default_timezone_set('Africa/Porto-Novo'); 
	$d = getdate();

	$y = $d["year"];
	$mo = $d["mon"];
	$wd = $d["mday"];

	$h = $d["hours"];
	$m = $d["minutes"];
	$s = $d["seconds"];
	
	//$dateTransaction = "$y-$mo-$wd $h:$m:$s";
    $dateValidation = "$y-$mo-$wd $h:$m:$s";
	$dateTransaction = $_POST['dateTransaction'];

	$minutef = $h*60 + $m;

	$day = Date('l');
	$jour = getJour($day);

    $operateur = '';
	$nom            = 'IITECH';
	$prenom         = 'BENIN';
	$indicatif      = $_POST['pays'];
	$tel            = $indicatif.$_POST['tel'];
	$devise         = $_POST['devise'];
	$typeOperation  = $_POST['type']; //type de payement (1 = MoMo, 2 = Moov Money, 3 = Visa)
	if($typeOperation == "1") {
	    $operateur = 'MoMo';
	}else if($typeOperation == "2") {
	    $operateur = 'Moov Money';
	}else{
	    $operateur = 'Visa';
	}

    $amount = $_POST['montant']; //ceil(($_POST['montant']*100)/97); Math.round((x*1.2)/100)
    
    $message = $_POST['nature'];
    
    $currency = $_POST['devise'];
    
    $externalId = time();
    
    $partyId = $indicatif.$_POST['tel'];
    
    $accesstoken = access_token();
    
    $uuid = Uuid::uuid4();
    $uuid = $uuid->toString();
    
	//print_r($typeOperation);
	$matricule      = $_POST['matricule'];
	$montant        = $_POST['montant'];
	$fraisOperation = round(($montant*1.2)/100);
	$idFiliere 	    = $_POST['idFiliere'];
	$annee    	    = $_POST['annee'];  
	$niveau    	    = $_POST['niveau'];  
	$annee_acad     = $_POST['academique']; 
	$idComptable    = $_POST['matricule'];
	$refFacture     = $externalId; //mt_rand();
	
	$statutOperation = '1'; // 1 = Pending; 0 = Successful; 2 = Error.
	
	$sql = "SELECT nom, prenom  FROM tabetudiant  WHERE (matricule = :matri)";
	$statement = $bdd->prepare($sql);
	$statement->bindParam(':matri',  	$matricule, 	PDO::PARAM_STR);
	$statement->execute();
	$row=$statement->fetch(PDO::FETCH_ASSOC);
	$nom     = $row['nom'];		
	$prenom  = $row['prenom'];

	$sql2 = "SELECT sigleFilieres  FROM filieres  WHERE (idFiliere = :id)";
	$statement2 = $bdd->prepare($sql2);
	$statement2->bindParam(':id',  	$idFiliere, 	PDO::PARAM_STR);
	$statement2->execute();
	$row2=$statement2->fetch(PDO::FETCH_ASSOC);
	$sigleFiliere     = $row2['sigleFilieres'];	
	$niv = '';
    if($niveau == 1){
        $niv = 'L'.$annee.'/'.$sigleFiliere;
    }else if($niveau == 2){
        $niv = 'M'.$annee.'/'.$sigleFiliere;
    }else if($niveau == 3){
        $niv = 'D'.$annee.'/'.$sigleFiliere;
    }
	if(empty($_POST['nameetu']) ) {
	    $message .=' pour le compte de '.$nom.' '.$prenom.' - '.$niv;
	}else{
	    $message .=' pour le compte de '.$_POST['nameetu'].' - '.$niv;
	}
?>

<?php
    $filepath  = 'facturebank/';
    $filepath .= $idEtablissement;
    $filepath .= '/';
	$file = $filepath . $refFacture . '.jpg';
	$sql2 = "SELECT *  FROM tabinscription  WHERE (matricule = :matri AND annee_acad = :acad AND annee = :an AND idFiliere = :id AND niveauFormation = :niv)";
	$statement2 = $bdd->prepare($sql2);
	$statement2->bindParam(':matri',  	$matricule, 	PDO::PARAM_STR);
	$statement2->bindParam(':acad',  	$annee_acad, 	PDO::PARAM_STR);
	$statement2->bindParam(':an',  		$annee, 		PDO::PARAM_STR);
	$statement2->bindParam(':id',  		$idFiliere, 	PDO::PARAM_STR);
	$statement2->bindParam(':niv',  	$niveau, 		PDO::PARAM_STR);
	$statement2->execute();
	$statement2->fetch(PDO::FETCH_ASSOC);
	$nb = $statement2->rowCount();
	$statutetud = 0;
	if($nb == 1) {
        $affiche = '';
        $montantDu = 0; //pour chaque annee
        $montTotaleDu = 0; //pour l'ensemble des années
        /** Pour chaque étudiant, on fait la recherche de ces dettes antérieures */
        $sqlm 	 = "SELECT * FROM tabinscription WHERE annee_acad < :acad AND matricule =:matr";
        $resm     = $bdd -> prepare($sqlm);
        $resm     ->execute(array('acad'=>$annee_acad, 'matr'=>$matricule)) or die(print_r($resm->errorInfo()));
        while($donneem=$resm->fetch()) {
        	//Déterminer le montant
        	$resMontantm = $bdd->prepare('SELECT * FROM montant WHERE idEtablissement=? AND idFiliere =? AND annee =? AND periode =? AND idStatut =?');
        	$resMontantm->execute(array($idEtablissement,$donneem['idFiliere'],$donneem['annee'],$donneem['annee_acad'],$donneem['statut']));
        	$Montantm= $resMontantm->fetch();
        	$fraism          	= $Montantm['scolarite'] + $Montantm['fraisInscription'];
        	$p = ($donneem['annee_acad']-1).'-'.$donneem['annee_acad'];
        	$montantDu = $fraism - $donneem['montant'];
        	$affiche .= '['.$p.' : '.$montantDu.' FCFA]   ';
        	$montTotaleDu = $montTotaleDu + $montantDu;
        }
        $statutetud =  0;
		try{
			$sql2 = "SELECT statut  FROM tabinscription  WHERE (matricule = :matri AND annee_acad = :acad)";
			$statement2 = $bdd->prepare($sql2);
			$statement2->bindParam(':matri',  	$matricule, 	PDO::PARAM_STR);
			$statement2->bindParam(':acad',  	$annee_acad, 	PDO::PARAM_STR);
			$statement2->execute();
			$row2=$statement2->fetch(PDO::FETCH_ASSOC);
			$statutetud     = $row2['statut'];		
		}catch(PDOException  $e ){
			$impossible ='
			<div style="width:400px;background:#fff;padding:20px;border-radius:5px;font-family:Calibri;box-shadow:0px 0px 5px #ccc inset;margin:auto;">
				<div style="color:#555;">
					'.$e->getMessage( ).'
				</div>
			</div>
			';
			echo $impossible;
		}

		//Déterminer le montant
		$resMontant = $bdd->prepare('SELECT * FROM montant WHERE idEtablissement=? AND idFiliere =? AND annee =? AND periode =? AND idStatut =?');
		$resMontant->execute(array($idEtablissement,$idFiliere,$annee,$annee_acad,$statutetud));
		$Montant    = $resMontant->fetch();
		$frais 	    = $Montant['scolarite'] + $Montant['fraisInscription']; //scolarite de l'année en cours

		$newFrais = 0; // Frais de la scolarité en tenant compte des arrièrés des années antérieures
        $newFrais = $frais + $montTotaleDu;
        
		$sql1  = 'SELECT  montant FROM `tabinscription` WHERE annee_acad = :acad AND  annee = :an AND niveauFormation = :niv AND idFiliere = :id AND matricule = :matri';
		$statement1 = $bdd->prepare($sql1);
		$statement1->bindParam(':acad',  			$annee_acad, PDO::PARAM_STR);
		$statement1->bindParam(':an', 				$annee, PDO::PARAM_STR);
		$statement1->bindParam(':niv', 				$niveau, PDO::PARAM_STR);
		$statement1->bindParam(':id', 				$idFiliere, PDO::PARAM_STR);
		$statement1->bindParam(':matri', 			$matricule, PDO::PARAM_STR);
		$statement1->execute();
		$row=$statement1->fetch(PDO::FETCH_ASSOC);
		$montantNew = $montant + $row['montant']; // $montant : montant envoyé par $_POST; $row['montant'] : montant enregistré dans la base
		$hauteur     = 	$montantNew - 	$frais;	
		$newHauteur = 	$montantNew - 	$newFrais;	

        $soldedu = $newFrais - $montantNew;

	    $transref   =   insertionMontant($matricule, $annee, $niveau, $annee_acad, $idFiliere, $refFacture, $file, $montant, $fraisOperation, $dateTransaction, $idComptable, $montantNew, $soldedu, 0, $frais, $affiche, $operateur, $statutOperation, $tel, $uuid, $bdd);
    	////////////////////////////////////////////////////////////////////////////////
    	if($typeOperation == "1") {
    	    $operateur  = 'MoMo';
            $response   = callRequestpayment($amount, $currency, $externalId, $partyId, $accesstoken, $uuid, $message);
            $res        = getRequestpaymentstatus($accesstoken, $uuid);
            $res        = json_decode("$res");
            $_SESSION['financialTransactionId'] =   $res->financialTransactionId;
        	$_SESSION['accesstoken']            =   $accesstoken;
        	$_SESSION['uuid']                   =   $uuid;
        	$_SESSION['externalId']             =   $externalId;
    	}else if($typeOperation == "2") {
    	    $operateur = 'Moov Money';
    	}else{
    	    $operateur = 'Visa';
    	}
    	
		/*if($montantNew <= $newFrais) {
		    $transref   =   insertionMontant($matricule, $annee, $niveau, $annee_acad, $idFiliere, $refFacture, $file, $montant, $dateTransaction, $idComptable, $montantNew, $soldedu, 0, $frais, $affiche, $operateur, $statutOperation, $tel, $bdd);
        	////////////////////////////////////////////////////////////////////////////////
        	if($typeOperation == "1") {
        	    $operateur = 'MoMo';
                $response = callRequestpayment($amount, $currency, $externalId, $partyId, $accesstoken, $uuid);
        	}else if($typeOperation == "2") {
        	    $operateur = 'Moov Money';
        	}else{
        	    $operateur = 'Visa';
        	}
		}else{
		    $depassement = -$newHauteur;
		    $transref   =   insertionMontant($matricule, $annee, $niveau, $annee_acad, $idFiliere, $refFacture, $file, $montant, $dateTransaction, $idComptable, $montantNew, $soldedu, $depassement, $frais, $affiche, $operateur, $statutOperation, $tel, $bdd);
        	////////////////////////////////////////////////////////////////////////////////
        	if($typeOperation == "1") {
        	    $operateur = 'MoMo';
                $response = callRequestpayment($amount, $currency, $externalId, $partyId, $accesstoken, $uuid);
        	}else if($typeOperation == "2") {
        	    $operateur = 'Moov Money';
        	}else{
        	    $operateur = 'Visa';
        	}
		}*/
    	/*$response = json_decode($make_call, true);
    	/////////////////////////////////////////////////////////////////
    	$_SESSION['uuid']       =   $uuid;
    	$_SESSION['externalId']   =   $externalId;*/
	}else{
		echo '<div style="width:400px;background:#fff;padding:20px;border-radius:5px;font-family:Calibri;box-shadow:0px 0px 5px #ccc inset;margin:auto;">
			<div style="color:#555;">
				Erreur de traitement. Veuillez v&eacute;rifier les donn&eacute;es (fili&egrave;re, ann&eacutee d\'&eacutetude, niveau,...) et reprendre l\'op&eacute;ration..<br/>
			</div>
		</div>';
	}	
?>