import express, { query } from "express";
import bodyParser from "body-parser";
import pg from "pg";

const app = express();
const port = 4000;

const db=new pg.Client({
    user:"postgres",
    password:"7008",
    database:"Workers",
    host:"localhost",
    port:5432
});

db.connect((err)=>{
    if(err){
        console.log("Database Connection Failed");
    }else{
        console.log("DataBase Connected");
    }
})

app.use(bodyParser.urlencoded({extended : true}));
app.use(express.static("public"));

app.get('/', async (req, res) => {
    try {
        const result = await db.query('SELECT * FROM workers_data'); // Fetch all workers
        res.render('home.ejs', { workers: result.rows }); // Pass data to the frontend
    } catch (err) {
        console.error('Error fetching data:', err.stack);
        res.status(500).send('Internal Server Error');
    }
});

app.get("/register",(req,res)=>{
    res.render("register.ejs");
})


app.get("/search", async (req, res) => {
    const { location, profession } = req.query; // Destructure location and profession

    let query = "SELECT * FROM workers_data WHERE 1=1";
    let values = [];

    // Adding location filter if provided
    if (location) {
        query += " AND location=$" + (values.length + 1);
        values.push(location);
    }

    // Adding profession filter if provided
    if (profession) {
        query += " AND profession=$" + (values.length + 1);
        values.push(profession);
    }

    try {
        const response = await db.query(query, values); // Pass dynamic values to the query
        console.log(response.rows); // Log the response for debugging
        const result = response.rows;

        // Render the result in the list view
        res.render("list.ejs", {
            data: result
        });
    } catch (err) {
        console.log(err); // Log error in case of failure
        res.status(500).send("An error occurred");
    }
});


app.post("/submit",async(req,res)=>{
    const name = req.body.username;
    const phone = req.body.phone;
    const profession = req.body.profession;
    const location = req.body.location;

    try{
        const response = await db.query("insert into workers_data (name,phone,location,profession) VALUES($1,$2,$3,$4)",[name,phone,location,profession]);
        console.log("Data Inserted");
        alert("Worker Registered.")
        
    }catch(err){
        console.log(err);
    }
})



app.listen(port,()=>{
    console.log(`Server Running from Port ${port}`);
})