# ============================================================
# ADDITIVE: Company / HR REST API - payroll, attendance,
# check-in list, finance (Client/Expense/Invoice), Target,
# DailyTask and bank-account management.
#
# Ported from the legacy MVT project's Company/views.py; every
# endpoint here is new and reuses existing serializers/models -
# nothing in Company/views.py or urls.py is touched.
#
# All endpoints require an Admin-or-HR JWT (the same
# AdminOrEmployeeJWTAuthentication / IsAdminOrHR pair already
# used by EmployeeViewSet / EmployeeRoleViewSet / HolidayViewSet)
# unless stated otherwise, and are company-isolated via
# resolve_company_for_user().
# ============================================================

from datetime import date, datetime

from django.db.models import Q
from django.http import Http404, HttpResponse
from django.utils import timezone
from django.shortcuts import get_object_or_404

from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework import status as http_status
from rest_framework.exceptions import PermissionDenied

from Employee.employee_crud_permissions import (
    AdminOrEmployeeJWTAuthentication,
    IsAdminOrHR,
    actor_label,
    get_employee_for_actor,
    resolve_company_for_user,
)

from .hr_api_views import employee_brief, employee_map

from .models import (
    company_details,
    Client,
    Expense,
    Invoice,
    BankTransaction,
    ProfitLoss,
)
from .serializers import (
    ClientSerializer,
    ExpenseSerializer,
    InvoiceSerializer,
    BankTransactionSerializer,
    ProfitLossSerializer,
)

from .utils_payroll_export import (
    calculate_salary,
    generate_monthly_payroll,
    is_not_future_month,
    last_month_year,
    monthly_profit_loss,
    yearly_profit_loss,
    invoice_summary,
    render_salary_slip_pdf,
    render_invoice_pdf,
    employees_excel_response,
    monthly_attendance_excel_response,
    attendance_payroll_excel_response,
)


# ============================================================
# SHARED MIXIN: company resolution + Admin-or-HR auth
# ============================================================

class AdminOrHRAPIView(APIView):

    authentication_classes = [AdminOrEmployeeJWTAuthentication]
    permission_classes = [IsAdminOrHR]

    def get_company(self, request):

        company = resolve_company_for_user(request.user)

        if company is None:
            raise PermissionDenied(
                "Unable to resolve your company. Access denied."
            )

        return company


class AdminOrHRModelViewSet(ModelViewSet):
    """Company-isolated CRUD base for the Client/Expense/Invoice/etc ViewSets below."""

    authentication_classes = [AdminOrEmployeeJWTAuthentication]
    permission_classes = [IsAdminOrHR]

    # Fields the server fills in itself (via perform_create/update)
    # rather than requiring the client to send them. Subclasses can
    # extend this list (see TargetViewSet).
    server_set_fields = ["company"]

    def get_serializer(self, *args, **kwargs):

        serializer = super().get_serializer(*args, **kwargs)

        for field_name in self.server_set_fields:

            field = serializer.fields.get(field_name)

            if field is not None:
                field.required = False

        return serializer

    def get_company(self):

        company = resolve_company_for_user(self.request.user)

        if company is None:
            raise PermissionDenied(
                "Unable to resolve your company. Access denied."
            )

        return company

    def perform_create(self, serializer):
        serializer.save(company=self.get_company())

    def perform_update(self, serializer):
        serializer.save(company=self.get_company())


def with_employee_info(rows, company, request, code_key="Employee_ID"):
    """Attach an `employee` info block to serialized rows (1 query)."""

    rows = list(rows)

    emp_map = employee_map(company, [r.get(code_key) for r in rows])

    return [
        {**r, "employee": employee_brief(emp_map.get(r.get(code_key)), request)}
        for r in rows
    ]




# ============================================================
# PAYROLL: GENERATE
# ============================================================

