// Good code != pretty code

        // Good code != pretty code

        import pkg from 'pg';
        import express from 'express';
        import bodyParser from 'body-parser';
        import url from 'url'
        import { fileURLToPath } from 'url';
        import path from 'path';
        import ejs from 'ejs';
        
        // Set up express app
        const app = express();
        const port = 3000;
        const { Pool } = pkg;
        const noEmail = false;
        const goodPW = false;
        
        // new Object user
        
        const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Gets the current file path/directory and defines it as dirname
        app.use(express.static(path.join(__dirname, 'public'))); // Selects the directory for static files
        console.log('Static directory:', path.join(__dirname));
        
        // Set up body parser middleware to handle form data
        app.use(bodyParser.urlencoded({ extended: true }));
        app.use(bodyParser.json());
        
        //Setting up view engine
        app.set('view engine', 'ejs');
        
        // PostgreSQL database connection configuration
        const pool = new Pool({
            host: 'localhost',           // PostgreSQL server host
            user: 'postgres',        // PostgreSQL username
            password: 'password',    // PostgreSQL password
            database: 'db1',    // Database name
            port: 5432,     // Port
        });
        
        // Function to insert data into the PostgreSQL database
        async function insertData(name, pass, email) {
            try {
                const client = await pool.connect(); // Connects to the db
        
                // Prepare the SQL query to insert data
                const sql = 'INSERT INTO users (name, pass, email) VALUES ($1, $2, $3) RETURNING *';
                const values = [name, pass, email];
        
                // Execute the query
                const res = await client.query(sql, values);
                console.log('Data inserted:', res.rows[0]);
        
                
                client.release();  // Release the client back to the pool
            } catch (error) {
                console.error('Error inserting data into the database:', error);
            }
        }
        
        app.post('/submit', async (req, res) => {
            const {name, pass, email} = req.body;
        
            let enteredInfo = res.rows;
        
            //Insert data into the db
            await insertData(name, pass, email);
        
            //Send respons back to user + debugging
            console.log("Data submitted successfully")
            res.render('submit.ejs');
        
            return enteredInfo
        });
        
        // const [info]
        
        app.post('/adminData', async (req, res) =>{
            // const {name, pass, email} = req.body;
        
            console.log("Hello")
        });
        
        async function login(email, pass, userEmail, userPass){
            console.log("Login function called")
        
        }
        
        async function count(emailSubmit){
            const client = await pool.connect();
            const email = emailSubmit.email;
            const pass = emailSubmit.pass;
            console.log(`email submitted: ${email}`);
            console.log(`password submitted: ${pass}`);
        
            const count = `SELECT count(*) FROM users WHERE email = '${email}'`; // Need the quotes around the ${email} so it takes it as a string
            const res = await client.query(count)
            const resRows = res.rows;
            const [dResRows] = resRows; ///Destructuring the JSON format, takes the JSON thingy and turns it into an array that allows its contents to be accessed by variables
            const numRows = dResRows.count // Number of returned rows
            console.log(`number of returned rows: ${numRows}`)
        
            if(numRows < 1){ //User isn't in database
                const noEmail = true;
                console.log("User doesn't have an email")
                return noEmail;
            }
            else{ //User is in database
                console.log("User does have an email")
                const noEmail = false;
                login(email)
                return noEmail;
            };
        };
        
        async function pwCheck(userPass, pass){
            if(userPass === pass){
                console.log("passwords match")
                const goodPW = true;
                return goodPW;
            }
            else{
                console.log("Passwords don't match")
                const goodPW = false;
                return goodPW;
            }
        }
        
        // Call function in /profile to get user data, if they havent signed in it'll throw an error, catch and handle, BOSH
        app.post('/middle', async (req, res) => {
            const emailSubmit = req.body;
            try{
                const client = await pool.connect();
                const noEmail = await count(emailSubmit); //Calling the count function
                const email = emailSubmit.email;
                const pass = emailSubmit.pass; // Entered password
                res.locals.email = email;
        
                if (noEmail == false){
                    const sql = `SELECT * FROM users WHERE email = '${email}'`;
                    const res1 = await client.query(sql);
                    const [user] = res1.rows;
                    const userEmail = user.email;
                    const userPass = user.pass; // Password of the user
                    const name = user.name;
                    console.log(`User email: ${userEmail}`);
                    console.log(`User password: ${userPass}`);
        
                    // const goodPW = await pwCheck(userPass, pass);
        
                    console.log(`Log in says, noEmail = ${noEmail}`)
                    console.log(user)
                    res.render('profile.ejs', { userEmail, userPass, name });
                }
                else{
                    console.log("No email found in the system")
                    console.log(`Log in says, noEmail = ${noEmail}`)
                    res.redirect('/signin');
                }
        
            } catch (error) {
                count(emailSubmit);
                console.error('Error in getting data from the database:', error);
            }
        });
        
        async function getData(email){
            console.log("getData called")
            const client = await pool.connect();
            const sql = `SELECT * FROM users where email = '${email}'`;
            const res = await client.query(sql);
            console.log(`Data got: ${res.rows}`);
        }
        
        // app.get('/login', (req, res) => {
        //     try{
        //         getData(email);
        //         res.render('profile.ejs', { email })
        //     }catch(error){
        //         console.log('Error in displaying error)
        //     }
        // });
        
        //Requirements for the bookings table
        // ID
        // email
        // day
        // time
        
        //Requirements for the hotel table
        // ID
        // Email
        // eDate (entry date)
        // lDate (leave date)
        // type (room type, how many beds)
        
        //Loyalty scheme could be something along the lines of get points for booking and then store them in the users table, display them upon logging in
        
        
        // Start the server
        app.listen(port, () => {
            console.log(`Server running at http://localhost:${port}`);
        });
        
        // Pushes index.ejs to the  res object
        app.get('/', (req, res) => {
            res.render('index.ejs');
        });
        
        app.get('/access', (req, res) => {
            res.render('access.ejs');
        });
        
        app.get('/signup', (req, res) => {
            res.render('signup.ejs');
        });
        
        app.get('/signin', (req, res) => {
            res.render('signin.ejs', noEmail);
        });
        
        app.get('/admin', (req, res) => {
            res.render('adminsignin.ejs');
        });
        
        app.get('/test', (req, res) => {
            res.render('test.ejs');
        });
        
        //404 error handling
        app.use((req, res, next) => {
            res.status(404).send("404, page not found")
        });
        
        app.use((err, req, res, next) => {
            res.locals.error = err;
            const status = err.status || 500;
            res.status(status);
            res.render('error');
          });
    

        // Good code != pretty code

        import express from 'express';
        import pg from 'pg';
        import bodyParser from 'body-parser';
        import path from 'path';
        import { fileURLToPath } from 'url';
        
        const app = express(); // Defines the express app
        const port = 3000; // Define port
        const { Pool } = pg;
        let hasEmail = false;
        
        const __dirname = path.dirname(fileURLToPath(import.meta.url)); 
        app.use(express.static(path.join(__dirname, 'public')));
        console.log('Static directory:', path.join(__dirname));
        
        // Set up body parser middleware to handle form data
        app.use(bodyParser.urlencoded({ extended: true }));
        app.use(bodyParser.json());
        
        //Setting up view engine
        app.set('view engine', 'ejs');
        
        const pool = new Pool({
            host: 'localhost',
            user: 'postgres',
            password: 'password',
            database: 'db1',
            port: 5432
        });
        
        const foo = "Balls";
        function foo1(){
            console.log(balls);
        }
        
        app.get('/', (req, res) => {
            res.render('index.ejs', {foo})
        });
        
        async function insertData(name,email, pass){
            try{
                const client = await pool.connect()
        
                const sql = 'insert into users (name, email, pass) values ($1, $2, $3) RETURNING *';
                const values = [name, email, pass];
                console.log("Name is: ",name);
        
                const res = await client.query(sql, values);
                console.log('Data inserted:', res.rows[0]);
        
                client.release();
            } catch(error){
                console.log(`Error inserting data into database ${error}`);
            }
        };
        
        async function emailCheck(email){
            try{
                const client = await pool.connect()
                const sql = `select count(*) from users where email = '${email}'`;
                const res = await client.query(sql)
                client.release();
                const count = res.rows;
                const [rows] = count;
                const tRows = rows.count; // Total rows
        
                console.log(`Returned rows ${tRows}`);
                if(tRows < 1){
                    console.log("User does not have an account");
                    hasEmail = false;
                    return hasEmail
                }
                else if(tRows <= 1){
                    console.log("User has an account")
                    hasEmail = true;
                    return hasEmail;
                };
            }catch(error){
                console.log(`Error checking email: ${error}`);
            }
        }
        
        app.post('/submit', async (req, res) => {
            try{
                const { name, email, pass } = req.body;
                let info = res.rows;
                let hasEmail = await emailCheck(email);
                console.log(`Has email?: ${hasEmail}`);
                if (hasEmail == true){
                    res.redirect('no');
                    return;
                }
                else(
                    insertData(name, email, pass)
                );
            
                res.render('submit.ejs', {info, name})
                // return info;
            }catch(error){
                console.log(`Error submitting data to database${error}`)
            }
        
        });
        
        app.get('/login', (req, res) => {
            res.render('logIn.ejs')
        });
        
        async function getData(email, pass){
            try{
                const client = await pool.connect();
                const sql = `select * from users where email = '${email}'`;
                const res = await client.query(sql);
                const rows = res.rows;
                const [user] = rows; // Destructuring
                return user;
            } catch(error){
                console.log(`Error getting data from the database ${error}`)
            }
        };

        app.post('/profile', async (req, res) => {
            const { email, pass } = req.body;
            const user = await getData(email, pass);
            // console.log(`User password: ${user.pass}`);
            // console.log(`Entered password: ${pass}`);
            if(user.pass === pass){
                console.log("Password correct")
                res.render('profile.ejs', {email});
                return;
            }
            else{
                console.log("Password incorrect");
                res.redirect('/');
            }
        });
        
        app.get('/no', (req, res) => {
            res.render('no.ejs');
        });
        
        app.listen(port, () => {
            console.log(`App is running on port ${port}`)
        });
        
        //404 error handling
        app.use((req, res, next) => {
            res.status(404).send("404, page not found")
        });
    
        
            
            
                
                
                
                
                Welcome to RZA!
            
            
                <%- include('partials/nav.ejs') %>

                
