/////////////////////////////////////////////////
// LOGGING
/////////////////////////////////////////////////
const logger = require("../../public/js/app/logger_lienventetemp");
/////////////////////////////////////////////////
// APPELS DES MODULES
/////////////////////////////////////////////////
const moment = require('moment');
const ejs = require('ejs');
const nodemailer = require('nodemailer');
const path = require("path");
const fs = require("fs");
const mysql = require('mysql2');
const mysql_promise = require('mysql2/promise');
const stripe = require('stripe')(process.env.STRIPE_PRIVATE_KEY);

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

////////////////////////////////////////////////////
// Configuration de la connexion à la base de données
////////////////////////////////////////////////////
const dbConfig = {
    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
};

////////////////////////////////////////////////////
// ÉCRAN 2 - PAIEMENT AVEC STRIPE
////////////////////////////////////////////////////
const post_req_stripe = async function(req, res) {

    logger.info("======================================");
    logger.info("======== FUNCTION post_req_stripe  (vente vidéo) ==========");
    logger.info("======================================");

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

    try {
        // STRIPE - ETAPE 1 - CREER l'INTENTION DE PAIEMENT
        const session_stripe = await stripe.checkout.sessions.create({
        
            metadata: {app: "vente_video"},
            mode: 'payment',
            success_url: process.env.STRIPE_VENTEVIDEO_SUCCESSURL,
            cancel_url: process.env.STRIPE_VENTEVIDEO_CANCELURL,

            line_items: [{
                price_data: {
                    currency: 'eur',
                    unit_amount: 800,
                    product_data: {
                        name: 'Film du Concert National Suzuki',
                        description: "Concert au Palais de l'UNESCO Paris du 21 avril 2024 (fichier vidéo H264/mp4)",
                    },
                },
                quantity: 1,
            }]
        });

        res.redirect(session_stripe.url)

    } catch (error) {
        // Echec de connection à la BD
        logger.error("Il y a un problème avec la connection Stripe post_req_stripe : " + error, { numsession: req.session.id });
        req.session.affiche_err_1 = '"Il y a un problème système, veuillez recommencer, "' + error;
        res.redirect('/boutique/videos');
    }

}


/////////////////////////////////////////////////
// ÉCRAN 3 - RETOUR STRIPE RÉUSSI
/////////////////////////////////////////////////
const ventevideo_accompte_reussi = async function(req, res) {
    logger.info("======================================");
    logger.info("======== FUNCTION ventevideo_accompte_reussi ==========");
    logger.info("======================================");
    //////////////////////////////////////////////////////////////////////////////
    // RETOUR STRIPE
    let id = req.query.id;
    console.log("id = ", id);
    const session_stripe = await stripe.checkout.sessions.retrieve(id);
  
    let customer_email = session_stripe.customer_email;
    let payment_status = session_stripe.payment_status;
    let amount_total = session_stripe.amount_total/100;
    let stripe_customer = session_stripe.customer;
    let stripe_payment_intent = session_stripe.payment_intent;
    let payment_method_types = session_stripe.payment_method_types;
    let stripe_status = session_stripe.status;
    


    console.log("payment_status = ", payment_status);
    console.log("stripe_customer = ", stripe_customer);
    console.log("stripe_payment_intent = ", stripe_payment_intent);
    console.log("payment_method_types = ", payment_method_types);
    console.log("stripe_status = ", stripe_status);
    console.log("customer_email = ", customer_email);

    //////////////////////////////////////////////////////////////////////////////
    // PRÉPARATION PAGE PAIEMENT RÉUSSI
    moment.locale('fr');
    let now = moment().format("YYYY-MM-DD HH:mm:ss");
    res.locals.today = now;
    res.locals.montant = amount_total;
    res.locals.mail = customer_email;

    //////////////////////////////////////////////////////////////////////////////
    // AFFICHAGE PAGE PAIEMENT RÉUSSI
    //res.render('don/page_templates/don_paiement_reussi.ejs');
    //res.status(200).json({
    //    success: true,
    //    message: "Retour de STRIPE réussi",
    //    data: payment_status
    //});
    res.render('ventevideo/page_templates/ventelien_paiement_reussi');
}

/////////////////////////////////////////////////
// ÉCRAN 3 - RETOUR STRIPE ECHEC
/////////////////////////////////////////////////
const ventevideo_accompte_annule = async function(req, res) {
    logger.info("======================================");
    logger.info("======== FUNCTION ventevideo_accompte_annule ==========");
    logger.info("======================================");
    //////////////////////////////////////////////////////////////////////////////
    // RETOUR STRIPE
    let id = req.query.id;
    const session_stripe = await stripe.checkout.sessions.retrieve(id);
    let customer_email = session_stripe.customer_email;


    let payment_status = session_stripe.payment_status;
    let amount_total = session_stripe.amount_total/100;
    let stripe_customer = session_stripe.customer;
    let stripe_payment_intent = session_stripe.payment_intent;
    let payment_method_types = session_stripe.payment_method_types;
    let stripe_status = session_stripe.status;
  
    console.log("payment_status = ", payment_status);
    console.log("stripe_customer = ", stripe_customer);
    console.log("stripe_payment_intent = ", stripe_payment_intent);
    console.log("payment_method_types = ", payment_method_types);
    console.log("stripe_status = ", stripe_status);
    console.log("customer_email = ", customer_email);  
  
    //////////////////////////////////////////////////////////////////////////////
    // AFFICHAGE PAGE PAIEMENT ANNULÉE
    // res.render('don/page_templates/don_paiement_annule.ejs');
    //res.status(200).json({
    //    success: true,
    //    message: "Retour de STRIPE échec",
    //    data: payment_status
    //);
    res.render('ventevideo/page_templates/ventelien_paiement_echec');
  }

module.exports = {
    post_req_stripe,
    ventevideo_accompte_reussi,
    ventevideo_accompte_annule
}