/////////////////////////////////////////////////
// LOGGING
/////////////////////////////////////////////////
const logger = require("../../public/js/app/logger_concert");

/////////////////////////////////////////////////
// APPELS DES MODULES
/////////////////////////////////////////////////
const path = require("path");
const fs = require("fs");
// CALCUL DE DATE
const moment = require('moment');
// ENVOIE MAIL GOOGLE MAIL
const nodemailer = require('nodemailer');
// CONNECTION BASE DE DONNÉES
const mysql = require('mysql2');
const mysql_promise = require('mysql2/promise');
// STRIPE
const stripe = require('stripe')(process.env.STRIPE_PRIVATE_KEY);
// FETCH (utile pour nodejs version < 18)
const fetch = require("node-fetch");

/////////////////////////////////////////////////
// GOOGLE SHEET PARAMETERS
/////////////////////////////////////////////////
const { GoogleSpreadsheet } = require('google-spreadsheet');
const GS_creds = require('../../inscriptionsafps-53b60452f63d.json');
const { error } = require("console");
// Fichier Google Sheet "afps_concert_annuel" (Mon Drive/inscriptions/base_donees)
// doc ID is the long id in the sheets URL
const GS_concert = new GoogleSpreadsheet(process.env.gsheet_concertannuel);

/////////////////////////////////////////////////
// APPELS DES FONCTIONS
/////////////////////////////////////////////////
const sleep = require("./../../modules/sleep");
const envoie_mail = require("./../../modules/envoie_mail");

////////////////////////////////////////////////////
// FILE NAME
////////////////////////////////////////////////////
const filename = path.parse(__filename).base;

////////////////////////////////////////////////////
// CONNECTION DB
////////////////////////////////////////////////////
async function connect_DB_promise() {
    return db_connection_promise = await mysql_promise.createConnection({
        host: process.env.db_connection_host,
        port: process.env.db_connection_port,
        user: process.env.db_connection_user,
        password: process.env.db_connection_password,
        database: process.env.db_connection_database
    });
}

/////////////////////////////////////////////////
// 4 - PAGE RECAP
// CLIC sur PAYER
// enregistrement dans la BD des participants
// Envoie vers Stripe
/////////////////////////////////////////////////

