const express = require("express");
const { query } = require("../config/database");
const { requireAuth } = require("../middleware/auth");
const router = express.Router();

// Dashboard stats API
router.get("/dashboard/stats", requireAuth, async (req, res) => {
  try {
    const productsCount = await query("SELECT COUNT(*) FROM products");
    const projectsCount = await query("SELECT COUNT(*) FROM portfolioprojects");
    const blogCount = await query("SELECT COUNT(*) FROM blogposts");
    const pagesCount = await query("SELECT COUNT(*) FROM pages");

    res.json({
      success: true,
      stats: {
        products: parseInt(productsCount.rows[0].count),
        projects: parseInt(projectsCount.rows[0].count),
        blog: parseInt(blogCount.rows[0].count),
        pages: parseInt(pagesCount.rows[0].count),
      },
      user: {
        name: req.session.name,
        email: req.session.email,
        role: req.session.role,
      },
    });
  } catch (error) {
    console.error("Dashboard error:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
});

// Products API
router.get("/products", requireAuth, async (req, res) => {
  try {
    const result = await query(
      "SELECT id, name, price, stockquantity, isactive, createdat FROM products ORDER BY createdat DESC"
    );
    res.json({
      success: true,
      products: result.rows,
    });
  } catch (error) {
    console.error("Products error:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
});

// Portfolio Projects API
router.get("/portfolio/projects", requireAuth, async (req, res) => {
  try {
    const result = await query(
      "SELECT id, title, description, imageurl, categoryid, createdat FROM portfolioprojects ORDER BY createdat DESC"
    );
    res.json({
      success: true,
      projects: result.rows,
    });
  } catch (error) {
    console.error("Portfolio error:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
});

// Blog Posts API
router.get("/blog", requireAuth, async (req, res) => {
  try {
    const result = await query(
      "SELECT id, title, slug, excerpt, ispublished, createdat FROM blogposts ORDER BY createdat DESC"
    );
    res.json({
      success: true,
      posts: result.rows,
    });
  } catch (error) {
    console.error("Blog error:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
});

// Pages API
router.get("/pages", requireAuth, async (req, res) => {
  try {
    const result = await query(
      "SELECT id, title, slug, ispublished, createdat FROM pages ORDER BY createdat DESC"
    );
    res.json({
      success: true,
      pages: result.rows,
    });
  } catch (error) {
    console.error("Pages error:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
});

module.exports = router;
