// Import the 'path' module
const path = require("path");
const express = require("express");
const sqlite3 = require("sqlite3").verbose();

const app = express();
const db = new sqlite3.Database("cart.db");

// Use middleware to parse the request body
app.use(express.urlencoded({ extended: true }));

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "form.html"));
});

app.get("/categories", (req, res) => {
  const selectCategoriesQuery = `SELECT * FROM categories`;
  db.all(selectCategoriesQuery, (err, rows) => {
    if (err) {
      console.error(err);
      res.status(500).json({ error: "Failed to fetch categories" });
    } else {
      res.json(rows);
    }
  });
});

// Handle POST request to add a new category
app.post("/addCategory", (req, res) => {
  const categoryName = req.body.categoryName;

  // Insert the new category into the categories table
  const insertCategoryQuery = `INSERT INTO categories (name) VALUES (?)`;
  db.run(insertCategoryQuery, [categoryName], (err) => {
    if (err) {
      console.error(err);
      res.status(500).send("Error adding category");
    } else {
      res.send(`
          <script>
            alert('Category added successfully');
            window.location.href = '/';
          </script>
        `);
    }
  });
});

// Handle POST request to add a new product
app.post("/addProduct", (req, res) => {
  const productName = req.body.productName;
  const category = req.body.category;
  const price = req.body.price;
  const description = req.body.description;

  let imageUrl = "";
  if (req.file) {
    imageUrl = req.file.filename;
  }

  // Insert the new product into the products table
  const insertProductQuery = `INSERT INTO products (name, catid, price, description) VALUES (?, ?, ?, ?)`;
  db.run(
    insertProductQuery,
    [productName, category, price, description],
    (err) => {
      if (err) {
        console.error(err);
        res.status(500).send("Error adding product");
      } else {
        res.send(`
        <script>
          alert('Category added successfully');
          window.location.href = '/';
        </script>
      `);
      }
    }
  );
});

// Start the server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});
