<?php
session_start();

$idEtablissement = ( empty($_SESSION['idEtablissement']) ) ? $_GET['e'] : $_SESSION['idEtablissement'];

ini_set("include_path", '/home/africawebstudent/php:' . ini_get("include_path") );

require_once 'HTTP/Request2.php'; // Only when installed with PEAR

include_once('PayementLibrary/getaccesstoken.php');

include_once('PayementLibrary/requestepayement.php');

include('/home/africawebstudent/public_html/gs/progicielgeststudent/configuration_etabli.php');

include_once('Library/Basededonnees.php');

include_once('payment_function.php');

$DB_DATABASE = $_SESSION["DB_DATABASE"];

$database = new Basededonnees($DB_DATABASE);
$bdd = $database->getBdd();

include('Library/Identite.php');
include('footer.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"];

$dateValidation = "$y-$mo-$wd $h:$m:$s";

$aff = 'YES';
$sql0 = "SELECT * FROM academique where idEtablissement = :idEtablissement AND affiche = :aff";
$statement0 = $bdd->prepare($sql0);
$statement0->bindParam(':idEtablissement', 	$idEtablissement, PDO::PARAM_STR);
$statement0->bindParam(':aff', 	$aff, PDO::PARAM_STR);
$statement0->execute();
$row=$statement0->fetch(PDO::FETCH_ASSOC);
$acad 		= $row['annee_acad'];											

$uidmomo = ( empty($_SESSION['uuid']) ) ? $_GET['uid'] : $_SESSION['uuid'];

$resRef = $bdd->prepare('SELECT refInternationale, typeOperation FROM facture WHERE  uidmomo =?');
$resRef->execute(array($uidmomo));
$ref        = $resRef->fetch();
$transref 	= $ref['refInternationale']; //reférence internationnale de la transaction
$typeOperation = $ref['typeOperation'];

$clientRef = $bdd->prepare('SELECT clientid FROM etablissement WHERE idEtablissement =?');
$clientRef->execute(array($idEtablissement));
$client     = $clientRef->fetch();
//echo $transref;
$statut = '';
$accesstoken = access_token();
$btnprimary = '';
if($typeOperation == "MoMo") {
    $res        = getRequestpaymentstatus($accesstoken, $uidmomo);
    $res        = json_decode("$res");
    $status     = $res->status;
    //echo $status;
    if($status=="PENDING"){
        $idStatut = 1;
    	$statut = "En attente de validation";
    	$btnprimary = 'btn-warning';
    	$sqli  = 'UPDATE `facture` SET statutOperation = :st WHERE (refInternationale = :ref)';
    	$statementi = $bdd->prepare($sqli);
    	$statementi->bindParam(':st', 	$idStatut, 	PDO::PARAM_STR);
    	$statementi->bindParam(':ref', 	$transref, 	PDO::PARAM_STR);
    	$statementi->execute();
    }elseif($status=="SUCCESSFUL"){
        $idStatut = 0;
    	$statut = "Opération réussie";
    	$btnprimary = 'btn-success';
    	$sql2 = "SELECT *  FROM facture  WHERE refInternationale = :ref";
    	$statement2 = $bdd->prepare($sql2);
    	$statement2->bindParam(':ref', 	$transref, 	PDO::PARAM_STR);
    	$statement2->execute();
    	$row2=$statement2->fetch(PDO::FETCH_ASSOC);
    	$annee_acad     = $row2['annee_acad'];		
    	$matricule      = $row2['matricule'];		
    	$annee          = $row2['annee'];		
    	$niveau         = $row2['niveau'];		
    	$idFiliere      = $row2['idFiliere'];		
    	$montant        = $row2['montant'];		
    	$statutOperation= $row2['statutOperation'];		
    	$sql3 = "SELECT *  FROM tabinscription  WHERE annee_acad = :acad AND matricule = :ma AND annee = :a AND idFiliere = :id";
    	$statement3 = $bdd->prepare($sql3);
    	$statement3->bindParam(':acad', 	$annee_acad, 	PDO::PARAM_STR);
    	$statement3->bindParam(':ma', 	$matricule, 	PDO::PARAM_STR);
    	$statement3->bindParam(':a', 	$annee, 	PDO::PARAM_STR);
    	$statement3->bindParam(':id', 	$idFiliere, 	PDO::PARAM_STR);
    	$statement3->execute();
    	$row3=$statement3->fetch(PDO::FETCH_ASSOC);
    	$montantNew     = $row3['montant'] + $montant;	
        $depassement = 0;
        if($statutOperation != 0) {
            validationMontant($montant, $montantNew, $depassement, $annee_acad, $annee, $niveau, $idFiliere, $matricule, $idStatut, $bdd); 
        }
    	$sqli  = 'UPDATE `facture` SET statutOperation = :st WHERE (refInternationale = :ref)';
    	$statementi = $bdd->prepare($sqli);
    	$statementi->bindParam(':st', 	$idStatut, 	PDO::PARAM_STR);
    	$statementi->bindParam(':ref', 	$transref, 	PDO::PARAM_STR);
    	$statementi->execute();
    }elseif($status=="FAILED") {
    	$statut = "Echec de l'opération";
    	$btnprimary = 'btn-danger';
    	$idStatut = 2;
    	$sqli  = 'UPDATE `facture` SET statutOperation = :st WHERE (refInternationale = :ref)';
    	$statementi = $bdd->prepare($sqli);
    	$statementi->bindParam(':st', 	$idStatut, 	PDO::PARAM_STR);
    	$statementi->bindParam(':ref', 	$transref, 	PDO::PARAM_STR);
    	$statementi->execute();
    }else{
        $statut = $status;
        $btnprimary = 'btn-danger';
    }
}else if($typeOperation == "Moov Money") {
}else{
    $operateur = 'Visa';
}

///////////////////////////////////////////////////////////////////////////////////////////////
//Moov Money
//INSUFFICIENT_FUND_ERROR = 10 
//SUCCESS = 0;
/////////////////////////////////////////////////////////////////////////////////////////
?>


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>GestStudentPay</title>
        <!-- Favicon-->
        <link rel="icon" type="image/png" sizes="16x16" href="https://progiciel.africawebstudent.org/plugins/images/favicon.png">
        <!-- Bootstrap icons-->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css" rel="stylesheet" />
        <!-- Core theme CSS (includes Bootstrap)-->
        <link href="styles_.css" rel="stylesheet" />
    </head>
    <body>
        <!-- Responsive navbar-->
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container px-lg-5">
                <a class="navbar-brand" href="#!">GestStudentPay</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
            </div>
        </nav>
        <br /><br />
        <br /><br />
        <!-- Header-->
        <header class="py-5">
            <div class="container px-lg-5">
                <div class="p-4 p-lg-5 bg-light rounded-3 text-center">
                    <div class="m-4 m-lg-5">
                        <h1 class="display-5 fw-bold">Résultats de votre opération!!!</h1>
                        <p class="fs-6">GestStudentPay la première plateforme de paiement des frais de scolarité en ligne. Cette plateforme donne la 
                        possibilité aux etudiants ainsi qu'aux parents d'étudiants de procéder au règlement des frais de formation à partir de leur terminal!!!</p>
                        <a class="btn <?php echo $btnprimary; ?> btn-lg" href="#!"><?php echo $statut; ?></a>
                    </div>
                </div>
            </div>
        </header>
        <!-- Page Content-->
        <!--section class="pt-4">
            <br /><br />
            <br /><br />
            <br /><br />
            <br /><br />
        </section>
        <!-- Footer-->

        <!--footer class="py-5 bg-dark">
            <div class="container"><p class="m-0 text-center text-white">Copyright &copy; Your Website 2021</p></div>
        </footer-->
        <!-- Bootstrap core JS-->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js"></script>
        <!-- Core theme JS-->
        <script src="scripts_.js"></script>
    </body>
</html>
