

# ============ توابع جدید برای گزارشات پیامکی ============

def send_daily_slaughter_statistics_sms():
    # دریافت شماره های تلفن از دیتابیس
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    
    # # شماره های hardcoded (اکنون از دیتابیس استفاده می شود)
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]
    
    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)
    
    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'
    
    province_kill_requests = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).aggregate(
        total_orders=Sum('id'),
        total_quantity=Sum('total_killed_quantity'),
        total_live_weight=Sum('total_killed_weight'),
    )
    
    orders_count = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).count()
    
    total_quantity = province_kill_requests['total_quantity'] or 0
    total_live_weight = province_kill_requests['total_live_weight'] or 0
    total_carcass_weight = int(total_live_weight * 0.75)
    average_weight = round(total_live_weight / total_quantity, 1) if total_quantity > 0 else 0
    
    kill_house_requests = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).aggregate(
        total_quantity=Sum('accepted_real_quantity'),
        total_weight=Sum('accepted_real_weight')
    )
    
    loads_count = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).count()
    
    loads_quantity = kill_house_requests['total_quantity'] or 0
    loads_weight = kill_house_requests['total_weight'] or 0
    
    formatted_quantity = to_locale_str(int(total_quantity))
    formatted_live_weight = to_locale_str(int(total_live_weight))
    formatted_carcass_weight = to_locale_str(int(total_carcass_weight))
    formatted_loads_quantity = to_locale_str(int(loads_quantity))
    formatted_loads_weight = to_locale_str(int(loads_weight))
    
    message = f'اطلاعات کشتار مرغ گوشتی مورخ {date_shamsi} استان {province_name}\n' \
              f'تعداد سفارشات: {orders_count}\n' \
              f'حجم سفارش کشتار: {formatted_quantity} قطعه\n' \
              f'وزن تقریبی زنده: {formatted_live_weight} کیلوگرم\n' \
              f'وزن تقریبی لاشه: {formatted_carcass_weight} کیلوگرم\n' \
              f'میانگین وزن زنده: {average_weight} کیلوگرم\n' \
              f'اطلاعات بارایجاد شده:\n' \
              f'تعداد بار: {loads_count}\n' \
              f'حجم بارها: {formatted_loads_quantity} قطعه\n' \
              f'وزن بارها(زنده): {formatted_loads_weight} کیلوگرم\n' \
              f'سامانه رصدیار'
    
    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}"
                    f"&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")
            except Exception as e:
                print(f"Error sending SMS to {mobile}: {str(e)}")


