const express = require('express');
const router = express.Router();
const { Portfolio, Service, SiteSettings } = require('../models');

// Home page
router.get('/', async (req, res) => {
  try {
    const [settings, featuredPortfolio, featuredServices] = await Promise.all([
      SiteSettings.findOne() || {},
      Portfolio.find({ featured: true, isPublished: true })
        .sort({ order: 1, createdAt: -1 })
        .limit(6),
      Service.find({ featured: true, isActive: true })
        .sort({ order: 1 })
        .limit(4)
    ]);

    res.render('index', {
      title: 'SmartSolTech - Innovative Technology Solutions',
      settings: settings || {},
      featuredPortfolio,
      featuredServices,
      currentPage: 'home'
    });
  } catch (error) {
    console.error('Home page error:', error);
    res.status(500).render('error', {
      title: 'Error',
      message: 'Something went wrong'
    });
  }
});

// About page
router.get('/about', async (req, res) => {
  try {
    const settings = await SiteSettings.findOne() || {};
    
    res.render('about', {
      title: 'About Us - SmartSolTech',
      settings,
      currentPage: 'about'
    });
  } catch (error) {
    console.error('About page error:', error);
    res.status(500).render('error', {
      title: 'Error',
      message: 'Something went wrong'
    });
  }
});

// Portfolio page
router.get('/portfolio', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = 12;
    const skip = (page - 1) * limit;
    const category = req.query.category;

    let query = { isPublished: true };
    if (category && category !== 'all') {
      query.category = category;
    }

    const [portfolio, total, categories] = await Promise.all([
      Portfolio.find(query)
        .sort({ featured: -1, publishedAt: -1 })
        .skip(skip)
        .limit(limit),
      Portfolio.countDocuments(query),
      Portfolio.distinct('category', { isPublished: true })
    ]);

    const totalPages = Math.ceil(total / limit);

    res.render('portfolio', {
      title: 'Portfolio - SmartSolTech',
      portfolio,
      categories,
      currentCategory: category || 'all',
      pagination: {
        current: page,
        total: totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1
      },
      currentPage: 'portfolio'
    });
  } catch (error) {
    console.error('Portfolio page error:', error);
    res.status(500).render('error', {
      title: 'Error',
      message: 'Something went wrong'
    });
  }
});

// Portfolio detail page
router.get('/portfolio/:id', async (req, res) => {
  try {
    const portfolio = await Portfolio.findById(req.params.id);
    
    if (!portfolio || !portfolio.isPublished) {
      return res.status(404).render('404', {
        title: '404 - Project Not Found',
        message: 'The requested project was not found'
      });
    }

    // Increment view count
    portfolio.viewCount += 1;
    await portfolio.save();

    // Get related projects
    const relatedProjects = await Portfolio.find({
      _id: { $ne: portfolio._id },
      category: portfolio.category,
      isPublished: true
    }).limit(3);

    res.render('portfolio-detail', {
      title: `${portfolio.title} - Portfolio - SmartSolTech`,
      portfolio,
      relatedProjects,
      currentPage: 'portfolio'
    });
  } catch (error) {
    console.error('Portfolio detail error:', error);
    res.status(500).render('error', {
      title: 'Error',
      message: 'Something went wrong'
    });
  }
});

// Services page
router.get('/services', async (req, res) => {
  try {
    const services = await Service.find({ isActive: true })
      .sort({ featured: -1, order: 1 })
      .populate('portfolio', 'title images');

    const categories = await Service.distinct('category', { isActive: true });

    res.render('services', {
      title: 'Services - SmartSolTech',
      services,
      categories,
      currentPage: 'services'
    });
  } catch (error) {
    console.error('Services page error:', error);
    res.status(500).render('error', {
      title: 'Error',
      message: 'Something went wrong'
    });
  }
});

// Calculator page
router.get('/calculator', async (req, res) => {
  try {
    const services = await Service.find({ isActive: true })
      .select('name pricing category')
      .sort({ category: 1, name: 1 });

    res.render('calculator', {
      title: 'Project Calculator - SmartSolTech',
      services,
      currentPage: 'calculator'
    });
  } catch (error) {
    console.error('Calculator page error:', error);
    res.status(500).render('error', {
      title: 'Error',
      message: 'Something went wrong'
    });
  }
});

// Contact page
router.get('/contact', async (req, res) => {
  try {
    const settings = await SiteSettings.findOne() || {};
    
    res.render('contact', {
      title: 'Contact Us - SmartSolTech',
      settings,
      currentPage: 'contact'
    });
  } catch (error) {
    console.error('Contact page error:', error);
    res.status(500).render('error', {
      title: 'Error',
      message: 'Something went wrong'
    });
  }
});

module.exports = router;