/////////////////////////////////////////////////
// APPELS DES MODULES
/////////////////////////////////////////////////
const path = require("path");
// CALCUL DE DATE
const moment = require('moment');
// STRIPE
const stripe = require('stripe')(process.env.STRIPE_STN_PRIVATE_KEY);

/////////////////////////////////////////////////
// APPELS DES MODULES PERSOS
/////////////////////////////////////////////////
// loggings
const logger = require("../../public/js/app/logger_stagenat");
// DB
const { connect_DB_promise } = require('../../modules/db/databaseconnect');
// VÉRIF CODE SECRET
const { verif_codesecret } = require('../../modules/verif_codesecret');

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

/////////////////////////////////////////////////
// PAGE 3 - clic sur payer acompte
// DOMAIN/stagenational/recap
//
// Ajout informations base de données
//
/////////////////////////////////////////////////

const post_payer_accompte = async function(req, res, next) {

    logger.info("======================================");
    logger.info("======== FUNCTION post_payer_acompte (STAGE) ==========");
    logger.info("======================================");

    /////////////////////////////////////////////////
    // VARIABLES
    /////////////////////////////////////////////////
    let saison = "2025/2026";
    moment.locale('fr');
    let now = moment().format("YYYY-MM-DD HH:mm:ss");
    let sql;
    let table;
    let champs;
    let values;
    
    // SI DATE LIMITE D'INSCRIPTION DÉPASSÉE ON vérifie que le code secret est bien ok
    await verif_codesecret(req, res);
    logger.info("req.session.onpeutcontinuer : " + req.session.onpeutcontinuer , { numsession: req.session.id, label: filename});

    if (req.session.onpeutcontinuer === "oui") {
        /////////////////////////////////////////////////
        // 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";
            res.redirect('/stagenational/identifier');
        } else {

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

            try {
                //Connexion
                let db_connection_promise = await connect_DB_promise();

                /////////////////////////////////////////////////
                // AJOUT PARTICIPANTS
                for (let toto = 1; toto < 7; toto++) {
                    if (req.session["personne_"+toto+"_nom"]) {

                        // QUERY ADD stn_participant
                        table = "stn_participant";
                        champs = `
                            identifiant, date_maj, stn_part_nom, stn_part_prenom, prise_charge_famille, 
                            stn_part_date_naiss, stn_part_age, stn_part_profilage, stn_role, stn_profil, 
                            stn_transport, stn_arret, instrument, instrument_ensemble, instrument_collectif, cahier, piece, 
                            prof_nom, prof_mail, concert_solo_piece, concert_solo_cahier, cours_individuel, 
                            decouverte_alto, option_choral, option_rythmique, option_eveil, option_collectif, 
                            option_ensemble, option_particulier, cout_hebergement, cout_transport, eveil_cout, 
                            dalcroze_cout, collectif_cout, ensemble_cout, particulier_cout, observation_cout, 
                            cours_cout, coursindividuel_cout, decouvrealto_cout, chant_cout, statut_suppression
                        `;
                        values = `
                            "${req.session.identifiant}", "${now}", "${req.session[`personne_${toto}_nom`]}",
                            "${req.session[`personne_${toto}_prenom`]}", "${req.session[`personne_${toto}_prise_charge_nom`]}",
                            "${req.session[`personne_${toto}_datenaissance`]}", "${req.session[`personne_${toto}_age`]}",
                            "${req.session[`personne_${toto}_profilage`]}", "${req.session[`personne_${toto}_role`]}",
                            "${req.session[`personne_${toto}_profil`]}", "${req.session[`personne_${toto}_transport_mode`]}",
                            "${req.session[`personne_${toto}_transport_arret`]}", "${req.session[`personne_${toto}_instrument`]}",
                            "${req.session[`personne_${toto}_instrument_ensemble`]}", "${req.session[`personne_${toto}_instrument_collectif`]}", "${req.session[`personne_${toto}_cahier`]}",
                            "${req.session[`personne_${toto}_piece`]}", "${req.session[`personne_${toto}_prof`]}",
                            "${req.session[`personne_${toto}_mail_prof`]}", "${req.session[`personne_${toto}_option_concertsolo_piece`]}",
                            "${req.session[`personne_${toto}_option_concertsolo_cahier`]}", "${req.session[`personne_${toto}_option_coursindividuel`]}",
                            "${req.session[`personne_${toto}_option_decouvrealto`]}", "${req.session[`personne_${toto}_opt_chantchoral`]}",
                            "${req.session[`personne_${toto}_opt_dalcroze`]}", "${req.session[`personne_${toto}_opt_eveil`]}",
                            "${req.session[`personne_${toto}_opt_collectif`]}", "${req.session[`personne_${toto}_opt_ensemble`]}",
                            "${req.session[`personne_${toto}_opt_particulier`]}", "${req.session[`personne_${toto}_cout_hebergement`]}",
                            "${req.session[`personne_${toto}_cout_transport`]}", "${req.session[`personne_${toto}_eveil_cout`]}",
                            "${req.session[`personne_${toto}_dalcroze_cout`]}", "${req.session[`personne_${toto}_collectif_cout`]}",
                            "${req.session[`personne_${toto}_ensemble_cout`]}", "${req.session[`personne_${toto}_particulier_cout`]}",
                            "${req.session[`personne_${toto}_observation_cout`]}", "${req.session[`personne_${toto}_cours_cout`]}",
                            "${req.session[`personne_${toto}_coursindividuel_cout`]}", "${req.session[`personne_${toto}_option_decouvrealto_cout`]}",
                            "${req.session[`personne_${toto}_chant_cout`]}", 0
                        `;
                        sql = 'INSERT INTO ' + table + ' (' + champs + ') VALUES (' + values + ')';

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

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

                // QUERY ADD stn_adherent

                table = "stn_adherent";

                champs = `
                    identifiant, association_suzuki, saison, date_maj, adherent_nom, adherent_prenom, 
                    adherent_telephone, adherent_mail, adherent_adresse_rue, adherent_adresse_complement, 
                    adherent_adresse_codepostal, adherent_adresse_ville, adherent_adresse_pays, 
                    stn_hebergement, stn_commentaire, acompte_initial, cout_hebergement, cout_transport, 
                    cout_cours, cout_coursparticulier, cout_decouvertealto, cout_option_surplace, 
                    cout_chantchoral, cout_dalcroze, cout_total_collectif, cout_total_ensemble, 
                    cout_total_particulier, cout_eveil, cout_observation, frais_dossier, frais_bancaire, 
                    remise_famille_nombreuse, cout_total, statut_reservation, statut_suppression
                `;

                values = `
                    "${req.session.identifiant}", "${req.session.association_suzuki}", "${saison}", "${now}", 
                    "${req.session.adherent_nom}", "${req.session.adherent_prenom}", "${req.session.adherent_telephone}", 
                    "${req.session.adherent_mail}", "${req.session.adherent_adresse_rue}", "${req.session.adherent_adresse_complement}", 
                    "${req.session.adherent_adresse_codepostal}", "${req.session.adherent_adresse_ville}", "${req.session.adherent_adresse_pays}", 
                    "${req.session.hebergement}", "${req.session.commentaire_adherent}", ${req.session.montant_accompte}, 
                    ${req.session.cout_total_hebergement}, ${req.session.cout_total_transport}, ${req.session.cout_total_cours}, 
                    ${req.session.cout_total_coursparticulier}, ${req.session.cout_total_option_decouvrealto}, 
                    ${req.session.cout_total_dalcroze_surplace}, ${req.session.cout_total_chant}, ${req.session.cout_total_dalcroze}, 
                    ${req.session.cout_total_collectif}, ${req.session.cout_total_ensemble}, ${req.session.cout_total_particulier}, 
                    ${req.session.cout_total_eveil}, ${req.session.cout_total_observation}, ${req.session.frais_dossier}, 
                    ${req.session.accompte_frais_bancaire}, ${req.session.remise_fn_montant}, ${req.session.cout_total}, "attente", 0
                `;

                sql = `INSERT INTO ${table} (${champs}) VALUES (${values})`;
                
                const [results_stn_adherent, fields] = await db_connection_promise.execute(sql);
                
                logger.info("stn_adherent Row ID added : " + results_stn_adherent.insertId, { numsession: req.session.id, label: filename});

                await db_connection_promise.end();

                if (req.session.montant_accompte > 100) {
                    /////////////////////////////////////////////////
                    // STRIPE - ETAPE 1 - CREER l'INTENTION DE PAIEMENT

                    logger.info("======================================", { label: filename });
                    logger.info("======== ENVOIE VERS STRIPE ==========", { label: filename });
                    logger.info("======================================", { label: filename });
                    

                    const session = await stripe.checkout.sessions.create({
                        metadata: {identifiant: req.session.identifiant, compteur_ado: req.session.compteur_ado, code_secret: req.session.code_secret},
                        customer_email: req.session.adherent_mail,
                        
                        submit_type: 'pay',
                        
                        success_url: process.env.STRIPE_SN_SUCCESSURL,
                        cancel_url: process.env.STRIPE_SN_CANCELURL,

                        payment_method_types: ['card'],
                        line_items: [{
                            price_data: {
                            currency: 'eur',
                            product_data: {
                                name: 'Stage national AFPS acompte',
                            },
                            unit_amount: req.session.montant_accompte * 100,
                            },
                            quantity: 1,
                        },],
                        //Checkout has three modes: payment, subscription, or setup. 
                        mode: 'payment'
                
                    });
                    res.redirect(session.url)
                }

                if (req.session.montant_accompte < 100) {
                    res.redirect('/stagenational/paiement_reussi');
                }

                
                
            }  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, label: filename});
                req.session.err_mail_form_adhesion_1 = '"Il y a un problème système connexion base de données, veuillez recommencer, "' + error;
                res.redirect('/stagenational/identifier');
            }

        }

    } else {
        req.session.err_mail_form_adhesion_1 = 'Votre session est terminée ("onpeutcontinuer" = non), veuillez recommencer.';
        res.redirect('/stagenational/identifier');
    }
}


/////////////////////////////////////////////////
// EXPORT DE MODULE POUR QU'IL SOIT LU DANS LES AUTRES FICHIERS JS
/////////////////////////////////////////////////

module.exports = {
    post_payer_accompte
}