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

// Home page
router.get('/', async (req, res) => {
  try {
    const [settings, featuredPortfolio, featuredServices] = await Promise.all([
      SiteSettings.findOne() || {},
      Portfolio.findAll({ 
        where: { featured: true, isPublished: true },
        order: [['order', 'ASC'], ['createdAt', 'DESC']],
        limit: 6
      }),
      Service.findAll({ 
        where: { featured: true, isActive: true },
        order: [['order', 'ASC']],
        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',
      settings: {},
      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',
      settings: {},
      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 [settings, portfolio, total, categories] = await Promise.all([
      SiteSettings.findOne() || {},
      Portfolio.findAll({
        where: query,
        order: [['featured', 'DESC'], ['publishedAt', 'DESC']],
        offset: skip,
        limit: limit
      }),
      Portfolio.count({ where: query }),
      Portfolio.findAll({
        where: { isPublished: true },
        attributes: ['category'],
        group: ['category']
      }).then(results => results.map(r => r.category))
    ]);

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

    res.render('portfolio', {
      title: 'Portfolio - SmartSolTech',
      settings: settings || {},
      portfolioItems: 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',
      settings: {},
      message: 'Something went wrong'
    });
  }
});

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

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

    // Get related projects
    const relatedProjects = await Portfolio.findAll({
      where: {
        id: { [Op.ne]: portfolio.id },
        category: portfolio.category,
        isPublished: true
      },
      order: [['publishedAt', 'DESC']],
      limit: 3
    });

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

// Services page
router.get('/services', async (req, res) => {
  try {
    const [settings, services, categories] = await Promise.all([
      SiteSettings.findOne() || {},
      Service.findAll({
        where: { isActive: true },
        order: [['featured', 'DESC'], ['order', 'ASC']]
      }),
      Service.findAll({
        where: { isActive: true },
        attributes: ['category'],
        group: ['category']
      })
    ]);

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

// Modern Calculator page (new UX-polished version)
router.get('/calculator', async (req, res) => {
  try {
    const [settings, services] = await Promise.all([
      SiteSettings.findOne() || {},
      Service.findAll({
        where: { isActive: true },
        attributes: ['id', 'name', 'pricing', 'category'],
        order: [['category', 'ASC'], ['name', 'ASC']]
      })
    ]);

    res.render('calculator-modern', {
      title: 'Калькулятор стоимости услуг - SmartSolTech',
      settings: settings || {},
      services,
      currentPage: 'calculator',
      siteSettings: settings || {}
    });
  } catch (error) {
    console.error('Modern calculator page error:', error);
    res.status(500).render('error', {
      title: 'Error',
      settings: {},
      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',
      settings: {},
      message: 'Something went wrong'
    });
  }
});

module.exports = router;