Name: <%= name %> Email: <%= email %>

Booking List

    <% data.forEach(user=> { %>
  • Booking ID: <%= user.bookid %>, Type: <%= user.type %>, Time <%= user.time %>
  • <% }); %>
// Good code != pretty code import pkg from 'pg'; import express from 'express'; import bodyParser from 'body-parser'; import url from 'url' import { fileURLToPath } from 'url'; import path from 'path'; import ejs from 'ejs'; // Set up express app const app = express(); const port = 3000; const { Pool } = pkg; const noEmail = false; const goodPW = false; const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Gets the current file path/directory and defines it as dirname app.use(express.static(path.join(__dirname, 'public'))); // Selects the directory for static files console.log('Static directory:', path.join(__dirname)); // Set up body parser middleware to handle form data app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); //Setting up view engine app.set('view engine', 'ejs'); // new user{ // "ID" : 1, // "name" : "john" // "pw" : "passwords" // "email" : "email@gmail.com" // } // new booking{ // "bookingID" : 123, // "userID" : 1, // "type" : "consultation", // "product" : "solar panel" // "date" : 12/03/2025, // "time" : "1700" // } // PostgreSQL database connection configuration const pool = new Pool({ host: 'localhost', // PostgreSQL server host user: 'postgres', // PostgreSQL username password: 'password', // PostgreSQL password database: 'db1', // Database name port: 5432, // Port }); // Function to insert data into the PostgreSQL database async function insertData(name, pass, email) { try { const client = await pool.connect(); // Connects to the db // Prepare the SQL query to insert data const sql = 'INSERT INTO users (name, pass, email) VALUES ($1, $2, $3) RETURNING *'; const values = [name, pass, email]; // Execute the query const res = await client.query(sql, values); console.log('Data inserted:', res.rows[0]); client.release(); // Release the client back to the pool } catch (error) { console.error('Error inserting data into the database:', error); } } app.post('/submit', async (req, res) => { const {name, pass, email} = req.body; let enteredInfo = res.rows; //Insert data into the db await insertData(name, pass, email); //Send respons back to user + debugging console.log("Data submitted successfully") res.render('submit.ejs'); return enteredInfo }); // const [info] app.post('/adminData', async (req, res) =>{ // const {name, pass, email} = req.body; console.log("Hello") }); async function count(email){ const client = await pool.connect(); const count = `SELECT count(*) FROM users WHERE email = '${email}'`; // Need the quotes around the ${email} so it takes it as a string const res = await client.query(count) const resRows = res.rows; const [dResRows] = resRows; ///Destructuring the JSON format, takes the JSON thingy and turns it into an array that allows its contents to be accessed by variables const numRows = dResRows.count // Number of returned rows console.log(`number of returned rows: ${numRows}`) if(numRows < 1){ //User isn't in database const hasEmail = false; console.log("User doesn't have an email") return hasEmail; } else{ //User is in database console.log("User does have an email") const hasEmail = true; return hasEmail; }; }; async function pwCheck(userPass, pass){ if(userPass === pass){ console.log("passwords match") const goodPW = true; return goodPW; } else{ console.log("Passwords don't match") const goodPW = false; return goodPW; } } async function getData(email){ console.log("getData called") const client = await pool.connect(); const sql = `SELECT * FROM users where email = '${email}'`; const res = await client.query(sql); const [data] = res.rows; return data; }; async function getBook(userID){ const client = await pool.connect(); const sql = `SELECT * FROM booking WHERE userID = '${userID}'`; console.log("Get book says userID:") console.log(userID); const res = await client.query(sql); const data = res.rows; // const dataP = JSON.stringify(data); // console.log("Get book says:"); // console.log(data); client.release(); return data; }; // Call function in /profile to get user data, if they havent signed in it'll throw an error, catch and handle, BOSH app.post('/middle', async (req, res) => { const { email, pass } = req.body; try{ const client = await pool.connect(); const hasEmail = await count(email); //Calling the count function if (hasEmail == true){ const sql = `SELECT * FROM users WHERE email = '${email}'`; const res1 = await client.query(sql); const [user] = res1.rows; // const goodPW = await pwCheck(userPass, pass); console.log(`Log in says, hasEmail = ${hasEmail}`); const gotData = await getData(email); const name = gotData.name; const userID = gotData.id; console.log(`Name: ${name}`) const data = await getBook(userID); console.log(data); res.render('profile.ejs', { email, pass, name, data: data }); } else{ console.log("No email found in the system"); console.log(`Log in says, hasEmail = ${hasEmail}`); res.redirect('/signin'); } } catch (error) { count(email); console.error('Error in getting data from the database:', error); } }); async function makeBook(email, type, time, userid){ const client = await pool.connect(); const sql = `INSERT INTO booking (userid, type, time) VALUES ($1, $2, $3) returning *`; const values = [userid, type, time]; const res = await client.query(sql, values); const data = res.rows; console.log("makeBook says:"); console.log(data); } app.get('/booking', (req, res) => { res.render('booking.ejs') }); app.post('/book', async (req, res) => { const { email, type, time } = req.body; const client = await pool.connect(); const hasEmail = await count(email); //Calling the count function if (hasEmail == true){ const sql = `SELECT id FROM users WHERE email = '${email}'`; const res1 = await client.query(sql); const [data] = res1.rows; const userID = data.id; console.log(`/book says userID: ${userID}`) const booking = makeBook(email, type, time, userID); // const booking = `select * from booking where userid = '${userID}'` // console.log(`Log in says, hasEmail = ${hasEmail}`); res.redirect('/'); client.release() } else{ console.log("No email found in the system"); console.log(`Log in says, hasEmail = ${hasEmail}`); res.redirect('/booking'); client.release() } }); // app.get('/login', (req, res) => { // try{ // getData(email); // res.render('profile.ejs', { email }) // }catch(error){ // console.log(`Error logging in ${error}`) // } // }); //Requirements for the bookings table // ID // email // day // time //Requirements for the hotel table // ID // Email // eDate (entry date) // lDate (leave date) // type (room type, how many beds) //Loyalty scheme could be something along the lines of get points for booking and then store them in the users table, display them upon logging in // Start the server app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); // Pushes index.ejs to the res object app.get('/', (req, res) => { res.render('index.ejs'); }); app.get('/access', (req, res) => { res.render('access.ejs'); }); app.get('/signup', (req, res) => { res.render('signup.ejs'); }); app.get('/signin', (req, res) => { res.render('signin.ejs', noEmail); }); app.get('/carbf', (req, res) => { res.render('carbF.ejs'); // Run calculation in carbF, output to 'result.ejs' }); app.get('/admin', (req, res) => { res.render('adminsignin.ejs'); }); app.get('/test', (req, res) => { res.render('test.ejs'); }); //404 error handling app.use((req, res, next) => { res.status(404).send("404, page not found") }); // app.use((err, req, res, next) => { // res.locals.error = err; // const status = err.status || 500; // res.status(status); // res.render('error'); // });