from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import *
from .serializers import *
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from django.conf import settings
import os
import json
from decimal import Decimal
from rest_framework import generics




# class MachineRegistrationView(APIView):
#     def get(self, request):
#         machines = MachineRegistration.objects.all()
#         serializer = MachineRegistrationSerializer(machines, many=True)
#         return Response(serializer.data)
#
#     def post(self, request):
#         serializer = MachineRegistrationSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_201_CREATED)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class MachineRegistrationView(APIView):
    def get(self, request):
        machines = MachineRegistration.objects.all()
        serializer = MachineRegistrationSerializer(machines, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = MachineRegistrationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# class BudgetingView(APIView):
#     def get(self, request):
#         budgets = Budgeting.objects.all()
#         serializer = BudgetingSerializer(budgets, many=True)
#         return Response(serializer.data)
#
#     def post(self, request):
#         serializer = BudgetingSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_201_CREATED)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# class BudgetingView(APIView):
#     def get(self, request):
#         budgets = Budgeting.objects.all()
#         serializer = BudgetingSerializer(budgets, many=True)
#         return Response(serializer.data)
#
#     def post(self, request):
#         serializer = BudgetingSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_201_CREATED)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
#     def patch(self, request):
#         budgeting_id = request.data.get('id')
#         if not budgeting_id:
#             return Response({'error': 'ID is required for PATCH'}, status=status.HTTP_400_BAD_REQUEST)
#
#         try:
#             budgeting = Budgeting.objects.get(id=budgeting_id)
#         except Budgeting.DoesNotExist:
#             return Response({'error': 'Budgeting object not found'}, status=status.HTTP_404_NOT_FOUND)
#
#         serializer = BudgetingSerializer(budgeting, data=request.data, partial=True)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_200_OK)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BudgetingView(APIView):
    def post(self, request):
        data = request.data.copy()
        row_number = data.get('row_number')
        zone_id = data.get('zone')
        crop_id = data.get('crop')

        if not (row_number and zone_id and crop_id):
            return Response({'error': 'row_number, zone, and crop are required'}, status=400)

        try:
            row_index = int(row_number) - 1
            crop_plan_rows = CropPlanRow.objects.filter(
                user_crop_plan__zone_id=zone_id,
                user_crop_plan__crop_id=crop_id
            ).order_by('id')
            crop_plan_row = crop_plan_rows[row_index]
            data['crop_plan_row'] = crop_plan_row.id
        except (IndexError, ValueError):
            return Response({'error': 'Invalid row_number or no matching crop plan rows found'}, status=400)

        serializer = BudgetingSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request):
        data = request.data.copy()
        budgeting_id = data.get('id')

        if not budgeting_id:
            return Response({'error': 'ID is required for PATCH'}, status=400)

        try:
            budgeting = Budgeting.objects.get(id=budgeting_id)
        except Budgeting.DoesNotExist:
            return Response({'error': 'Budgeting object not found'}, status=404)

        # Optional update of crop_plan_row if row_number, zone, and crop are provided
        row_number = data.get('row_number')
        zone_id = data.get('zone')
        crop_id = data.get('crop')

        if row_number and zone_id and crop_id:
            try:
                row_index = int(row_number) - 1
                crop_plan_rows = CropPlanRow.objects.filter(
                    user_crop_plan__zone_id=zone_id,
                    user_crop_plan__crop_id=crop_id
                ).order_by('id')
                crop_plan_row = crop_plan_rows[row_index]
                data['crop_plan_row'] = crop_plan_row.id
            except (IndexError, ValueError):
                return Response({'error': 'Invalid row_number or no matching crop plan rows found'}, status=400)

        serializer = BudgetingSerializer(budgeting, data=data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        budgets = Budgeting.objects.all()
        serializer = BudgetingSerializer(budgets, many=True)
        return Response(serializer.data)
from django.shortcuts import get_object_or_404

class MachineRegistrationDetailView(APIView):
    def get_object(self, pk):
        return get_object_or_404(MachineRegistration, pk=pk)

    def get(self, request, pk):
        machine = self.get_object(pk)
        serializer = MachineRegistrationSerializer(machine)
        return Response(serializer.data)

    def put(self, request, pk):
        machine = self.get_object(pk)
        serializer = MachineRegistrationSerializer(machine, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, pk):
        machine = self.get_object(pk)
        serializer = MachineRegistrationSerializer(machine, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



class InputMasterListCreateAPIView(generics.ListCreateAPIView):
    queryset = InputMaster.objects.all().order_by('-created_at')
    serializer_class = InputMasterSerializer

class InputMasterDetailView(APIView):
    def get_object(self, pk):
        return get_object_or_404(InputMaster, pk=pk)

    def get(self, request, pk):
        input_obj = self.get_object(pk)
        serializer = InputMasterSerializer(input_obj)
        return Response(serializer.data)

    def put(self, request, pk):
        input_obj = self.get_object(pk)
        serializer = InputMasterSerializer(input_obj, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, pk):
        input_obj = self.get_object(pk)
        serializer = InputMasterSerializer(input_obj, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)





# class BudgetingSummaryView(APIView):
#     permission_classes = [AllowAny]
#
#     def load_translations(self, language):
#         try:
#             file_name = f"{language}_translations.json"
#             file_path = os.path.join(settings.BASE_DIR, file_name)
#             with open(file_path, 'r', encoding='utf-8') as f:
#                 return json.load(f)
#         except Exception:
#             return {'labour': {}}
#
#     def translate_text(self, text, translation_map, key='labour', language='en'):
#         translated = translation_map.get(key, {}).get(text)
#         if translated:
#             return translated
#         if language in ['ml', 'ta']:
#             try:
#                 from googletrans import Translator
#                 return Translator().translate(text, src='en', dest=language).text
#             except Exception:
#                 pass
#         return text
#
#     def calculate_summary(self, budgets):
#         total_labour_cost = Decimal(0)
#         total_machine_cost = Decimal(0)
#         total_input_cost = Decimal(0)
#         total_miscellaneous = Decimal(0)
#
#         for budget in budgets:
#             # Labour
#             labour = budget.labour_estimation
#             try:
#                 male = Decimal(labour.get('male_labour_cost', 0)) * int(labour.get('male_labour_count', 0)) * int(labour.get('male_hours', 0))
#                 female = Decimal(labour.get('female_labour_cost', 0)) * int(labour.get('female_labour_count', 0)) * int(labour.get('female_hours', 0))
#                 total_labour_cost += male + female
#             except Exception:
#                 pass
#
#             # Machine
#             machine = budget.machine_estimation
#             try:
#                 mc = Decimal(machine.get('machine_count', 0))
#                 rate = Decimal(machine.get('rate_per_hour', 0))
#                 hrs = Decimal(machine.get('working_hours', 0))
#                 total_machine_cost += mc * rate * hrs
#             except Exception:
#                 pass
#
#             # Input
#             input_data = budget.input_estimation
#             try:
#                 qty = Decimal(input_data.get('input_quantity', 0))
#                 cost = Decimal(input_data.get('input_cost', 0))
#                 total_input_cost += qty * cost
#             except Exception:
#                 pass
#
#             # Miscellaneous
#             try:
#                 total_miscellaneous += Decimal(budget.miscellaneous or 0)
#             except Exception:
#                 pass
#
#         total_cost = total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous
#
#         return {
#             "total_labour_cost": str(total_labour_cost),
#             "total_machine_cost": str(total_machine_cost),
#             "total_input_cost": str(total_input_cost),
#             "total_miscellaneous": str(total_miscellaneous),
#             "total_budget_cost": str(total_cost)
#         }
#
#     def get(self, request, *args, **kwargs):
#         stage = request.query_params.get('stage')
#         language = request.query_params.get('language', 'en')
#
#         try:
#             if stage:
#                 budgets = Budgeting.objects.filter(stage__iexact=stage)
#                 if not budgets.exists():
#                     return JsonResponse({'error': f"No data found for stage '{stage}'"}, status=404)
#                 summary = self.calculate_summary(budgets)
#                 summary['stage'] = stage
#             else:
#                 budgets = Budgeting.objects.all()
#                 summary = self.calculate_summary(budgets)
#                 summary['stage'] = 'All'
#
#             # Optional translation (only labels if mapped)
#             translations = self.load_translations(language)
#             for key in summary:
#                 summary[key] = self.translate_text(summary[key], translations, key='labour', language=language)
#
#             return JsonResponse(summary)
#
#         except Exception as e:
#             return JsonResponse({'error': str(e)}, status=500)

from decimal import Decimal
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
import json
import os
from .models import Budgeting

# class BudgetingSummaryView(APIView):
#     permission_classes = [AllowAny]
#
#     def load_translations(self, language):
#         try:
#             file_name = f"{language}_translations.json"
#             file_path = os.path.join(settings.BASE_DIR, file_name)
#             with open(file_path, 'r', encoding='utf-8') as f:
#                 return json.load(f)
#         except Exception:
#             return {'labour': {}}
#
#     def translate_text(self, text, translation_map, key='labour', language='en'):
#         translated = translation_map.get(key, {}).get(text)
#         if translated:
#             return translated
#         if language in ['ml', 'ta']:
#             try:
#                 from googletrans import Translator
#                 return Translator().translate(text, src='en', dest=language).text
#             except Exception:
#                 pass
#         return text
#
#     def calculate_summary(self, budgets):
#         total_labour_cost = Decimal(0)
#         total_machine_cost = Decimal(0)
#         total_input_cost = Decimal(0)
#         total_miscellaneous = Decimal(0)
#
#         for budget in budgets:
#             # Labour Estimation
#             labour = budget.labour_estimation
#             try:
#                 male = Decimal(labour.get('male_labour_cost', 0)) * int(labour.get('male_labour_count', 0)) * int(labour.get('male_hours', 0))
#                 female = Decimal(labour.get('female_labour_cost', 0)) * int(labour.get('female_labour_count', 0)) * int(labour.get('female_hours', 0))
#                 total_labour_cost += male + female
#             except Exception:
#                 pass
#
#             # Machine Estimation
#             machine_data = budget.machine_estimation
#             try:
#                 mc = Decimal(machine_data.get('machine_count', 0))
#                 hrs = Decimal(machine_data.get('working_hours', 0))
#
#                 # Get rate from related machine model
#                 rate = Decimal(0)
#                 if budget.machine and budget.machine.rate_per_hour:
#                     rate = Decimal(budget.machine.rate_per_hour)
#
#                 total_machine_cost += mc * rate * hrs
#             except Exception:
#                 pass
#
#             # Input Estimation
#             input_data = budget.input_estimation
#             try:
#                 qty = Decimal(input_data.get('input_quantity', 0))
#                 cost = Decimal(input_data.get('input_cost', 0))
#                 total_input_cost += qty * cost
#             except Exception:
#                 pass
#
#             # Miscellaneous
#             try:
#                 total_miscellaneous += Decimal(budget.miscellaneous or 0)
#             except Exception:
#                 pass
#
#         total_cost = total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous
#
#         return {
#             "total_labour_cost": str(total_labour_cost),
#             "total_machine_cost": str(total_machine_cost),
#             "total_input_cost": str(total_input_cost),
#             "total_miscellaneous": str(total_miscellaneous),
#             "total_budget_cost": str(total_cost)
#         }
#
#     def get(self, request, *args, **kwargs):
#         stage = request.query_params.get('stage')
#         language = request.query_params.get('language', 'en')
#
#         try:
#             if stage:
#                 budgets = Budgeting.objects.filter(stage__iexact=stage)
#                 if not budgets.exists():
#                     return JsonResponse({'error': f"No data found for stage '{stage}'"}, status=404)
#                 summary = self.calculate_summary(budgets)
#                 summary['stage'] = stage
#             else:
#                 budgets = Budgeting.objects.all()
#                 summary = self.calculate_summary(budgets)
#                 summary['stage'] = 'All'
#
#             # Apply translations if available
#             translations = self.load_translations(language)
#             for key in summary:
#                 summary[key] = self.translate_text(summary[key], translations, key='labour', language=language)
#
#             return JsonResponse(summary)
#
#         except Exception as e:
#             return JsonResponse({'error': str(e)}, status=500)
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django.http import JsonResponse
from decimal import Decimal
import json
import os

from .models import Budgeting

from decimal import Decimal
import os
import json
from django.conf import settings
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from .models import Budgeting  # Make sure your model import is correct

# class BudgetingSummaryView(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def load_translations(self, language):
#         try:
#             file_name = f"{language}_translations.json"
#             file_path = os.path.join(settings.BASE_DIR, file_name)
#             with open(file_path, 'r', encoding='utf-8') as f:
#                 return json.load(f)
#         except Exception:
#             return {'labour': {}}
#
#     def translate_text(self, text, translation_map, key='labour'):
#         return translation_map.get(key, {}).get(text, text)
#
#     def calculate_summary(self, budgets):
#         total_labour_cost = Decimal(0)
#         total_machine_cost = Decimal(0)
#         total_input_cost = Decimal(0)
#         total_miscellaneous = Decimal(0)
#
#         for budget in budgets:
#             # Labour
#             labour = budget.labour_estimation
#             try:
#                 male = Decimal(labour.get('male_labour_cost', 0)) * int(labour.get('male_labour_count', 0)) * int(labour.get('male_hours', 0))
#                 female = Decimal(labour.get('female_labour_cost', 0)) * int(labour.get('female_labour_count', 0)) * int(labour.get('female_hours', 0))
#                 total_labour_cost += male + female
#             except Exception:
#                 pass
#
#             # Machine
#             machine = budget.machine_estimation
#             try:
#                 mc = Decimal(machine.get('machine_count', 0))
#                 hrs = Decimal(machine.get('working_hours', 0))
#                 rate = Decimal(machine.get('rate_per_hour', 0))
#                 total_machine_cost += mc * rate * hrs
#             except Exception:
#                 pass
#
#             # Input
#             input_data = budget.input_estimation
#             try:
#                 qty = Decimal(input_data.get('input_quantity', 0))
#                 cost = Decimal(input_data.get('input_cost', 0))
#                 total_input_cost += qty * cost
#             except Exception:
#                 pass
#
#             # Miscellaneous
#             try:
#                 total_miscellaneous += Decimal(budget.miscellaneous or 0)
#             except Exception:
#                 pass
#
#         total = total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous
#
#         return {
#             "total_labour_cost": str(total_labour_cost),
#             "total_machine_cost": str(total_machine_cost),
#             "total_input_cost": str(total_input_cost),
#             "total_miscellaneous": str(total_miscellaneous),
#             "total_budget_cost": str(total)
#         }
#
#     def get(self, request, *args, **kwargs):
#         crop_plan_row_id = request.query_params.get('crop_plan_row_id')
#         zone_id = request.query_params.get('zone_id')
#         crop_id = request.query_params.get('crop_id')
#         language = request.query_params.get('language', 'en')
#
#         try:
#             budgets = Budgeting.objects.all()
#
#             if crop_plan_row_id:
#                 budgets = budgets.filter(crop_plan_row__id=crop_plan_row_id)
#             if zone_id:
#                 budgets = budgets.filter(zone__id=zone_id)
#             if crop_id:
#                 budgets = budgets.filter(crop__id=crop_id)
#
#             if not budgets.exists():
#                 return JsonResponse({'error': 'No data found for given filters.'}, status=404)
#
#             translations = self.load_translations(language)
#             row_summaries = []
#
#             # Initialize totals
#             total_labour_cost = Decimal(0)
#             total_machine_cost = Decimal(0)
#             total_input_cost = Decimal(0)
#             total_miscellaneous = Decimal(0)
#
#             for budget in budgets:
#                 summary = self.calculate_summary([budget])  # calculate for a single row
#                 row_summary = {
#                     'crop_plan_row_id': budget.crop_plan_row.id,
#                     'stage': budget.crop_plan_row.stage,
#                     'date': budget.crop_plan_row.date.strftime("%Y-%m-%d"),
#                     'zone_id': budget.zone.id if budget.zone else None,
#                     'crop_id': budget.crop.id if budget.crop else None,
#                     'total_labour_cost': summary['total_labour_cost'],
#                     'total_machine_cost': summary['total_machine_cost'],
#                     'total_input_cost': summary['total_input_cost'],
#                     'total_miscellaneous': summary['total_miscellaneous'],
#                     'total_budget_cost': summary['total_budget_cost'],
#                 }
#                 row_summaries.append(row_summary)
#
#                 # Add to totals
#                 total_labour_cost += Decimal(summary['total_labour_cost'])
#                 total_machine_cost += Decimal(summary['total_machine_cost'])
#                 total_input_cost += Decimal(summary['total_input_cost'])
#                 total_miscellaneous += Decimal(summary['total_miscellaneous'])
#
#             total_budget_cost = (
#                     total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous
#             )
#
#             # Final summary
#             total_summary = {
#                 'total_labour_cost': str(total_labour_cost),
#                 'total_machine_cost': str(total_machine_cost),
#                 'total_input_cost': str(total_input_cost),
#                 'total_miscellaneous': str(total_miscellaneous),
#                 'total_budget_cost': str(total_budget_cost)
#             }
#
#             # Optionally translate fields
#             for key in total_summary:
#                 total_summary[key] = self.translate_text(total_summary[key], translations, key='labour')
#
#             return JsonResponse({
#                 "rows": row_summaries,
#                 "total_summary": total_summary
#             })
#
#         except Exception as e:
#             return JsonResponse({'error': str(e)}, status=500)

class BudgetingSummaryView(APIView):
    permission_classes = [IsAuthenticated]

    def load_translations(self, language):
        try:
            file_name = f"{language}_translations.json"
            file_path = os.path.join(settings.BASE_DIR, file_name)
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception:
            return {'labour': {}}

    def translate_text(self, text, translation_map, key='labour'):
        return translation_map.get(key, {}).get(text, text)

    def calculate_summary(self, budgets):
        total_labour_cost = Decimal(0)
        total_machine_cost = Decimal(0)
        total_input_cost = Decimal(0)
        total_miscellaneous = Decimal(0)

        for budget in budgets:
            # Labour
            try:
                labour = budget.labour_estimation
                male = Decimal(labour.get('male_labour_cost', 0)) * int(labour.get('male_labour_count', 0)) * int(labour.get('male_hours', 0))
                female = Decimal(labour.get('female_labour_cost', 0)) * int(labour.get('female_labour_count', 0)) * int(labour.get('female_hours', 0))
                total_labour_cost += male + female
            except Exception:
                pass

            # Machine
            try:
                machine = budget.machine_estimation
                mc = Decimal(machine.get('machine_count', 0))
                hrs = Decimal(machine.get('working_hours', 0))
                rate = Decimal(machine.get('rate_per_hour', 0))
                total_machine_cost += mc * rate * hrs
            except Exception:
                pass

            # Input
            try:
                input_data = budget.input_estimation
                qty = Decimal(input_data.get('input_quantity', 0))
                cost = Decimal(input_data.get('input_cost', 0))
                total_input_cost += qty * cost
            except Exception:
                pass

            # Miscellaneous
            try:
                total_miscellaneous += Decimal(budget.miscellaneous or 0)
            except Exception:
                pass

        total = total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous

        return {
            "total_labour_cost": str(total_labour_cost),
            "total_machine_cost": str(total_machine_cost),
            "total_input_cost": str(total_input_cost),
            "total_miscellaneous": str(total_miscellaneous),
            "total_budget_cost": str(total)
        }

    def get(self, request, *args, **kwargs):
        row_number = request.query_params.get('row_number')
        zone_id = request.query_params.get('zone_id')
        crop_id = request.query_params.get('crop_id')
        language = request.query_params.get('language', 'en')

        try:
            budgets = Budgeting.objects.all()

            # ✅ Convert row_number to crop_plan_row if provided
            if row_number:
                try:
                    row_index = int(row_number) - 1
                    crop_plan_row = CropPlanRow.objects.all().order_by('id')[row_index]
                    budgets = budgets.filter(crop_plan_row=crop_plan_row)
                except (IndexError, ValueError):
                    return JsonResponse({'error': 'Invalid row_number'}, status=400)

            if zone_id:
                budgets = budgets.filter(zone__id=zone_id)
            if crop_id:
                budgets = budgets.filter(crop__id=crop_id)

            if not budgets.exists():
                return JsonResponse({'error': 'No data found for given filters.'}, status=404)

            translations = self.load_translations(language)
            row_summaries = []

            # ✅ Use the same filtering logic for CropPlanRow as used in BudgetingView
            crop_plan_row_qs = CropPlanRow.objects.filter(
                user_crop_plan__zone_id=zone_id,
                user_crop_plan__crop_id=crop_id
            ).order_by('id')
            all_rows = list(crop_plan_row_qs.values_list('id', flat=True))

            total_labour_cost = Decimal(0)
            total_machine_cost = Decimal(0)
            total_input_cost = Decimal(0)
            total_miscellaneous = Decimal(0)

            for budget in budgets:
                summary = self.calculate_summary([budget])

                try:
                    row_number = all_rows.index(budget.crop_plan_row.id) + 1
                except ValueError:
                    row_number = None

                row_summary = {
                    'row_number': row_number,
                    'stage': budget.crop_plan_row.stage,
                    'date': budget.crop_plan_row.date.strftime("%Y-%m-%d"),
                    'zone_id': budget.zone.id if budget.zone else None,
                    'crop_id': budget.crop.id if budget.crop else None,
                    'total_labour_cost': summary['total_labour_cost'],
                    'total_machine_cost': summary['total_machine_cost'],
                    'total_input_cost': summary['total_input_cost'],
                    'total_miscellaneous': summary['total_miscellaneous'],
                    'total_budget_cost': summary['total_budget_cost'],
                }
                row_summaries.append(row_summary)

                total_labour_cost += Decimal(summary['total_labour_cost'])
                total_machine_cost += Decimal(summary['total_machine_cost'])
                total_input_cost += Decimal(summary['total_input_cost'])
                total_miscellaneous += Decimal(summary['total_miscellaneous'])

            total_budget_cost = total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous

            total_summary = {
                'total_labour_cost': str(total_labour_cost),
                'total_machine_cost': str(total_machine_cost),
                'total_input_cost': str(total_input_cost),
                'total_miscellaneous': str(total_miscellaneous),
                'total_budget_cost': str(total_budget_cost)
            }

            for key in total_summary:
                total_summary[key] = self.translate_text(total_summary[key], translations, key='labour')

            return JsonResponse({
                "rows": row_summaries,
                "total_summary": total_summary
            })

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)


class MachineTypeListCreateView(generics.ListCreateAPIView):
    queryset = MachineType.objects.all()
    serializer_class = MachineTypeSerializer

# Machine Brand Views
class MachineBrandListCreateView(generics.ListCreateAPIView):
    queryset = MachineBrand.objects.all()
    serializer_class = MachineBrandSerializer
# class BudgetingSummaryViewSupervisor(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def calculate_summary(self, budgets):
#         total_labour_cost = Decimal(0)
#         total_machine_cost = Decimal(0)
#         total_input_cost = Decimal(0)
#         total_miscellaneous = Decimal(0)
#
#         for budget in budgets:
#             # Labour
#             labour = budget.labour_estimation
#             try:
#                 male = Decimal(labour.get('male_labour_cost', 0)) * int(labour.get('male_labour_count', 0)) * int(labour.get('male_hours', 0))
#                 female = Decimal(labour.get('female_labour_cost', 0)) * int(labour.get('female_labour_count', 0)) * int(labour.get('female_hours', 0))
#                 total_labour_cost += male + female
#             except Exception:
#                 pass
#
#             # Machine
#             machine = budget.machine_estimation
#             try:
#                 mc = Decimal(machine.get('machine_count', 0))
#                 hrs = Decimal(machine.get('working_hours', 0))
#                 rate = Decimal(machine.get('rate_per_hour', 0))
#                 total_machine_cost += mc * rate * hrs
#             except Exception:
#                 pass
#
#             # Input
#             input_data = budget.input_estimation
#             try:
#                 qty = Decimal(input_data.get('input_quantity', 0))
#                 cost = Decimal(input_data.get('input_cost', 0))
#                 total_input_cost += qty * cost
#             except Exception:
#                 pass
#
#             # Miscellaneous
#             try:
#                 total_miscellaneous += Decimal(budget.miscellaneous or 0)
#             except Exception:
#                 pass
#
#         total = total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous
#
#         return {
#             "total_budget_cost": str(total)
#         }
#
#     def get(self, request, *args, **kwargs):
#         try:
#             crop_plan_row_id = request.query_params.get('crop_plan_row_id')
#
#             if crop_plan_row_id:
#                 crop_plan_rows = CropPlanRow.objects.filter(id=crop_plan_row_id)
#             else:
#                 crop_plan_rows = CropPlanRow.objects.all()
#
#             row_summaries = []
#             overall_total = Decimal(0)
#
#             for row in crop_plan_rows:
#                 budgets = Budgeting.objects.filter(crop_plan_row=row)
#                 if budgets.exists():
#                     summary = self.calculate_summary(budgets)
#                     total_budget_cost = Decimal(summary.get('total_budget_cost', '0') or '0')
#                 else:
#                     total_budget_cost = Decimal('0')
#
#                 overall_total += total_budget_cost
#
#                 row_summaries.append({
#                     'crop_plan_row_id': row.id,
#                     'total_budget_cost': str(total_budget_cost)
#                 })
#
#             return JsonResponse({
#                 "rows": row_summaries,
#                 "overall_total_budget_cost": str(overall_total)
#             })
#
#         except Exception as e:
#             return JsonResponse({'error': str(e)}, status=500)

class BudgetingSummaryViewSupervisor(APIView):
    permission_classes = [IsAuthenticated]

    def calculate_summary(self, budgets):
        total_labour_cost = Decimal(0)
        total_machine_cost = Decimal(0)
        total_input_cost = Decimal(0)
        total_miscellaneous = Decimal(0)

        for budget in budgets:
            # Labour
            labour = budget.labour_estimation
            try:
                male = Decimal(labour.get('male_labour_cost', 0)) * int(labour.get('male_labour_count', 0)) * int(labour.get('male_hours', 0))
                female = Decimal(labour.get('female_labour_cost', 0)) * int(labour.get('female_labour_count', 0)) * int(labour.get('female_hours', 0))
                total_labour_cost += male + female
            except Exception:
                pass

            # Machine
            machine = budget.machine_estimation
            try:
                mc = Decimal(machine.get('machine_count', 0))
                hrs = Decimal(machine.get('working_hours', 0))
                rate = Decimal(machine.get('rate_per_hour', 0))
                total_machine_cost += mc * rate * hrs
            except Exception:
                pass

            # Input
            input_data = budget.input_estimation
            try:
                qty = Decimal(input_data.get('input_quantity', 0))
                cost = Decimal(input_data.get('input_cost', 0))
                total_input_cost += qty * cost
            except Exception:
                pass

            # Miscellaneous
            try:
                total_miscellaneous += Decimal(budget.miscellaneous or 0)
            except Exception:
                pass

        total = total_labour_cost + total_machine_cost + total_input_cost + total_miscellaneous

        return {
            "total_budget_cost": str(total)
        }

    def get(self, request, *args, **kwargs):
        try:
            row_number = request.query_params.get('row_number')
            zone_id = request.query_params.get('zone_id')
            crop_id = request.query_params.get('crop_id')

            if not (zone_id and crop_id):
                return JsonResponse({'error': 'zone_id and crop_id are required'}, status=400)

            # ✅ Filter CropPlanRow by zone and crop
            crop_plan_rows_qs = CropPlanRow.objects.filter(
                user_crop_plan__zone_id=zone_id,
                user_crop_plan__crop_id=crop_id
            ).order_by('id')

            if not crop_plan_rows_qs.exists():
                return JsonResponse({'error': 'No CropPlanRows found for this zone and crop'}, status=404)

            crop_plan_rows = list(crop_plan_rows_qs)

            # ✅ If row_number provided, limit to that row
            if row_number:
                try:
                    index = int(row_number) - 1
                    if index < 0 or index >= len(crop_plan_rows):
                        return JsonResponse({'error': 'Invalid row_number for given crop and zone'}, status=400)
                    crop_plan_rows = [crop_plan_rows[index]]
                except ValueError:
                    return JsonResponse({'error': 'row_number must be an integer'}, status=400)

            row_summaries = []
            overall_total = Decimal(0)

            for idx, row in enumerate(crop_plan_rows_qs, start=1):
                if row not in crop_plan_rows:
                    continue

                budgets = Budgeting.objects.filter(crop_plan_row=row)
                if budgets.exists():
                    summary = self.calculate_summary(budgets)
                    total_budget_cost = Decimal(summary.get('total_budget_cost', '0') or '0')
                else:
                    total_budget_cost = Decimal('0')

                overall_total += total_budget_cost

                row_summaries.append({
                    'row_number': idx,
                    'total_budget_cost': str(total_budget_cost)
                })

            return JsonResponse({
                "rows": row_summaries,
                "overall_total_budget_cost": str(overall_total)
            })

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)