const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
require("dotenv").config();
const userRouter = require("./routes/userroutes");
const db = require('./models');
const productRoutes = require('./routes/productRoutes');
const categoryRoutes = require('./routes/categoryRoutes');
const path = require('path');
const multer = require('multer');


// Initialize express app
const app = express();


// Middleware
app.use(cors());  // Enable CORS for all routes
app.use(helmet());  // Set security HTTP headers
app.use(express.json());  // Parse JSON bodies
app.use(express.urlencoded({ extended: true }));  // Parse URL-encoded bodies



// Routes
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use('/users', userRouter)
app.use("/api/products", productRoutes)
app.use("/api/categories", categoryRoutes)
// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

// Start server
const PORT = process.env.PORT || 5000;

db.sequelize.sync({ force: false }).then(() => {
  console.log('Database synced');
  const PORT = process.env.PORT || 5000;
  app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
  });
}).catch((err) => {
  console.error('Failed to sync database:', err);
});

in categorypage :
 <div>
        <h2 className="text-3xl font-bold mb-6">
          {selectedCategory 
            ? `Products in ${categories.find(c => c.id === selectedCategory)?.name}`
            : 'All Products'}
        </h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
          {filteredProducts.map((product) => (
            <div key={product.id} className="bg-gray-800 p-6 rounded-lg">
              {product.image_url && (
                <img 
                  src={`http://localhost:5000${product.image_url}`} 
                  alt={product.name} 
                  className="w-full h-48 object-cover mb-4 rounded"
                />
              )}
              <h3 className="text-xl font-semibold mb-2">{product.name}</h3>
              <p className="text-gray-400">{product.description}</p>
              <p className="mt-2">Price: ${product.price}</p>
              <p>Stock: {product.stock_quantity}</p>
              {product.is_custom && <p className="text-secondary">Custom Design</p>}
            </div>
          ))}
        </div>
      </div>
 const { category } = useParams();
  const [categories, setCategories] = useState([]);
  const [products, setProducts] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(category || null);

  useEffect(() => {
    // Fetch categories
    axios.get('http://localhost:5000/api/categories')
      .then(response => setCategories(response.data))
      .catch(error => console.error('Error fetching categories:', error));

    // Fetch products
    axios.get('http://localhost:5000/api/products')
      .then(response => setProducts(response.data))
      .catch(error => console.error('Error fetching products:', error));
  }, []);

  const handleCategoryClick = (categoryId) => {
    setSelectedCategory(categoryId);
  };

  // Filter products based on selected category
  const filteredProducts = selectedCategory
    ? products.filter(product => product.category_id === selectedCategory)
    : products;
in multerConfig.js:
const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

module.exports = upload;