def send_daily_distribution_report_sms():
    # دریافت شماره های تلفن از دیتابیس
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    
    # # شماره های hardcoded (اکنون از دیتابیس استفاده می شود)
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]
    
    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)
    
    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'
    
    kill_houses = KillHouse.objects.filter(out_province=False, active=True, trash=False).order_by('name')
    
    distribution_data = []
    total_distribution_weight = 0
    
    for kill_house in kill_houses:
        kill_house_allocations = StewardAllocation.objects.filter(
            kill_house=kill_house,
            trash=False,
            receiver_state__in=('pending', 'accepted'),
            to_cold_house__isnull=True,
            date__date=target_date,
            warehouse=True
        ).aggregate(
            total_weight=Sum('real_weight_of_carcasses')
        )
        
        allocation_weight = kill_house_allocations['total_weight']
        
        if allocation_weight and allocation_weight > 0:
            distribution_data.append({
                'name': kill_house.name,
                'weight': allocation_weight
            })
            total_distribution_weight += allocation_weight
    
    if not distribution_data:
        return
    
    message_lines = [f'گزارش توزیع گوشت مرغ داخل استان']
    message_lines.append(f'مورخ {date_shamsi} استان {province_name}')
    
    for item in distribution_data:
        formatted_weight = to_locale_str(int(item['weight']))
        message_lines.append(f"{item['name']}: {formatted_weight} کیلوگرم")
    
    message_lines.append('-------------------------')
    formatted_total = to_locale_str(int(total_distribution_weight))
    message_lines.append(f'مجموع کل توزیع: {formatted_total} کیلوگرم')
    message_lines.append('سامانه رصدیار')
    
    message = '\n'.join(message_lines)
    
    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}"
                    f"&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")
            except Exception as e:
                print(f"Error sending SMS to {mobile}: {str(e)}")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def send_daily_distribution_report_sms_manual(request):
    # دریافت شماره های تلفن از دیتابیس
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    
    # # شماره های hardcoded (اکنون از دیتابیس استفاده می شود)
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]
    
    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)
    
    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'
    
    kill_houses = KillHouse.objects.filter(out_province=False, active=True, trash=False).order_by('name')
    
    distribution_data = []
    total_distribution_weight = 0
    
    for kill_house in kill_houses:
        kill_house_allocations = StewardAllocation.objects.filter(
            kill_house=kill_house,
            trash=False,
            receiver_state__in=('pending', 'accepted'),
            to_cold_house__isnull=True,
            date__date=target_date,
            warehouse=True
        ).aggregate(
            total_weight=Sum('real_weight_of_carcasses')
        )
        
        allocation_weight = kill_house_allocations['total_weight']
        
        if allocation_weight and allocation_weight > 0:
            distribution_data.append({
                'name': kill_house.name,
                'weight': allocation_weight
            })
            total_distribution_weight += allocation_weight
    
    if not distribution_data:
        return HttpResponse('هیچ توزیعی برای امروز ثبت نشده است', status=status.HTTP_200_OK)
    
    message_lines = [f'گزارش توزیع گوشت مرغ داخل استان']
    message_lines.append(f'مورخ {date_shamsi} استان {province_name}')
    
    for item in distribution_data:
        formatted_weight = to_locale_str(int(item['weight']))
        message_lines.append(f"{item['name']}: {formatted_weight} کیلوگرم")
    
    message_lines.append('-------------------------')
    formatted_total = to_locale_str(int(total_distribution_weight))
    message_lines.append(f'مجموع کل توزیع: {formatted_total} کیلوگرم')
    message_lines.append('سامانه رصدیار')
    
    message = '\n'.join(message_lines)
    
    success_count = 0
    failed_numbers = []
    
    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}"
                    f"&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")
                success_count += 1
            except Exception as e:
                failed_numbers.append(mobile)
                print(f"Error sending SMS to {mobile}: {str(e)}")
        else:
            failed_numbers.append(mobile)
    
    return HttpResponse(f'گزارش توزیع با موفقیت برای {success_count} شماره ارسال شد. تعداد کشتارگاه: {len(distribution_data)}. شماره های ناموفق: {failed_numbers if failed_numbers else "ندارد"}', status=status.HTTP_200_OK)


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def send_daily_slaughter_statistics_sms_manual(request):
    # دریافت شماره های تلفن از دیتابیس
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    
    # # شماره های hardcoded (اکنون از دیتابیس استفاده می شود)
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]
    
    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)
    
    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'
    
    province_kill_requests = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).aggregate(
        total_orders=Sum('id'),
        total_quantity=Sum('total_killed_quantity'),
        total_live_weight=Sum('total_killed_weight'),
    )
    
    orders_count = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).count()
    
    total_quantity = province_kill_requests['total_quantity'] or 0
    total_live_weight = province_kill_requests['total_live_weight'] or 0
    total_carcass_weight = int(total_live_weight * 0.75)
    average_weight = round(total_live_weight / total_quantity, 1) if total_quantity > 0 else 0
    
    kill_house_requests = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).aggregate(
        total_quantity=Sum('accepted_real_quantity'),
        total_weight=Sum('accepted_real_weight')
    )
    
    loads_count = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).count()
    
    loads_quantity = kill_house_requests['total_quantity'] or 0
    loads_weight = kill_house_requests['total_weight'] or 0
    
    formatted_quantity = to_locale_str(int(total_quantity))
    formatted_live_weight = to_locale_str(int(total_live_weight))
    formatted_carcass_weight = to_locale_str(int(total_carcass_weight))
    formatted_loads_quantity = to_locale_str(int(loads_quantity))
    formatted_loads_weight = to_locale_str(int(loads_weight))
    
    message = f'اطلاعات کشتار مرغ گوشتی مورخ {date_shamsi} استان {province_name}\n' \
              f'تعداد سفارشات: {orders_count}\n' \
              f'حجم سفارش کشتار: {formatted_quantity} قطعه\n' \
              f'وزن تقریبی زنده: {formatted_live_weight} کیلوگرم\n' \
              f'وزن تقریبی لاشه: {formatted_carcass_weight} کیلوگرم\n' \
              f'میانگین وزن زنده: {average_weight} کیلوگرم\n' \
              f'اطلاعات بارایجاد شده:\n' \
              f'تعداد بار: {loads_count}\n' \
              f'حجم بارها: {formatted_loads_quantity} قطعه\n' \
              f'وزن بارها(زنده): {formatted_loads_weight} کیلوگرم\n' \
              f'سامانه رصدیار'
    
    success_count = 0
    failed_numbers = []
    
    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}"
                    f"&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")
                success_count += 1
            except Exception as e:
                failed_numbers.append(mobile)
                print(f"Error sending SMS to {mobile}: {str(e)}")
        else:
            failed_numbers.append(mobile)
    
    return HttpResponse(f'پیامک با موفقیت برای {success_count} شماره ارسال شد. شماره های ناموفق: {failed_numbers if failed_numbers else "ندارد"}', status=status.HTTP_200_OK)