class PayrollGenerateView(AdminOrHRAPIView):
    """
    POST /api/payroll/generate/
    body: { "month": 8, "year": 2026 }

    Generates/updates payroll for every employee of the caller's
    company for (month, year). Future months are rejected -
    "Paid" rows are never touched (same rule as the legacy view).
    """

    permission_module = "payroll"


    def post(self, request):

        try:

            company = self.get_company(request)

            month = int(request.data.get("month"))
            year = int(request.data.get("year"))

            if not is_not_future_month(month, year):

                return Response({
                    "status": "error",
                    "code": "future_month",
                    "message": "You can generate payroll only for the current or past months.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            from Employee.serializers import PayrollSerializer

            entries = generate_monthly_payroll(month, year, company)

            return Response({
                "status": "success",
                "code": "payroll_generated",
                "message": f"Payroll generated for {month}/{year}.",
                "data": with_employee_info(
                    PayrollSerializer(entries, many=True).data, company, request
                ),
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except (TypeError, ValueError):

            return Response({
                "status": "error", "code": "invalid_input",
                "message": "month and year are required integers.",
                "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not generate payroll: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# PAYROLL: LIST (+ optional excel export)
# ============================================================

class PayrollListView(AdminOrHRAPIView):
    """
    GET /api/payroll/?month=8&year=2026
    GET /api/payroll/?month=8&year=2026&export=excel

    Defaults to last month when month/year are not given.
    Optional filters: ?status=Paid|Unpaid&employee_id=<code>
    """

    permission_module = "payroll"


    def get(self, request):

        try:

            from Employee.models import Payroll
            from Employee.serializers import PayrollSerializer

            company = self.get_company(request)

            month = request.query_params.get("month")
            year = request.query_params.get("year")

            if not month or not year:
                month, year = last_month_year()

            month = int(month)
            year = int(year)

            payroll_qs = Payroll.objects.filter(
                company=company, month=month, year=year
            )

            status_filter = request.query_params.get("status")
            if status_filter:
                payroll_qs = payroll_qs.filter(status=status_filter)

            employee_id = request.query_params.get("employee_id")
            if employee_id:
                payroll_qs = payroll_qs.filter(Employee_ID=employee_id)

            if request.query_params.get("export", "").lower() == "excel":
                return attendance_payroll_excel_response(company, month, year)

            return Response({
                "status": "success",
                "code": "payroll_list",
                "message": "Payroll fetched successfully.",
                "data": {
                    "month": month,
                    "year": year,
                    "payrolls": with_employee_info(
                        PayrollSerializer(payroll_qs, many=True).data,
                        company,
                        request,
                    ),
                },
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not fetch payroll: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# PAYROLL: SALARY SLIP PDF DOWNLOAD
# ============================================================

class PayrollSlipPDFView(APIView):
    """
    GET /api/payroll/<employee_id>/<month>/<year>/slip/

    Admin/HR can download any employee's slip in their company.
    An employee can download only their OWN slip.
    """

    def get_authenticators(self):
        from Employee.employee_crud_permissions import AdminOrEmployeeJWTAuthentication as _Auth
        return [_Auth()]

    def get_permissions(self):
        return []  # manual check below - two different actor types allowed

    def get(self, request, employee_id, month, year):

        try:

            from Employee.models import EmployeeDT, Payroll

            employee = get_employee_for_actor(
                request.user, employee_id, "payroll", "view"
            )

            payroll = get_object_or_404(
                Payroll,
                company=employee.company,
                Employee_ID=employee.employee_code,
                month=month,
                year=year,
            )

            return render_salary_slip_pdf(employee, payroll)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Http404:

            return Response({
                "status": "error", "code": "not_found",
                "message": "Salary slip not found.", "data": None,
            }, status=http_status.HTTP_404_NOT_FOUND)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not generate salary slip: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# PAYROLL: MARK PAID / UNPAID + PAYMENT DETAILS
# ============================================================

class PayrollPaymentUpdateView(AdminOrHRAPIView):
    """
    PATCH /api/payroll/<pk>/payment/

    body:
        {
            "action": "mark_paid" | "mark_unpaid",
            "payment_method": "BANK" | "UPI" | "CASH" | "CHEQUE" | "WALLET",
            "amount_paid": "25000.00",
            "payment_date": "2026-09-05",
            "bank_account_id": 3,          # optional, from employee.bank_accounts
            "upi_id": "name@upi",          # optional, manual UPI
            "reference": {...}             # optional extra meta, merged into payment_account_json
        }
    """

    permission_module = "payroll"


    def patch(self, request, pk):

        try:

            from Employee.models import Payroll, BankAccount
            from Employee.serializers import PayrollSerializer

            company = self.get_company(request)
            payroll = get_object_or_404(Payroll, pk=pk, company=company)

            action = request.data.get("action")
            method = request.data.get("payment_method") or payroll.payment_method

            if action == "mark_unpaid":

                payroll.status = "Unpaid"
                payroll.amount_paid = None
                payroll.payment_date = None
                payroll.upi_id = None
                payroll.upi_txn_id = None
                payroll.payment_account_json = None
                payroll.save()

                return Response({
                    "status": "success", "code": "payroll_marked_unpaid",
                    "message": "Payroll marked as unpaid.",
                    "data": PayrollSerializer(payroll).data,
                }, status=http_status.HTTP_200_OK)

            meta = dict(request.data.get("reference") or {})

            bank_account_id = request.data.get("bank_account_id")
            if bank_account_id and method in ("BANK", "CHEQUE"):

                acc = BankAccount.objects.filter(
                    id=bank_account_id, active=True
                ).first()

                if acc:
                    meta.update({
                        "bank_name": acc.bank_name,
                        "account_number": acc.account_number,
                        "ifsc_code": acc.ifsc_code,
                    })

            if method == "UPI":
                payroll.upi_id = request.data.get("upi_id") or payroll.upi_id
                payroll.upi_txn_id = request.data.get("upi_txn_id") or payroll.upi_txn_id

            payroll.payment_method = method
            payroll.payment_account_json = meta or None
            payroll.amount_paid = (
                request.data.get("amount_paid")
                or payroll.amount_paid
                or payroll.net_salary
            )
            payroll.payment_date = request.data.get("payment_date") or payroll.payment_date
            payroll.status = "Paid"
            payroll.save()

            return Response({
                "status": "success", "code": "payroll_marked_paid",
                "message": "Payroll marked as paid.",
                "data": PayrollSerializer(payroll).data,
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not update payroll payment: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ATTENDANCE: LIST + STATUS UPDATE
# ============================================================

ATTENDANCE_STATUSES = {
    "Present",
    "Absent",
    "Half Day",
    "Holiday",
    "Paid Leave",
    "Sick Leave",
    "Casual Leave",
    "Off",
}


def _parse_date(value, field_name):
    """YYYY-MM-DD -> date, or ValueError with a friendly message."""

    try:
        return datetime.strptime(str(value).strip(), "%Y-%m-%d").date()
    except (TypeError, ValueError):
        raise ValueError(f"{field_name} must be a date in YYYY-MM-DD format.")


class AttendanceListView(AdminOrHRAPIView):
    """
    Attendance list + manual update (module "attendance").

    GET /api/attendance/?employee_id=&status=&start_date=&end_date=
        (each row also carries an `employee` info block)

    PATCH /api/attendance/          -> can_edit_attendance
    body: { "attendance_id": 55, "status": "Present",
            "comment": "Forgot to check in",        # optional
            "total_working_hours": "08:30" }        # optional

    POST /api/attendance/           -> can_create_attendance
    body: { "employee_id": "7518A82C", "date": "2026-09-28",
            "status": "Present", "comment": "...",   # comment optional
            "total_working_hours": "08:00" }         # optional
    (one row per employee per date; use PATCH to change it)
    """

    permission_module = "attendance"

    def get(self, request):

        try:

            from Employee.models import AttendanceEmp
            from Employee.serializers import AttendanceEmpSerializer

            company = self.get_company(request)

            qs = AttendanceEmp.objects.filter(company=company)

            employee_id = request.query_params.get("employee_id")
            if employee_id:
                qs = qs.filter(Employee_ID__icontains=employee_id)

            att_status = request.query_params.get("status")
            if att_status:
                qs = qs.filter(status=att_status)

            start_date = request.query_params.get("start_date")
            if start_date:
                qs = qs.filter(date__gte=_parse_date(start_date, "start_date"))

            end_date = request.query_params.get("end_date")
            if end_date:
                qs = qs.filter(date__lte=_parse_date(end_date, "end_date"))

            qs = list(qs.order_by("-date", "-id")[:500])

            emp_map = employee_map(company, [r.Employee_ID for r in qs])

            rows = [
                {
                    **row,
                    "employee": employee_brief(
                        emp_map.get(row.get("Employee_ID")), request
                    ),
                }
                for row in AttendanceEmpSerializer(qs, many=True).data
            ]

            return Response({
                "status": "success",
                "code": "attendance_list",
                "message": "Attendance fetched successfully.",
                "data": rows,
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except ValueError as exc:

            return Response({
                "status": "error", "code": "invalid_input",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not fetch attendance: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

    def patch(self, request):

        try:

            from Employee.models import AttendanceEmp
            from Employee.serializers import AttendanceEmpSerializer

            company = self.get_company(request)

            attendance_id = request.data.get("attendance_id")

            if not attendance_id:
                return Response({
                    "status": "error", "code": "invalid_input",
                    "message": "attendance_id is required.", "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            record = get_object_or_404(
                AttendanceEmp,
                id=attendance_id,
                company=company,
            )

            if "status" in request.data:

                new_status = request.data.get("status")

                if new_status not in ATTENDANCE_STATUSES:
                    return Response({
                        "status": "error", "code": "invalid_status",
                        "message": "status must be one of: "
                                   + ", ".join(sorted(ATTENDANCE_STATUSES)),
                        "data": None,
                    }, status=http_status.HTTP_400_BAD_REQUEST)

                record.status = new_status

            if "comment" in request.data:
                record.comment = (request.data.get("comment") or "")[:200] or None

            if "total_working_hours" in request.data:
                record.total_working_hours = (
                    request.data.get("total_working_hours") or None
                )

            record.updated_by = actor_label(request.user)
            record.id_version = (record.id_version or 1) + 1
            record.save()

            return Response({
                "status": "success",
                "code": "attendance_updated",
                "message": "Attendance updated.",
                "data": AttendanceEmpSerializer(record).data,
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Http404:

            return Response({
                "status": "error", "code": "not_found",
                "message": "Attendance record not found.", "data": None,
            }, status=http_status.HTTP_404_NOT_FOUND)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not update attendance: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request):

        try:

            from Employee.models import AttendanceEmp, EmployeeDT
            from Employee.serializers import AttendanceEmpSerializer

            company = self.get_company(request)

            employee_code = (request.data.get("employee_id") or "").strip()
            new_status = request.data.get("status")

            if not employee_code or not request.data.get("date") or not new_status:
                return Response({
                    "status": "error", "code": "invalid_input",
                    "message": "employee_id, date and status are required.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            if new_status not in ATTENDANCE_STATUSES:
                return Response({
                    "status": "error", "code": "invalid_status",
                    "message": "status must be one of: "
                               + ", ".join(sorted(ATTENDANCE_STATUSES)),
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            day = _parse_date(request.data.get("date"), "date")

            if day > timezone.localdate():
                return Response({
                    "status": "error", "code": "future_date",
                    "message": "Attendance cannot be added for a future date.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            employee = EmployeeDT.objects.filter(
                company=company, employee_code=employee_code
            ).first()

            if employee is None:
                return Response({
                    "status": "error", "code": "employee_not_found",
                    "message": "No employee with this employee_id in your company.",
                    "data": None,
                }, status=http_status.HTTP_404_NOT_FOUND)

            existing = AttendanceEmp.objects.filter(
                company=company, Employee_ID=employee_code, date=day
            ).first()

            if existing is not None:
                return Response({
                    "status": "error", "code": "attendance_exists",
                    "message": "Attendance already exists for this date. "
                               "Use PATCH with attendance_id to change it.",
                    "data": {"attendance_id": existing.pk},
                }, status=http_status.HTTP_409_CONFLICT)

            actor = actor_label(request.user)

            record = AttendanceEmp.objects.create(
                Employee_ID=employee_code,
                company=company,
                Name=employee.name,
                date=day,
                status=new_status,
                comment=(request.data.get("comment") or "")[:200] or None,
                total_working_hours=request.data.get("total_working_hours") or None,
                created_by=actor,
                updated_by=actor,
            )

            return Response({
                "status": "success",
                "code": "attendance_created",
                "message": "Attendance added.",
                "data": AttendanceEmpSerializer(record).data,
            }, status=http_status.HTTP_201_CREATED)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except ValueError as exc:

            return Response({
                "status": "error", "code": "invalid_input",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not add attendance: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ATTENDANCE: ONE EMPLOYEE'S MONTHLY CALENDAR
# ============================================================

class EmployeeAttendanceCalendarView(APIView):
    """
    GET /api/employees/<employee_id>/calendar/<year>/<month>/

    Per-day attendance status + check-in/out times for one
    employee's month. Admin/HR for anyone in their company, or
    the employee themself for their own calendar.
    """

    def get_authenticators(self):
        from Employee.employee_crud_permissions import AdminOrEmployeeJWTAuthentication as _Auth
        return [_Auth()]

    def get_permissions(self):
        return []

    def get(self, request, employee_id, year, month):

        try:

            from Employee.models import EmployeeDT, AttendanceEmp, EMP_check_in_check_out

            employee = get_employee_for_actor(
                request.user, employee_id, "attendance", "view"
            )

            year = int(year)
            month = int(month)

            attendance_qs = AttendanceEmp.objects.filter(
                company=employee.company,
                Employee_ID=employee.employee_code,
                date__year=year, date__month=month,
            )

            checkins = EMP_check_in_check_out.objects.filter(
                company=employee.company,
                Employee_ID=employee.employee_code,
                login_date__year=year, login_date__month=month,
            )
            checkin_map = {c.login_date.day: c for c in checkins}

            attendance_map = {}
            for att in attendance_qs:
                c = checkin_map.get(att.date.day)
                attendance_map[att.date.isoformat()] = {
                    "status": att.status,
                    "login_time": c.login_time if c else None,
                    "logout_time": c.logout_time if c else None,
                    "total_working_hours": att.total_working_hours,
                }

            return Response({
                "status": "success",
                "code": "attendance_calendar",
                "message": "Calendar fetched successfully.",
                "data": {
                    "employee_code": employee.employee_code,
                    "employee_name": employee.name,
                    "year": year,
                    "month": month,
                    "days": attendance_map,
                },
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Http404:

            return Response({
                "status": "error", "code": "not_found",
                "message": "Employee not found.", "data": None,
            }, status=http_status.HTTP_404_NOT_FOUND)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not fetch calendar: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# CHECK-IN / CHECK-OUT: RECENT LIST (Admin/HR)
# ============================================================

class CheckInOutListView(AdminOrHRAPIView):
    """
    Login history (module "attendance").

    GET /api/check-in-out/?employee_id=&start_date=&end_date=&limit=

    Latest check-in/out records for the company (default 50, max
    500), newest first. Every row carries an `employee` info block.
    """

    permission_module = "attendance"

    def get(self, request):

        try:

            from Employee.models import EMP_check_in_check_out
            from Employee.serializers import EmployeeCheckInOutSerializer

            company = self.get_company(request)

            qs = EMP_check_in_check_out.objects.filter(company=company)

            employee_id = request.query_params.get("employee_id")
            if employee_id:
                qs = qs.filter(Employee_ID=employee_id.strip())

            start_date = request.query_params.get("start_date")
            if start_date:
                qs = qs.filter(login_date__gte=_parse_date(start_date, "start_date"))

            end_date = request.query_params.get("end_date")
            if end_date:
                qs = qs.filter(login_date__lte=_parse_date(end_date, "end_date"))

            try:
                limit = min(max(int(request.query_params.get("limit", 50)), 1), 500)
            except (TypeError, ValueError):
                limit = 50

            qs = list(qs.order_by("-login_date", "-id")[:limit])

            emp_map = employee_map(company, [r.Employee_ID for r in qs])

            rows = [
                {
                    **row,
                    "employee": employee_brief(
                        emp_map.get(row.get("Employee_ID")), request
                    ),
                }
                for row in EmployeeCheckInOutSerializer(qs, many=True).data
            ]

            return Response({
                "status": "success",
                "code": "check_in_out_list",
                "message": "Check-in/out list fetched successfully.",
                "data": rows,
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except ValueError as exc:

            return Response({
                "status": "error", "code": "invalid_input",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not fetch check-in/out list: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


class EmployeeLiveCheckInStatusListView(AdminOrHRAPIView):
    """
    GET /api/check-in-status/<status>/
    status: "checkin" (currently checked in, not out yet),
            "checkout" (not currently checked in),
            "all" (every employee, either state)

    Mirrors the legacy check_in_status(request, status) view -
    based on EmployeeDT.check_st (the LIVE flag), not on
    whether a check-in/out record merely touched today.
    """

    permission_module = "attendance"


    def get(self, request, status):

        try:

            from Employee.models import EmployeeDT
            from Employee.serializers import EmployeeCRUDSerializer

            company = self.get_company(request)

            qs = EmployeeDT.objects.filter(company=company)

            if status == "checkin":
                qs = qs.filter(check_st="check_in")
            elif status == "checkout":
                qs = qs.filter(check_st__isnull=True)
            # "all" (or anything else) -> no extra filter

            return Response({
                "status": "success",
                "code": "employee_check_in_status_list",
                "message": "Employee check-in status list fetched successfully.",
                "data": EmployeeCRUDSerializer(qs, many=True).data,
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not fetch check-in status list: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


class EmployeeCalendarDayDetailView(APIView):
    """
    GET /api/employees/<employee_id>/calendar/<year>/<month>/<day>/

    One specific day's check-in/out record for one employee,
    including the check-in/check-out image URLs (mirrors the
    legacy calendar_day_images view). Admin/HR for anyone in
    their company, or the employee themself for their own day.
    """

    def get_authenticators(self):
        from Employee.employee_crud_permissions import AdminOrEmployeeJWTAuthentication as _Auth
        return [_Auth()]

    def get_permissions(self):
        return []

    def get(self, request, employee_id, year, month, day):

        try:

            from Employee.models import EmployeeDT, EMP_check_in_check_out
            from Employee.serializers import EmployeeCheckInOutSerializer

            employee = get_employee_for_actor(
                request.user, employee_id, "attendance", "view"
            )

            record = EMP_check_in_check_out.objects.filter(
                company=employee.company,
                Employee_ID=employee.employee_code,
                login_date__year=year,
                login_date__month=month,
                login_date__day=day,
            ).order_by("-id").first()

            return Response({
                "status": "success",
                "code": "calendar_day_detail",
                "message": "Day detail fetched successfully.",
                "data": {
                    "employee_code": employee.employee_code,
                    "employee_name": employee.name,
                    "year": int(year),
                    "month": int(month),
                    "day": int(day),
                    "record": EmployeeCheckInOutSerializer(record).data if record else None,
                },
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Http404:

            return Response({
                "status": "error", "code": "not_found",
                "message": "Employee not found.", "data": None,
            }, status=http_status.HTTP_404_NOT_FOUND)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not fetch day detail: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# EXCEL EXPORTS
# ============================================================

class EmployeesExcelExportView(AdminOrHRAPIView):
    """GET /api/exports/employees/ - full active employee list as .xlsx."""

    def get(self, request):

        from Employee.models import EmployeeDT

        company = self.get_company(request)
        employees = EmployeeDT.objects.filter(company=company, is_active=True)

        return employees_excel_response(employees)


class EmployeeMonthlyAttendanceExcelExportView(AdminOrHRAPIView):
    """GET /api/exports/attendance/<employee_id>/?year=&month="""

    permission_module = "attendance"


    def get(self, request, employee_id):

        from Employee.models import EmployeeDT

        company = self.get_company(request)
        employee = get_object_or_404(EmployeeDT, employee_code=employee_id, company=company)

        today = datetime.today()
        year = int(request.query_params.get("year") or today.year)
        month = int(request.query_params.get("month") or today.month)

        return monthly_attendance_excel_response(employee, year, month)


class AttendancePayrollExcelExportView(AdminOrHRAPIView):
    """GET /api/exports/attendance-payroll/?month=&year="""

    permission_module = "payroll"


    def get(self, request):

        company = self.get_company(request)

        month = request.query_params.get("month")
        year = request.query_params.get("year")

        if not month or not year:
            month, year = last_month_year()

        return attendance_payroll_excel_response(company, month, year)


# ============================================================
# FINANCE SUMMARY (Profit/Loss + Invoice summary)
# ============================================================

class FinanceSummaryView(AdminOrHRAPIView):
    """GET /api/finance/summary/ - monthly/yearly P&L + invoice summary."""

    permission_module = "reports"


    def get(self, request):

        try:

            company = self.get_company(request)

            return Response({
                "status": "success",
                "code": "finance_summary",
                "message": "Finance summary fetched successfully.",
                "data": {
                    "monthly_profit_loss": monthly_profit_loss(company),
                    "yearly_profit_loss": yearly_profit_loss(company),
                    "invoice_summary": invoice_summary(company),
                },
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not fetch finance summary: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# CLIENT / EXPENSE / INVOICE - full CRUD
# ============================================================

class ClientViewSet(AdminOrHRModelViewSet):
    """/api/clients/ - full CRUD."""

    permission_module = "invoice"


    serializer_class = ClientSerializer

    def get_queryset(self):
        return Client.objects.filter(company=self.get_company())


class ExpenseViewSet(AdminOrHRModelViewSet):
    """/api/expenses/ - full CRUD."""

    permission_module = "expense"


    serializer_class = ExpenseSerializer

    def get_queryset(self):
        return Expense.objects.filter(company=self.get_company())


class InvoiceViewSet(AdminOrHRModelViewSet):
    """
    /api/invoices/ - full CRUD.
    Totals (GST/TDS/grand total) are computed automatically by
    Invoice.save() - see Company/models.py.
    """

    permission_module = "invoice"


    serializer_class = InvoiceSerializer

    def get_queryset(self):
        return Invoice.objects.filter(company=self.get_company())


class InvoicePDFView(AdminOrHRAPIView):
    """GET /api/invoices/<pk>/pdf/ - download the invoice as a PDF."""

    permission_module = "invoice"


    def get(self, request, pk):

        company = self.get_company(request)
        invoice = get_object_or_404(Invoice, pk=pk, company=company)

        return render_invoice_pdf(invoice)


# ============================================================
# BANK ACCOUNT: ADD / UPDATE for an employee (Admin/HR)
# ============================================================

class EmployeeBankAccountUpsertView(AdminOrHRAPIView):
    """
    POST /api/employees/<employee_id>/bank-account/
    Creates a new BankAccount for the employee, or updates their
    first active one if bank_account_id is given in the body.
    """

    permission_module = "bank"
    permission_write_action = "edit"


    def post(self, request, employee_id):

        try:

            from Employee.models import EmployeeDT, BankAccount
            from Employee.serializers import BankAccountSerializer

            company = self.get_company(request)
            employee = get_object_or_404(
                EmployeeDT, employee_code=employee_id, company=company
            )

            bank_account_id = request.data.get("bank_account_id")

            if bank_account_id:
                account = get_object_or_404(
                    BankAccount, id=bank_account_id, employee=employee
                )
                serializer = BankAccountSerializer(
                    account, data=request.data, partial=True
                )
            else:
                # employee is supplied via perform-save below, not
                # by the client, so treat it as partial here too.
                serializer = BankAccountSerializer(data=request.data, partial=True)

            if not serializer.is_valid():

                return Response({
                    "status": "error", "code": "validation_error",
                    "message": "Invalid bank account data.",
                    "data": serializer.errors,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            serializer.save(employee=employee)

            return Response({
                "status": "success",
                "code": "bank_account_saved",
                "message": "Bank account saved successfully.",
                "data": serializer.data,
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error", "code": "permission_denied",
                "message": str(exc), "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Exception as exc:

            return Response({
                "status": "error", "code": "server_error",
                "message": f"Could not save bank account: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# TARGET / DAILY TASK - full CRUD
# ============================================================

class TargetViewSet(AdminOrHRModelViewSet):
    """
    /api/targets/ - full CRUD.
    Optional filters: ?employee=<pk>&target_date=YYYY-MM-DD&status=completed|pending
    """

    server_set_fields = ["company", "create_date"]

    def get_serializer_class(self):
        from Employee.serializers import TargetSerializer
        return TargetSerializer

    def get_queryset(self):

        from Employee.models import Target

        qs = Target.objects.filter(company=self.get_company()).order_by("-target_date")

        employee_id = self.request.query_params.get("employee")
        if employee_id:
            qs = qs.filter(employee__id=employee_id)

        target_date = self.request.query_params.get("target_date")
        if target_date:
            qs = qs.filter(target_date=target_date)

        status_filter = self.request.query_params.get("status")
        if status_filter == "completed":
            qs = qs.filter(completed=True)
        elif status_filter == "pending":
            qs = qs.filter(completed=False)

        return qs

    def perform_create(self, serializer):
        serializer.save(company=self.get_company(), create_date=date.today())


class DailyTaskViewSet(AdminOrHRModelViewSet):
    """
    /api/daily-tasks/ - full CRUD.
    Optional filters: ?employee=<pk>&task_date=YYYY-MM-DD&status=completed|pending
    """

    def get_serializer_class(self):
        from Employee.serializers import DailyTaskSerializer
        return DailyTaskSerializer

    def get_queryset(self):

        from Employee.models import DailyTask

        qs = DailyTask.objects.filter(company=self.get_company()).order_by("-task_date")

        employee_id = self.request.query_params.get("employee")
        if employee_id:
            qs = qs.filter(employee__id=employee_id)

        task_date = self.request.query_params.get("task_date")
        if task_date:
            qs = qs.filter(task_date=task_date)

        status_filter = self.request.query_params.get("status")
        if status_filter == "completed":
            qs = qs.filter(completed=True)
        elif status_filter == "pending":
            qs = qs.filter(completed=False)

        return qs

    def perform_update(self, serializer):

        task = serializer.save(company=self.get_company())

        if task.completed and not task.completed_time:
            task.completed_time = timezone.localtime().time()
            task.save(update_fields=["completed_time"])
        elif not task.completed:
            task.completed_time = None
            task.save(update_fields=["completed_time"])
