const { Booking, Payment, Customer, Vehicle, Driver, Route, Schedule, Review, User } = require('../models');
const { Op, fn, col, literal } = require('sequelize');

class DashboardController {
  async getStats(req, res, next) {
    try {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

      const [
        totalBookings,
        monthlyBookings,
        todayBookings,
        totalRevenue,
        monthlyRevenue,
        totalCustomers,
        activeVehicles,
        activeDrivers,
        activeRoutes,
        pendingBookings,
        recentBookings,
        revenueByMethod,
        bookingsByStatus,
        reviewsSummary,
      ] = await Promise.all([
        Booking.count(),
        Booking.count({ where: { created_at: { [Op.gte]: startOfMonth } } }),
        Booking.count({ where: { created_at: { [Op.gte]: today } } }),
        Payment.sum('amount', { where: { payment_status: 'completed' } }),
        Payment.sum('amount', {
          where: { payment_status: 'completed', payment_date: { [Op.gte]: startOfMonth } },
        }),
        Customer.count(),
        Vehicle.count({ where: { is_active: true } }),
        Driver.count({ where: { is_active: true } }),
        Route.count({ where: { is_active: true } }),
        Booking.count({ where: { booking_status: { [Op.in]: ['pending', 'POP_uploaded', 'pending_approval'] } } }),
        Booking.findAll({
          include: [{ model: Schedule, include: [{ model: Route }, { model: Vehicle }] }],
          order: [['created_at', 'DESC']],
          limit: 5,
        }),
        Payment.findAll({
          attributes: ['payment_method', [fn('SUM', col('amount')), 'total']],
          where: { payment_status: 'completed' },
          group: ['payment_method'],
        }),
        Booking.findAll({
          attributes: ['booking_status', [fn('COUNT', col('id')), 'count']],
          group: ['booking_status'],
        }),
        Review.findAll({
          attributes: [
            [fn('COUNT', col('id')), 'total'],
            [fn('AVG', col('rating')), 'average_rating'],
          ],
        }),
      ]);

      res.json({
        summary: {
          total_bookings: totalBookings,
          monthly_bookings: monthlyBookings,
          today_bookings: todayBookings,
          total_revenue: totalRevenue || 0,
          monthly_revenue: monthlyRevenue || 0,
          total_customers: totalCustomers,
          active_vehicles: activeVehicles,
          active_drivers: activeDrivers,
          active_routes: activeRoutes,
          pending_bookings: pendingBookings,
          average_rating: reviewsSummary[0] ? parseFloat(reviewsSummary[0].dataValues.average_rating || 0).toFixed(1) : 0,
        },
        revenue_by_method: revenueByMethod,
        bookings_by_status: bookingsByStatus,
        recent_bookings: recentBookings,
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new DashboardController();