const payer = async function (req, res) {
    logger.info("======================================", { label: filename });
    logger.info("======== FUNCTION payer (enregistrement BD + envoie vers Stripe) ==========", { label: filename });
    logger.info("======================================", { label: filename });

    logger.info("req.session.adherent_mail = " + req.session.adherent_mail , { numsession: req.session.id, label: filename});
    logger.info("req.session.deja_inscrit_concert = " + req.session.deja_inscrit_concert , { numsession: req.session.id, label: filename});

    let sql;
    let table;
    let champs;
    let values;
    let saison = "2025/2026";
    moment.locale('fr');
    let now = moment().format("YYYY-MM-DD HH:mm:ss");
    var today = moment().format('L');
    let commande_nbr_places_concertiste = 0;
    let commande_nbr_places_encadrant_parent = 0;
    let commande_nbr_places_encadrant_prof = 0;
    let piano_commandes = 0;
    let alto_commandes = 0;
    let flute_commandes = 0;
    let trompette_commandes = 0;
    let harpe_commandes = 0;
    let violon1_commandes = 0;
    let violon2_commandes = 0;
    let violoncelle1_commandes = 0;
    let violoncelle2_commandes = 0;
    var mail_objet;
    var mail_html;


    function affiche_page_identifier() {
        ////////////////////////////////////////////////////
        // AFFIHER LA PAGE /identifier
        // AFFICHAGE DES ERREURS
        // EN CAS DE RETOUR SUR LA PAGE AVEC ERREUR :
        //  - SI IDENTIFIANT NON ADHÉRENT
        //  - SI RIEN SAISIE
        ////////////////////////////////////////////////////

        if (req.session.err_mail_form_adhesion_1) {
            res.locals.err_mail_form_adhesion_1 = req.session.err_mail_form_adhesion_1;
            res.locals.err_mail_form_adhesion_2 = req.session.err_mail_form_adhesion_2;
            res.locals.err_mail_form_adhesion_3 = req.session.err_mail_form_adhesion_3;
            // on supprime le contenu après affichage
            req.session.err_mail_form_adhesion_1 = undefined;
            req.session.err_mail_form_adhesion_2 = undefined;
            req.session.err_mail_form_adhesion_3 = undefined;
        }
        res.render('concert/page_templates/erreur');
    };

    /////////////////////////////////////////////////
    // SI IDENTIFIANT PERDU
    /////////////////////////////////////////////////
    logger.info("req.session.identifiant : " + req.session.identifiant , { numsession: req.session.id, label: filename});
    if (req.session.identifiant === undefined) {
        logger.info("IDENTIFIANT PERDU", { numsession: req.session.id });
        req.session.err_mail_form_adhesion_1 = "Session expirée, veuillez recommencer";
        affiche_page_identifier();
    } else {

        /////////////////////////////////////////////////
        // AJOUT DANS LA BASE DE DONNÉES
        /////////////////////////////////////////////////

        if (req.session.deja_inscrit_concert == "non") {
            logger.info("NOUVELLE INSCRIPTION AU CONCERT", { numsession: req.session.id, label: filename});
        } else if (req.session.deja_inscrit_concert == "oui") {
            logger.info("AJOUT DE BILLETS POUR UN ADHÉRENT DÉJÀ INSCRIT AU CONCERT", { numsession: req.session.id, label: filename});
        }
        

        // CONNECTION DB PROMISE
        try {
            //Connexion
            let db_connection_promise = await connect_DB_promise();
            
            //Queries

            /////////////////////////////////////////////////
            // AJOUT CONCERTISTES
            for (let toto = 1; toto < 5; toto++) {
                if (req.session["eleve_"+toto+"_nom"]) {

                    table = "ca_concertiste";
                    if (req.session.deja_inscrit_concert == "non") {
                        champs = "date_maj,saison,identifiant,concertiste_nom,concertiste_prenom,concertiste_age,concertiste_intrument,concertiste_cahier,concertiste_piece,concertiste_prof_nom,concertiste_prof_mail";
                        values = '"'+ now + '","' + saison + '"' + ',"' + req.session.identifiant + '","' + req.session["eleve_"+toto+"_nom"] + '","' + req.session["eleve_"+toto+"_prenom"] + '",' + req.session["eleve_"+toto+"_age"] + ',"' + req.session["eleve_"+toto+"_instrument"] + '","' + req.session["eleve_"+toto+"_cahier"] + '","' + req.session["eleve_"+toto+"_piece"] + '","' + req.session["eleve_"+toto+"_prof_nom"] + '","' + req.session["eleve_"+toto+"_prof_mail"] + '"';
                    } else if (req.session.deja_inscrit_concert == "oui")  {
                        champs = "date_maj,saison,identifiant,concertiste_nom,concertiste_prenom,concertiste_age,concertiste_intrument,concertiste_cahier,concertiste_piece,concertiste_prof_nom,concertiste_prof_mail,ajout";
                        values = '"'+ now + '","' + saison + '"' + ',"' + req.session.identifiant + '","' + req.session["eleve_"+toto+"_nom"] + '","' + req.session["eleve_"+toto+"_prenom"] + '",' + req.session["eleve_"+toto+"_age"] + ',"' + req.session["eleve_"+toto+"_instrument"] + '","' + req.session["eleve_"+toto+"_cahier"] + '","' + req.session["eleve_"+toto+"_piece"] + '","' + req.session["eleve_"+toto+"_prof_nom"] + '","' + req.session["eleve_"+toto+"_prof_mail"] + '","' + now + '"';
                    }

                    sql = 'INSERT INTO ' + table + ' (' + champs + ') VALUES (' + values + ')';
                    logger.info("REQUETE SQL ca_concertiste : " + sql , { numsession: req.session.id, label: filename});

                    const [results, fields] = await db_connection_promise.execute(sql);
                    logger.info("CONCERTISTES Row ID added : " + results.insertId, { numsession: req.session.id, label: filename});

                    // COMPTEUR DE PLACES
                    commande_nbr_places_concertiste += 1;
                    if (req.session["eleve_"+toto+"_instrument"] == "Piano") {
                        piano_commandes += 1;
                    }
                    if (req.session["eleve_"+toto+"_instrument"] == "Alto") {
                        alto_commandes += 1;
                    }
                    if (req.session["eleve_"+toto+"_instrument"] == "Flute") {
                        flute_commandes += 1;
                    }
                    if (req.session["eleve_"+toto+"_instrument"] == "Trompette") {
                        trompette_commandes += 1;
                    }
                    if (req.session["eleve_"+toto+"_instrument"] == "Harpe") {
                        harpe_commandes += 1;
                    }
                    if (req.session["eleve_"+toto+"_instrument"] == "Violon") {
                        switch (req.session["eleve_"+toto+"_cahier"]) {
                            case 'Cahier 1':
                                violon1_commandes += 1;
                                break;
                            case 'Cahier 2':
                                violon1_commandes += 1;
                                break;
                            case 'Cahier 3':
                                violon1_commandes += 1;
                                break;
                            case 'Cahier 4':
                                violon1_commandes += 1;
                                break;
                            case 'Cahier 5':
                                violon1_commandes += 1;
                                break;
                            case 'Cahier 6':
                                violon2_commandes += 1;
                                break;
                            case 'Cahier 7':
                                violon2_commandes += 1;
                                break;
                            case 'Cahier 8':
                                violon2_commandes += 1;
                                break;
                            case 'Cahier 9':
                                violon2_commandes += 1;
                                break;
                            case 'Cahier 10':
                                violon2_commandes += 1;
                                break;
                            default:
                                logger.info("Erreur détecté dans le switch req.session[eleve_+toto+_instrument] == Violon", { numsession: req.session.id, label: filename});
                        }
                    }
                    if (req.session["eleve_"+toto+"_instrument"] == "Violoncelle") {
                        switch (req.session["eleve_"+toto+"_cahier"]) {
                            case 'Cahier 1':
                                violoncelle1_commandes += 1;
                                break;
                            case 'Cahier 2':
                                violoncelle1_commandes += 1;
                                break;
                            case 'Cahier 3':
                                violoncelle1_commandes += 1;
                                break;
                            case 'Cahier 4':
                                violoncelle1_commandes += 1;
                                break;
                            case 'Cahier 5':
                                violoncelle2_commandes += 1;
                                break;
                            case 'Cahier 6':
                                violoncelle2_commandes += 1;
                                break;
                            case 'Cahier 7':
                                violoncelle2_commandes += 1;
                                break;
                            case 'Cahier 8':
                                violoncelle2_commandes += 1;
                                break;
                            case 'Cahier 9':
                                violoncelle2_commandes += 1;
                                break;
                            case 'Cahier 10':
                                violoncelle2_commandes += 1;
                                break;
                            default:
                            logger.info("Erreur détecté dans le switch req.session[eleve_+toto+_instrument] == Violoncelle", { numsession: req.session.id, label: filename});
                        }
                    }
                }
            }

            /////////////////////////////////////////////////
            // AJOUT ENCADRANTS
            let compteur_encadrants = 0;
            for (let toto = 1; toto < 5; toto++) {
                if (req.session["encadrant_"+toto+"_nom"]) {

                    
                    // SI PARENT, ne rien mettre dans instrument (évite qu'il y ait "undefined")
                    if (!req.session["encadrant_"+toto+"_prof_instrument"]) {req.session["encadrant_"+toto+"_prof_instrument"] = ''};

                    table = "ca_encadrant";
                    

                    if (req.session.deja_inscrit_concert == "non") {
                        champs = "date_maj,saison,identifiant,encadrant_type,encadrant_nom,encadrant_prenom,encadrant_telephone_mobile,encadrant_mail,encadrant__prof_instrument";
                        values = '"'+ now + '","' + saison + '"' + ',"' + req.session.identifiant + '","' + req.session["encadrant_"+toto+"_type"] + '","' + req.session["encadrant_"+toto+"_nom"] + '","' + req.session["encadrant_"+toto+"_prenom"] + '","' + req.session["encadrant_"+toto+"_telephone_mobile"] + '","' + req.session["encadrant_"+toto+"_mail"] + '","' + req.session["encadrant_"+toto+"_prof_instrument"] + '"';
                    } else if (req.session.deja_inscrit_concert == "oui")  {
                        champs = "date_maj,saison,identifiant,encadrant_type,encadrant_nom,encadrant_prenom,encadrant_telephone_mobile,encadrant_mail,encadrant__prof_instrument, ajout";
                        values = '"'+ now + '","' + saison + '"' + ',"' + req.session.identifiant + '","' + req.session["encadrant_"+toto+"_type"] + '","' + req.session["encadrant_"+toto+"_nom"] + '","' + req.session["encadrant_"+toto+"_prenom"] + '","' + req.session["encadrant_"+toto+"_telephone_mobile"] + '","' + req.session["encadrant_"+toto+"_mail"] + '","' + req.session["encadrant_"+toto+"_prof_instrument"] + '","' + now + '"';
                    }

                    
                    sql = 'INSERT INTO ' + table + ' (' + champs + ') VALUES (' + values + ')';
                    logger.info("REQUETE SQL ca_encadrant : " + sql , { numsession: req.session.id, label: filename});
                    const [results, fields] = await db_connection_promise.execute(sql);

                    // COMPTEUR DE PLACES
                    if (req.session["encadrant_"+toto+"_type"]=="Professeur") {
                        commande_nbr_places_encadrant_prof += 1;
                    };
                    if (req.session["encadrant_"+toto+"_type"]=="Parent") {
                        commande_nbr_places_encadrant_parent += 1;
                    };
                    compteur_encadrants++;
                }

            }

            /////////////////////////////////////////////////
            // AJOUT DB INFORMATIONS ADHÉRENTS

            // SI C'EST SA PREMIÈRE INSCRIPTION
            if (req.session.deja_inscrit_concert == "non") {

                table = "ca_adherent";
                  
                sql = 'INSERT INTO ';
                sql += table;
                sql += ' (';
                sql += 'date_inscription, ';
                sql += 'date_maj, ';
                sql += 'saison, ';
                sql += 'identifiant, ';
                sql += 'association_suzuki, ';
                sql += 'adherent_nom, ';
                sql += 'adherent_prenom, ';
                sql += 'adherent_telephone_mobile, ';
                sql += 'adherent_mail, ';
                sql += 'hebergement_ville, ';
                sql += 'hebergement_places, ';
                sql += 'commande_nb_spectateur, ';
                sql += 'comment, ';
                sql += 'commande_nb_concertiste, ';
                sql += 'commande_nb_encadr_prof, ';
                sql += 'commande_nb_encadr_par, ';
                sql += 'commande_cout_concertiste, ';
                sql += 'commande_cout_spectateur, ';
                sql += 'don, ';
                sql += 'stripe_statut_paiement, ';
                sql += 'montant_total';
                sql += ') VALUES (';
                sql += '"'+ now +'",';
                sql += '"'+ now +'",';
                sql += '"'+ saison +'",';
                sql += '"'+ req.session.identifiant +'",';
                sql += '"'+ req.session.association_suzuki +'",';
                sql += '"'+ req.session.adherent_nom +'",';
                sql += '"'+ req.session.adherent_prenom +'",';
                sql += '"'+ req.session.adherent_telephone_mobile +'",';
                sql += '"'+ req.session.adherent_mail +'",';
                sql += '"'+ req.session.hebergement_ville +'",';
                sql += ''+ req.session.hebergement_nb +',';
                sql += ''+ req.session.spectateur_nb_place +',';
                sql += '"'+ req.session.commentaire_adherent +'",';
                sql += ''+ commande_nbr_places_concertiste +',';
                sql += ''+ commande_nbr_places_encadrant_prof +',';
                sql += ''+ commande_nbr_places_encadrant_parent +',';
                sql += ''+ req.session.cout_concertiste +',';
                sql += ''+ req.session.cout_spectateur +',';
                sql += ''+ parseInt(req.session.don) +',';
                if (req.session.montant_total > 0) {
                    sql += '"attente",';
                } else {
                    sql += '"gratuit",';
                }
                
                sql += ''+ req.session.montant_total;
                sql += ')';

                logger.info("REQUETE SQL ca_adherent : " + sql , { numsession: req.session.id, label: filename});
                const [results_insert_ca_adherent, fields_insert_ca_adherent] = await db_connection_promise.execute(sql);
                logger.info("ADHÉRENTS Row ID added : " + results_insert_ca_adherent.insertId, { numsession: req.session.id, label: filename});

            } else if (req.session.deja_inscrit_concert == "oui") {

                // SI C'EST UN AJOUT DE BILLET

                table = "ca_ajout";
                  
                sql = 'INSERT INTO ';
                sql += table;
                sql += ' (';
                sql += 'date_maj, ';
                sql += 'saison, ';
                sql += 'identifiant, ';
                sql += 'commande_nb_spectateur, ';
                sql += 'commande_nb_concertiste, ';
                sql += 'commande_nb_encadr_prof, ';
                sql += 'commande_nb_encadr_par, ';
                sql += 'commande_cout_concertiste, ';
                sql += 'commande_cout_spectateur, ';
                sql += 'don, ';
                sql += 'stripe_statut_paiement, ';
                sql += 'montant_total';
                sql += ') VALUES (';
                sql += '"'+ now +'",';
                sql += '"'+ saison +'",';
                sql += '"'+ req.session.identifiant +'",';
                sql += ''+ req.session.spectateur_nb_place +',';
                sql += ''+ commande_nbr_places_concertiste +',';
                sql += ''+ commande_nbr_places_encadrant_prof +',';
                sql += ''+ commande_nbr_places_encadrant_parent +',';
                sql += ''+ req.session.cout_concertiste +',';
                sql += ''+ req.session.cout_spectateur +',';
                sql += ''+ parseInt(req.session.don) +',';
                if (req.session.montant_total > 0) {
                    sql += '"attente",';
                } else {
                    sql += '"gratuit",';
                }
                
                sql += ''+ req.session.montant_total;
                sql += ')';

                logger.info("REQUETE SQL ca_ajout : " + sql , { numsession: req.session.id, label: filename});
                const [results_insert_ca_adherent, fields_insert_ca_adherent] = await db_connection_promise.execute(sql);
                logger.info("ca_ajout Row ID added : " + results_insert_ca_adherent.insertId, { numsession: req.session.id, label: filename});


            }

            /////////////////////////////////////////////////
            // ENVOIE VERS STRIPE
            // SI MONTANT TOTAL > 0
            /////////////////////////////////////////////////
            if (req.session.montant_total > 0) {
                logger.info("======================================", { label: filename });
                logger.info("======== ENVOIE VERS STRIPE ==========", { label: filename });
                logger.info("======================================", { label: filename });

                /////////////////////////////////////////////////
                // STRIPE - ETAPE 1 - CREER l'INTENTION DE PAIEMENT
                logger.info("req.session.adherent_mail = " + req.session.adherent_mail , { numsession: req.session.id, label: filename});
                const session_stripe = await stripe.checkout.sessions.create({
                    metadata: {identifiant: req.session.identifiant, ajoutbillet:req.session.deja_inscrit_concert},
                    customer_email: req.session.adherent_mail,
                
                    submit_type: 'pay',
                
                    success_url: process.env.STRIPE_CONCERT_SUCCESSURL,
                    cancel_url: process.env.STRIPE_CONCERT_CANCELURL,
                
                    payment_method_types: ['card'],
                    line_items: [{
                        price_data: {
                        currency: 'eur',
                        product_data: {
                            name: 'Billets Concert UNESCO',
                        },
                        unit_amount: req.session.montant_commande * 100,
                        },
                        quantity: 1,
                    },
                    {
                        price_data: {
                        currency: 'eur',
                        product_data: {
                            name: 'Don',
                        },
                        unit_amount: parseInt(req.session.don) * 100,
                        },
                        quantity: 1,
                    }],
                    //Checkout has three modes: payment, subscription, or setup. 
                    mode: 'payment'
                
                });
                logger.info("session_stripe.id : " + session_stripe.id , { numsession: req.session.id, label: filename});


                /////////////////////////////////////////////////
                // REDIRECTION VERS LA PAGE DE PAIEMENT STRIPE
                logger.info("Stripe session_stripe.url : " + session_stripe.url, { numsession: req.session.id, label: filename});
                res.redirect(session_stripe.url);
            } else {


                // AJOUT DÉCOMPTE DES PLACES
                // !!! Au démarrage de la campagne les champs de la table doivent être à 0 (zéro) et non vide ou null

                table = "ca_decompte_place";
            
                sql = 'UPDATE ';
                sql += table;
                sql += ' SET ';
                sql += 'date_maj = "' + now + '", ';
                sql += 'encadr_prof_commandes = encadr_prof_commandes + ' + commande_nbr_places_encadrant_prof + ', ';
                sql += 'encadr_parent_commandes = encadr_parent_commandes + ' + commande_nbr_places_encadrant_parent;

                logger.info("REQUETE SQL UPDATE ca_decompte_place : " + sql , { numsession: req.session.id, label: filename});
                const [results, fields] = await db_connection_promise.execute(sql);

                logger.info("REQUETE SQL UPDATE ca_decompte_place TERMINÉE ", { numsession: req.session.id, label: filename});

                /////////////////////////////////////////////////
                // SI PAS DE PAIEMENT À FAIRE CAR MONTANT < 0
                // ON CONTINUE ET ON ENVOIE LES BILLETS
                logger.info("Montant à payer inférieur à zéro, on ne passe pas par stripe", { numsession: req.session.id, label: filename});



                //////////////////////////
                // ENVOI MAIL À L'ADHÉRENT
                
                mail_objet = 'AFPS - CONCERT UNESCO 2024 - INSCRIPTION - ' + req.session.identifiant;

                
                mail_html = "<p style='font-size: 11pt; font-family: Arial; color: #454343; text-decoration: none;'>Cher(e) adhérent(e),<br></p><p style='font-size: 11pt; font-family: Arial; color: #454343; text-decoration: none;'>Félicitations ! Vous êtes inscrit au Concert national Unesco 2024 organisé par l'Association Française pour la Pédagogie Suzuki.";
                mail_html += "<br>Vous allez recevoir vos billets par mail de la part de la plateforme de Billetterie WEEZEVENT.</p>";
                

                mail_html += "<br>";
                mail_html += '<p style="color:#E73058;font-size: 13pt; font-family: Arial; text-decoration: none;"><strong>RÉCAPITULATIF</strong></p>';
                mail_html += "<p style='font-size: 11pt; font-family: Arial; color: #454343; text-decoration: none;'><strong>Identifiant Suzuki : </strong>" + req.session.identifiant;
                if (req.session.hebergement_nb > 0) {mail_html += "</p><br><p style='font-size: 11pt; font-family: Arial; color: #454343; text-decoration: none;'><strong>HÉBERGEMENT PROPOSÉ : </strong><br> Ville : " + req.session.hebergement_ville + ", nombre de personnes : " + req.session.hebergement_nb > 0 + "</p><br>";}

                mail_html += "<br><p style='font-size: 11pt; font-family: Arial; color: #454343; text-decoration: none;'><strong><span style='color: #E73058'>" + compteur_encadrants + "</span> ENCADRANT(S) :</strong></p>";
                mail_html += "<p style='font-size: 9pt; font-family: Arial; font-style: italic; color: #454343; text-decoration: none;'>Les encadrants s'engagent à être présents les 2 journées du 20 et 21 avril 2024.</p>";
                for (let toto = 1; toto < 5; toto++) {
                    if (req.session["encadrant_"+toto+"_nom"]) {
                        mail_html += "<p style='font-size: 11pt; font-family: Arial; color: #454343; text-decoration: none;'>Nom : " + req.session["encadrant_"+toto+"_nom"] + " " + req.session["encadrant_"+toto+"_prenom"] + " - " + req.session["encadrant_"+toto+"_type"] + "<br>";
                        mail_html += "coordonnées : " +  req.session["encadrant_"+toto+"_telephone_mobile"] + " - " + req.session["encadrant_"+toto+"_mail"] + "<br>";
                        if (req.session["encadrant_"+toto+"_prof_instrument"]) {mail_html += "instrument : " + req.session["encadrant_"+toto+"_prof_instrument"]};
                        mail_html += "</p>";
                    }

                }
                
            
                
                mail_html += '<br><br><p style="font-size: 11pt; font-family: Arial; color: #454343; text-decoration: none;">Association Française pour la pédagogie Suzuki<br>Marie Rossot - Pôle organisation du Concert national Unesco 2024</p><p><img src="cid:logo" alt="Logo" width="200" height="73"/></p>';

                // ajout du logo
                let dossier_image = path.resolve(__dirname, "../../public/images/logos/")+"/logosuzukigris.png";

                // VARIABLE POUR LE MAIL
                var mailOptions = {
                    from: 'afps.inscription@gmail.com',
                    to: req.session.adherent_mail,
                    subject: mail_objet,
                    html: mail_html,
                    attachments: [{
                        filename: 'logosuzukigris.png',
                        path: dossier_image,
                        cid: 'logo'
                    }]
                };
                envoie_mail.envoie_mail(mailOptions);

                /////////////////////////////////////
                // ENVOI BILLETS VERS WEEZEVENT
                /////////////////////////////////////

                let weez_id_evenement_concertiste = process.env.weezevent_id_event_concertiste;
                let weez_id_evenement_encadrant = process.env.weezevent_id_event_encacrant;
                let weez_id_evenement_spectateur = process.env.weezevent_id_event_spect;

                let weez_id_billet_concertiste = process.env.weez_id_billet_concertiste;
                let weez_id_billet_spectateur = process.env.weez_id_billet_spectateur;
                let weez_id_billet_encadrant_parent = process.env.weez_id_billet_encadrant_parent;
                let weez_id_billet_encadrant_prof = process.env.weez_id_billet_encadrant_prof;

                let weez_id_billet;
                let weez_email = req.session.adherent_mail;
                //let weez_nom = results_ca_adherent[0].adherent_nom;
                let participants = {
                    "participants": [],
                    "return_ticket_url": true
                };

                let weez_prenom;
                let TICKETING_API_BASE_URL = "https://api.weezevent.com/v3/participants?";
                let url = TICKETING_API_BASE_URL;
                body = '&api_key=' + process.env.weezevent_API_KEY;
                body += '&access_token=' + process.env.weezevent_TOKEN;
                

                async function envoi_weez_api(url,body) {
                    logger.info("url = " + url , { numsession: req.session.id, label: filename});
                    logger.info("body = " + body , { numsession: req.session.id, label: filename});
                    let headers = {'content-type':'application/x-www-form-urlencoded;charset=utf-8'};
                    let premise_post_token = await fetch(url, {
                        method: 'POST',
                        headers: headers,
                        body: body
                    });
                    let response_post_token = await premise_post_token.json();
                    console.log("response_post_token = ", response_post_token);
                    logger.info("response_post_token = " + response_post_token , { numsession: req.session.id, label: filename});
                }

                // LISTING DES PARTICIPANTS
                // BILLETS ENCADRANT
                for (let toto = 1; toto < 5; toto++) {
                    if (req.session["encadrant_"+toto+"_nom"]) {
                        if (req.session["encadrant_"+toto+"_type"]=="Parent") {weez_id_billet = weez_id_billet_encadrant_parent}
                        if (req.session["encadrant_"+toto+"_type"]=="Professeur") {weez_id_billet = weez_id_billet_encadrant_prof}
                        participants.participants.push({ "id_evenement": weez_id_evenement_encadrant, "id_billet": weez_id_billet, "email": weez_email, "nom": req.session["encadrant_"+toto+"_nom"], "prenom": req.session["encadrant_"+toto+"_prenom"], "form": {"adresse": req.session.identifiant}, "notify": true });

                    }
                }


                // ENVOIE DE TOUS LES BILLETS PAR 1 REQUÈTE API
                body += '&data=' + JSON.stringify(participants);
                envoi_weez_api(url,body);

                /////////////////////////////////////
                // COPIE VERS GOOGLE SHEET
                /////////////////////////////////////

                try {
                    await GS_concert.useServiceAccountAuth(GS_creds);
                    await GS_concert.loadInfo();
                    const GS_concert_adherent = GS_concert.sheetsByTitle['adherents'];
                    const GS_concert_hebergements = GS_concert.sheetsByTitle['hebergements'];
                    const GS_concert_spectateurs = GS_concert.sheetsByTitle['spectateurs'];
                    const GS_concert_concertistes = GS_concert.sheetsByTitle['concertistes'];
                    const GS_concert_encadrants = GS_concert.sheetsByTitle['encadrants'];
                    const GS_concert_nombre_places = GS_concert.sheetsByTitle['nombre_places'];
                    const GS_concert_finance = GS_concert.sheetsByTitle['finance'];
                    const GS_concert_inscription_en_attente = GS_concert.sheetsByTitle['inscription_en_attente'];
        
                        
                    const ajout_gs_adherent = await GS_concert_adherent.addRows (
                        [
                            {
                                saison: saison,
                                identifiant: req.session.identifiant,
                                association_suzuki: req.session.association_suzuki,
                                date_inscription: now,
                                date_inscription_maj: now,
                                paiement: "gratuit",
                                adherent_nom: req.session.adherent_nom,
                                adherent_prenom: req.session.adherent_prenom,
                                adherent_telephone_mobile: "'" + req.session.adherent_telephone_mobile,
                                adherent_mail: req.session.adherent_mail,
                                nb_encadr_prof: commande_nbr_places_encadrant_prof,
                                nb_encadr_par: commande_nbr_places_encadrant_parent,
                                commentaire: req.session.commentaire_adherent,
                                date_maj_gsheet: now
                            }
                        ]
                    );

                    if (req.session.hebergement_nb > 0){
                        const ajout_gs_hebergements = await GS_concert_hebergements.addRows (
                            [
                                {
                                    saison: saison,
                                    identifiant: req.session.identifiant,
                                    hebergement_ville: req.session.hebergement_ville,
                                    hebergement_places: req.session.hebergement_nb,
                                    date_maj_gsheet: now
                                }
                            ]
                        );
                    }

                    let ajout_gs_encadrants = [];
                    for (let toto = 1; toto < 5; toto++) {
                        if (req.session["encadrant_"+toto+"_nom"]) {
                            ajout_gs_encadrants.push({
                                saison: saison,
                                identifiant: req.session.identifiant,
                                encadrant_type: req.session["encadrant_"+toto+"_type"],
                                encadrant_nom: req.session["encadrant_"+toto+"_nom"],
                                encadrant_prenom: req.session["encadrant_"+toto+"_prenom"],
                                encadrant_telephone_mobile: "'" + req.session["encadrant_"+toto+"_telephone_mobile"],
                                encadrant_mail: req.session["encadrant_"+toto+"_mail"],
                                encadrant_prof_instrument: req.session["encadrant_"+toto+"_prof_instrument"],
                                date_maj_gsheet: now
                            })
                        }
                    }
                    await GS_concert_encadrants.addRows (ajout_gs_encadrants);

                    // ONGLET nombre_places

                    // récup nombre de places dans DBca_decompte_place
                    sql = 'SELECT spectateur_commandes, concertiste_commandes, encadr_prof_commandes, encadr_parent_commandes, piano_commandes, alto_commandes, flute_commandes, trompette_commandes, harpe_commandes, violon1_commandes, violon2_commandes, violoncelle1_commandes, violoncelle2_commandes FROM ca_decompte_place';
                    const [results_ca_decompte_place, fields_ca_decompte_place] = await db_connection_promise.execute(sql);
                    
                    await GS_concert_nombre_places.loadCells('A1:O2');

                    GS_concert_nombre_places.getCellByA1('C2').value = results_ca_decompte_place[0].encadr_prof_commandes;
                    GS_concert_nombre_places.getCellByA1('D2').value = results_ca_decompte_place[0].encadr_parent_commandes;
                    GS_concert_nombre_places.getCellByA1('O2').value = now;

                    await GS_concert_nombre_places.saveUpdatedCells();


                    /////////////////////////////////////
                    // AFFICHAGE DE LA PAGE
                    res.locals.identifiant = req.session.identifiant;
                    res.locals.today = today;
                    res.locals.amount_total = 0;
                    res.render('concert/page_templates/paiement_reussi');

        
                } catch (error) {
                    // Echec de connection à la GOOGLE SHEET
                    logger.error("Il y a un problème avec la connection à Google sheet : " + error, { numsession: req.session.id });
                    req.session.err_mail_form_adhesion_1 = '"Il y a un problème système connexion base de données, veuillez recommencer, "' + error;
                };




            }


        }  catch (error) {
            // Echec de connection à la BD
            logger.error("Il y a un problème avec la connection à la base de données! : " + error, { numsession: req.session.id });
            req.session.err_mail_form_adhesion_1 = '"Il y a un problème système connexion base de données, veuillez recommencer, "' + error;
            //await db_connection_promise.end();
            affiche_page_identifier();
        }

    }


       

}


/////////////////////////////////////////////////
// EXPORT DES MODULES POUR QU'ILS PUISSENT LUS PAR LES AUTRES FICHIERS JS
/////////////////////////////////////////////////

module.exports = {
    payer
}