const express = require("express");
const mysql = require("mysql2");
const bodyParser = require("body-parser");
var cors = require("cors");
const app = express();
const port = process.env.PORT || 8087;
const fs = require("fs");
app.use(cors());


app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
app.use(express.json());


let db;

const createdbConnection = () =>{
    db = mysql.createConnection({
         host: "localhost",
        user: "familpps_ashish",
        password: "Ashish@123",
        database: "familpps_pax"
        // host: "localhost",
        // user: "root",
        // password: "",
        // database: "pax",
    });
}


// createdbConnection()
// db.connect((err) => {
//     if (err) {
//         throw err;
//     } else {
//         console.log("connected to db");

//         const createTableQuery = `
//             CREATE TABLE IF NOT EXISTS user_data (
//                 id INT AUTO_INCREMENT PRIMARY KEY,
//                 userinfo JSON,
//                 questionaire  JSON,
//                 canvasuri TEXT
//             )
//         `;
//         db.query(createTableQuery, (error, results, fields) => {
//             if (error) {
//                 throw error;
//             }
//             console.log("Table created successfully");
//         });
//     }
// });

// db.on("error", (err) => console.log(err));

app.post("/api/savedata", (req, res) => {
    createdbConnection()
    db.connect((errdb) => {
        if (errdb) {
            throw errdb;
        } else {
            const data = req.body;
            const { userinfo, canvasuri ,questionaire } = data;
            const filePath = __dirname + `/canvas/${userinfo.name + Date.now()}.png`;

            // Remove the header from the dataUrl
            const base64Data = canvasuri.replace(/^data:image\/png;base64,/, "");
            fs.writeFile(filePath, base64Data, "base64", (err) => {
                if (err) {
                    console.error(err);
                    res.sendStatus(500);
                } else {
                
                            console.log("connected to db");
                            const sql = `INSERT INTO user_data (userinfo, canvasuri,questionaire) VALUES (?, ?, ?)`;

                            var respath = filePath.replace(
                                "/home/familpps/public_html",
                                "https://familyindustriesapps.com"
                            );
                            const values = [JSON.stringify(userinfo), respath,JSON.stringify(questionaire) ];

                            db.query(sql, values, (err, result) => {
                                if (err) {
                                    throw err;
                                }
                                // console.log('Data inserted:', result);
                            
                            });
                            db.end();
                            res.send("Entry updated");
                        
                }
            });
                    
        }
    });
});

app.get("/api/fetchdb", (req, res) => {
    createdbConnection()
    db.connect((err) => {
        if (err) {
            throw err;
        } else {
            console.log("fetching from db");
            const query = "SELECT * FROM user_data";

            db.query(query, (err, result) => {
                if (err) {
                    throw err;
                } else {
                    res.status(200).json(result);
                }
            });
            db.end();
         
        }
    });
});
app.get("/", (req, res) => {
    res.send("hello, its");
});

app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});