from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import datetime, timedelta
from django.db.models import Count, Sum, Q
from reservation.models import Reservation , ReservationWarehouse
from decimal import Decimal
from django.conf import settings
from userauth.models import MessageWhatsappTemplate
from django.template import Template, Context
# from core.management.utils import send_whatsapp_message
from waapi.utils import send_whatsapp
import time
from accountant.models import ExpenseItem,ExpensePaid



class Command(BaseCommand):
    help = 'Sending the monthly accounting report'

    def handle(self, *args, **options):
        self.stdout.write("Starting to send the monthly report...")
        try:
            message_template_obj = MessageWhatsappTemplate.objects.get(message_type='monthly_report')
            if message_template_obj.content:
                # محاسبه بازه ماه گذشته
                admin_phone = settings.MANAGER_PHONE
                today = timezone.now().date()
                first_day_this_month = today.replace(day=1)
                last_day_last_month = first_day_this_month - timedelta(days=1)
                first_day_last_month = last_day_last_month.replace(day=1)
                reservations = Reservation.objects.filter(
                    reservation_date__gte=first_day_last_month,
                    reservation_date__lte=last_day_last_month
                )
                # آمار ماه گذشته
                total_reservations = reservations.count()
                service_completed_count = reservations.filter(status='completed').count()
                service_cancelled_count = reservations.filter(status='cancelled').count()
                service_confirmed_count = reservations.filter(status='confirmed').count()
                service_technician_confirmed_count = reservations.filter(status='technician-confirmed').count()
                service_technician_reject_count = reservations.filter(status='technician-reject').count()
                service_doctor_confirmed_count = reservations.filter(status='doctor-confirmed').count()
                service_send_to_doctor_count = reservations.filter(status='send-to-doctor').count()
                service_doctor_reject_count = reservations.filter(status='doctor-reject').count()

                expenseItems = ExpenseItem.objects.filter(reservation__in=reservations)
                expenses = Decimal(0)
                expenses_details = ''
                income = Decimal(0)
                for expense in expenseItems:
                    expenses_details = expenses_details + f"total expense for {expense.reservation.service.name} of {expense.reservation.patient.get_full_name()} was ${expense.cost_dollar} with details: {expense.details} ,\n "
                    expenses += expense.cost_dollar
                    income += expense.reservation.paient_price
                    income += expense.reservation.deposit

                expenseItems = ExpenseItem.objects.filter(reservation__not_in=reservations, date=yesterday)
                for expense in expenseItems:
                    expenses_details = expenses_details + f"total expense for {expense.expense_type} was ${expense.cost_dollar} with details: {expense.description} ,\n "
                    expenses += expense.cost_dollar

                profit = income - expenses

                fee_details = ''
                fees = Decimal(0)
                expensePaids = ExpensePaid.objects.filter(date=yesterday)
                for expense in expensePaids:
                    if expense.doctor:
                        fee_details = fee_details + f"${expense.cost_dollar} payed to {expense.doctor.get_full_name()} with details: {expense.description} ,\n "
                        fees += expense.cost_dollar
                    if expense.technician:
                        fee_details = fee_details + f"${expense.cost_dollar} payed to {expense.technician.get_full_name()} with details: {expense.description} ,\n "
                        fees += expense.cost_dollar

                try:

                    template = Template(message_template_obj.content)
                    context_data = {
                        'total_reservations': total_reservations,
                        'service_completed_count': service_completed_count,
                        'service_cancelled_count': service_cancelled_count,
                        'service_doctor_reject_count': service_doctor_reject_count,
                        'service_doctor_confirmed_count': service_doctor_confirmed_count,
                        'service_send_to_doctor_count': service_send_to_doctor_count,
                        'service_technician_reject_count': service_technician_reject_count,
                        'service_technician_confirmed_count': service_technician_confirmed_count,
                        'service_confirmed_count': service_confirmed_count,
                        'expenses_details': expenses_details,
                        'fee_details': fee_details,
                        'expenses': expenses,
                        'fees': fees,
                        'income': income,
                        'profit': profit
                    }
                    context = Context(context_data)
                    personalized_message = template.render(context)
                    personalized_message = f"Monthly Report {start_date.strftime('%Y/%m/%d')} → {end_date.strftime('%Y/%m/%d')}\n"+personalized_message
                    phone = admin_phone
                    time.sleep(2)
                    success = send_whatsapp(phone, personalized_message)

                    if success:
                        print(f"✅ Appointment reminder has been sent to {admin_phone}.")
                        self.stdout.write(f"✅ Appointment reminder has been sent to {admin_phone}.")
                    else:
                        self.stdout.write(f"❌ Error sending reminder to {admin_phone}")
                except Exception as e:
                    print(e)
        except Exception as e:
            print(e)

    def get_monthly_stats(self, start_date, end_date):
        """محاسبه آمار ماهیانه"""
        reservations = Reservation.objects.filter(
            reservation_date__gte=start_date,
            reservation_date__lte=end_date
        )

        completed_reservations = reservations.filter(status='completed')

        doctor_total = completed_reservations.aggregate(
            total=Sum('doctor_price')
        )['total'] or 0

        technician_total = reservations.aggregate(
            total=Sum('technician_price')
        )['total'] or 0

        # محاسبه قیمت انبار
        reservation_warehouse_price = 0
        for reservation in reservations:
            warehouses = ReservationWarehouse.objects.filter(reservation=reservation)
            for wh in warehouses:
                reservation_warehouse_price += float(wh.price) * int(wh.quantity)

        total_price = doctor_total + technician_total + reservation_warehouse_price

        total_days = (end_date - start_date).days + 1
        avg_daily = reservations.count() / total_days if total_days > 0 else 0

        return {
            'total_reservations': reservations.count(),
            'completed': completed_reservations.count(),
            'cancelled': reservations.filter(status='cancelled').count(),
            'confirmed': reservations.filter(status='confirmed').count(),
            'payed': reservations.filter(status='paied').count(),
            'technician-confirmed': reservations.filter(status='technician-confirmed').count(),
            'technician-reject': reservations.filter(status='technician-reject').count(),
            'doctor-confirmed': reservations.filter(status='doctor-confirmed').count(),
            'send-to-doctor': reservations.filter(status='send-to-doctor').count(),
            'doctor-reject': reservations.filter(status='doctor-reject').count(),
            'total_income': completed_reservations.aggregate(
                total=Sum('paient_price')
            )['total'] or 0,
            'deposits': reservations.aggregate(
                total=Sum('deposit')
            )['total'] or 0,
            'total_price': total_price,
            'avg_daily': avg_daily
        }

    def format_monthly_report(self, start_date, end_date, stats):
        """فرمت گزارش ماهیانه"""
        return f"""
📊 Monthly Report 🗓 {start_date.strftime('%Y/%m/%d')} → {end_date.strftime('%Y/%m/%d')}
👥 Total Reservations: {stats['total_reservations']}
✅ Completed: {stats['completed']}
✅ Technician confirmed: {stats['technician-confirmed']}
✅ Doctor confirmed: {stats['doctor-confirmed']}
✅ Send to Doctor: {stats['send-to-doctor']}
❌ Technician reject: {stats['technician-reject']}
❌ Doctor reject: {stats['doctor-reject']}
❌ Cancelled: {stats['cancelled']}
⏳ Confirmed: {stats['confirmed']}
⏳ Payed: {stats['payed']}
📈 Average Daily: {stats['avg_daily']:.1f}
💰 Total Income: {stats['total_income']:,} $
💳 Deposits: {stats['deposits']:,} $
📦 Total Price (Doctor + Technician + Warehouse): {stats['total_price']:,} $
📱 Automated System Report
""".strip()
