package service

import "wails-app/internal/global"

type RevenueItem struct {
	Date       string  `json:"date"`
	ParkingLot string  `json:"parking_lot"`
	Cash       float64 `json:"cash"`
	Free       float64 `json:"free"`
	Total      float64 `json:"total"`
	Count      int64   `json:"count"`
}

type ReportService struct{}

func (s *ReportService) RevenueReport(startDate, endDate string, lotID uint) ([]RevenueItem, error) {
	var items []RevenueItem
	db := global.GVA_DB.Table("payment_record p").
		Select(`DATE(p.paid_at) as date, COALESCE(pr.lot_name,'-') as parking_lot,
			COALESCE(SUM(CASE WHEN p.payment_method='cash' THEN p.amount ELSE 0 END),0) as cash,
			COALESCE(SUM(CASE WHEN p.payment_method='free' THEN p.amount ELSE 0 END),0) as free,
			COALESCE(SUM(p.amount),0) as total, COUNT(*) as count`).
		Joins("LEFT JOIN vehicle_record vr ON vr.id = p.record_id").
		Joins("LEFT JOIN parking_lot pr ON pr.id = vr.parking_lot_id")
	if startDate != "" && endDate != "" {
		db = db.Where("p.paid_at >= ? AND p.paid_at <= ?", startDate, endDate+" 23:59:59")
	}
	if lotID > 0 {
		db = db.Where("vr.parking_lot_id = ?", lotID)
	}
	err := db.Group("DATE(p.paid_at), vr.parking_lot_id").Order("date DESC").Scan(&items).Error
	return items, err
}
