from django.shortcuts import render

# Create your views here.

# ============================================================
# ADDITIVE: Employee login / logout + auth log list
# ============================================================

from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status as http_status
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.exceptions import TokenError

from .models import EmployeeDT, EmployeeAccount
from .serializers import EmployeeCheckInOutSerializer
from Company.models import AuthLog, log_auth_event, blacklist_token
from Company.serializers import AuthLogSerializer
from .employee_authentication import (
    EmployeeJWTAuthentication,
    IsEmployeeAuthenticated,
)


# ============================================================
# EMPLOYEE LOGIN
# ============================================================
# ============================================================
# EMPLOYEE LOGIN
# ============================================================

class EmployeeLoginView(APIView):
    """
    POST /employee/auth/login/

    body:
        {
            "email": "jdoe@example.com",
            "password": "xxxxxxxx"
        }

    Validates against EmployeeDT.email + EmployeeDT.password,
    issues a JWT (type="employee"), tracks
    failed_login_attempts / last_login on EmployeeAccount, and
    writes one AuthLog row per attempt.

    NOTE (additive fix): EmployeeAccount no longer has a
    `username` field (see employee_authentication.py comment -
    it was replaced by EmployeeDT.email). Login now looks up
    EmployeeDT by email, then reads the linked EmployeeAccount
    via employee.account for role / login-enabled / counters.
    """

    authentication_classes = []
    permission_classes = []

    def post(self, request):

        email = request.data.get("email")
        password = request.data.get("password")

        if not email or not password:

            log_auth_event(
                actor_type=AuthLog.ACTOR_EMPLOYEE,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                reason="Missing email or password",
            )

            return Response({
                "status": "error",
                "code": "missing_fields",
                "message": "Email and password are required.",
                "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        try:

            employee = EmployeeDT.objects.select_related(
                "company",
                "account",
                "account__role",
            ).get(email__iexact=email)

        except EmployeeDT.DoesNotExist:

            log_auth_event(
                actor_type=AuthLog.ACTOR_EMPLOYEE,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                reason="Employee not found",
            )

            return Response({
                "status": "error",
                "code": "invalid_credentials",
                "message": "Invalid email or password.",
                "data": None,
            }, status=http_status.HTTP_401_UNAUTHORIZED)

        account = getattr(employee, "account", None)
        company = employee.company

        if account is None:

            log_auth_event(
                actor_type=AuthLog.ACTOR_EMPLOYEE,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=employee.employee_code,
                company=company,
                reason="No login account linked to this employee",
            )

            return Response({
                "status": "error",
                "code": "account_not_found",
                "message": "No login account is set up for this employee.",
                "data": None,
            }, status=http_status.HTTP_401_UNAUTHORIZED)

        if not account.is_login_enabled:

            log_auth_event(
                actor_type=AuthLog.ACTOR_EMPLOYEE,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=employee.employee_code,
                company=company,
                reason="Login disabled for this account",
            )

            return Response({
                "status": "error",
                "code": "login_disabled",
                "message": "Login is disabled for this account.",
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        if employee.password != password:

            account.failed_login_attempts = (
                account.failed_login_attempts + 1
            )
            account.save(
                update_fields=["failed_login_attempts", "updated_at"]
            )

            log_auth_event(
                actor_type=AuthLog.ACTOR_EMPLOYEE,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=employee.employee_code,
                company=company,
                reason="Incorrect password",
            )

            return Response({
                "status": "error",
                "code": "invalid_credentials",
                "message": "Invalid email or password.",
                "data": None,
            }, status=http_status.HTTP_401_UNAUTHORIZED)

        if not employee.is_active:

            log_auth_event(
                actor_type=AuthLog.ACTOR_EMPLOYEE,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=employee.employee_code,
                company=company,
                reason="Employee inactive",
            )

            return Response({
                "status": "error",
                "code": "employee_disabled",
                "message": "Employee account is inactive.",
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        if not company or not company.status:

            log_auth_event(
                actor_type=AuthLog.ACTOR_EMPLOYEE,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=employee.employee_code,
                company=company,
                reason="Company inactive",
            )

            return Response({
                "status": "error",
                "code": "company_disabled",
                "message": "Company account is inactive.",
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        # ---- success: reset counters, stamp last_login ----
        account.failed_login_attempts = 0
        account.last_login = timezone.now()
        account.save(
            update_fields=["failed_login_attempts", "last_login", "updated_at"]
        )

        refresh = RefreshToken()
        refresh["type"] = "employee"
        refresh["user_id"] = employee.employee_code
        refresh["employee_id"] = employee.employee_code
        refresh["company_id"] = company.company_id
        refresh["role"] = account.role.role_code if account.role else None

        log_auth_event(
            actor_type=AuthLog.ACTOR_EMPLOYEE,
            action=AuthLog.ACTION_LOGIN,
            status=AuthLog.STATUS_SUCCESS,
            request=request,
            identifier=email,
            actor_id=employee.employee_code,
            company=company,
        )

        # ADDITIVE: HR-role employees land on the shared
        # Company/HR dashboard, everyone else on their own
        # employee dashboard.
        role_code = (account.role.role_code or "").strip().lower() if account.role else ""
        redirect_url = (
            "/company/dashboard/"
            if role_code in {"hr", "human_resource", "human_resources"}
            else "/employee/dashboard/"
        )

        return Response({
            "status": "success",
            "code": "login_success",
            "message": "Login successful.",
            "data": {
                "access": str(refresh.access_token),
                "refresh": str(refresh),
                "employee_code": employee.employee_code,
                "name": employee.name,
                "email": employee.email,
                "role": account.role.role_name if account.role else None,
                "company_id": company.company_id,
                "redirect_url": redirect_url,
            },
        }, status=http_status.HTTP_200_OK)
        
        
# ============================================================
# EMPLOYEE LOGOUT
# ============================================================
# ============================================================
# EMPLOYEE LOGOUT
# ============================================================

class EmployeeLogoutView(APIView):
    """
    POST /employee/auth/logout/

    body:
        { "refresh": "<refresh_token>" }

    Requires a valid employee access token. Blacklists the
    refresh token and logs the logout.
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def post(self, request):

        employee = request.user
        refresh_token = request.data.get("refresh")

        if not refresh_token:

            return Response({
                "status": "error",
                "code": "missing_refresh_token",
                "message": "Refresh token is required.",
                "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        try:

            token = RefreshToken(refresh_token)
            blacklist_token(token)

        except TokenError:
            pass

        log_auth_event(
            actor_type=AuthLog.ACTOR_EMPLOYEE,
            action=AuthLog.ACTION_LOGOUT,
            status=AuthLog.STATUS_SUCCESS,
            request=request,
            identifier=employee.email,
            actor_id=employee.employee_code,
            company=employee.company,
        )

        return Response({
            "status": "success",
            "code": "logout_success",
            "message": "Logged out successfully.",
            "data": None,
        }, status=http_status.HTTP_200_OK)
        
        
# ============================================================
# EMPLOYEE AUTH LOG LIST (own history)
# ============================================================

class EmployeeAuthLogListView(APIView):
    """
    GET /employee/auth/logs/

    Returns this employee's own login/logout history,
    newest first.
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        employee = request.user

        logs = AuthLog.objects.filter(
            actor_type=AuthLog.ACTOR_EMPLOYEE,
            actor_id=employee.employee_code,
        )[:200]

        serializer = AuthLogSerializer(logs, many=True)

        return Response({
            "status": "success",
            "code": "auth_logs",
            "message": "Auth logs fetched successfully.",
            "data": serializer.data,
        }, status=http_status.HTTP_200_OK)


# ============================================================
# ADDITIVE: EMPLOYEE CRUD API (Employee Management)
# ------------------------------------------------------------
# GET    /api/employees/
# GET    /api/employees/<id>/
# POST   /api/employees/
# PUT    /api/employees/<id>/
# PATCH  /api/employees/<id>/
# DELETE /api/employees/<id>/
#
# Auth: Company Admin token OR Employee(HR) token.
# Permission: IsAdminOrHR (plain Employee token -> 403).
# Isolation: queryset is ALWAYS scoped to the caller's own
# company - enforced in get_queryset(), never trusted from the
# request body/query params.
# ============================================================

from rest_framework.viewsets import ModelViewSet
from rest_framework.pagination import PageNumberPagination
from rest_framework.exceptions import PermissionDenied
from rest_framework.filters import SearchFilter, OrderingFilter

from .employee_crud_permissions import (
    AdminOrEmployeeJWTAuthentication,
    IsAdminOrHR,
    resolve_company_for_user,
)
from .serializers import EmployeeCRUDSerializer


class EmployeeCRUDPagination(PageNumberPagination):
    page_size = 20
    page_size_query_param = "page_size"
    max_page_size = 200


class EmployeeViewSet(ModelViewSet):
    """
    Employee Management CRUD.

    Reuses the existing EmployeeDT model (Employee/models.py) -
    no duplicate model is created.

    SEARCH / FILTER / SORT (all on the LIST endpoint, i.e.
    GET /api/employees/):

      ?search=<text>
          Free-text search across name, email, phone_number,
          employee_code, Department, Designation, Job_Title.
          e.g. GET /api/employees/?search=rahul
               GET /api/employees/?search=IT

      ?is_active=true|false
          Only active / only inactive employees.
          e.g. GET /api/employees/?is_active=true

      ?department=<exact text>
      ?designation=<exact text>
      ?employee_status=<exact text>   (maps to Employee_Status)
      ?employee_type=<exact text>     (maps to Employee_Type)
          Exact-match filters.
          e.g. GET /api/employees/?department=IT

      ?ordering=<field> or -<field>
          Sort results. Allowed fields: name, email,
          Date_of_Joining, created_at.
          e.g. GET /api/employees/?ordering=name
               GET /api/employees/?ordering=-Date_of_Joining

      All of the above can be combined and are ALWAYS applied on
      top of get_queryset(), so they can never widen results
      beyond the caller's own company.
    """

    serializer_class = EmployeeCRUDSerializer
    pagination_class = EmployeeCRUDPagination

    filter_backends = [SearchFilter, OrderingFilter]

    search_fields = [
        "name",
        "email",
        "phone_number",
        "employee_code",
        "Department",
        "Designation",
        "Job_Title",
        "candidate_id",
        "applied_position",
        "candidate_source",
        "recruiter_name",
        "candidate_status",
    ]

    ordering_fields = [
        "name",
        "email",
        "Date_of_Joining",
        "created_at",
    ]

    ordering = ["-created_at"]

    # Tries Company (Admin) auth first, then falls back to
    # Employee (HR) auth - see AdminOrEmployeeJWTAuthentication
    # for why a plain [CompanyJWTAuthentication,
    # EmployeeJWTAuthentication] list does not work here.
    authentication_classes = [AdminOrEmployeeJWTAuthentication]

    permission_classes = [IsAdminOrHR]

    def get_company(self):
        """
        Resolve the authenticated caller's own company.
        Never derived from request data - always from the
        authenticated user attached by the authentication class.
        """

        company = resolve_company_for_user(self.request.user)

        if company is None:
            # Should not normally happen once IsAdminOrHR has
            # passed, but fail safe rather than leak data.
            raise PermissionDenied(
                "Unable to resolve your company. Access denied."
            )

        return company

    def get_queryset(self):
        """
        HARD company-level isolation. Every list/retrieve/
        update/delete goes through this queryset, so an
        Admin/HR user can never see, edit or delete another
        company's employees - a mismatched <id> simply looks
        like it doesn't exist (404), never a leaked 403/other
        company's data.

        Exact-match query params (?is_active=, ?department=,
        ?designation=, ?employee_status=, ?employee_type=) are
        applied here, AFTER the company filter, so they can only
        ever narrow results - never escape the company scope.
        """

        qs = (
            EmployeeDT.objects
            .filter(company=self.get_company())
            .prefetch_related(
                "documents",
                "educational_history",
                "professional_experience",
                "bank_accounts",
            )
            .select_related(
                "compensation_package",
                "bgv",
            )
        )

        params = self.request.query_params

        is_active = params.get("is_active")
        if is_active is not None:
            qs = qs.filter(is_active=is_active.strip().lower() in ("1", "true", "yes"))

        department = params.get("department")
        if department:
            qs = qs.filter(Department__iexact=department)

        designation = params.get("designation")
        if designation:
            qs = qs.filter(Designation__iexact=designation)

        employee_status = params.get("employee_status")
        if employee_status:
            qs = qs.filter(Employee_Status__iexact=employee_status)

        employee_type = params.get("employee_type")
        if employee_type:
            qs = qs.filter(Employee_Type__iexact=employee_type)

        candidate_status = params.get("candidate_status")
        if candidate_status:
            qs = qs.filter(candidate_status__iexact=candidate_status)

        candidate_source = params.get("candidate_source")
        if candidate_source:
            qs = qs.filter(candidate_source__iexact=candidate_source)

        return qs

    def perform_create(self, serializer):
        """
        The `company` field is READ ONLY on the serializer and
        is stripped from incoming data in validate(); it is set
        here, straight from the authenticated user's own
        company. A client can never create an employee under a
        different company.
        """

        serializer.save(company=self.get_company())

    def perform_update(self, serializer):
        """
        get_object() (used internally before this is called)
        already applies get_queryset(), so by the time we get
        here the instance is guaranteed to belong to the
        caller's own company. We still pin `company` again here
        defensively, so an update can never move an employee to
        another company even if `company` slipped through.
        """

        serializer.save(company=self.get_company())

    # perform_destroy() needs no override: ModelViewSet.destroy()
    # calls get_object() -> get_queryset() first, so deleting an
    # employee outside the caller's own company already 404s
    # before any delete happens.


# ============================================================
# ADDITIVE: Employee Self-Service Dashboard
# ============================================================

class EmployeeDashboardView(APIView):
    """
    GET /employee/dashboard/

    The logged-in employee's own dashboard: today's check-in
    status, this month's attendance summary, this month's
    payroll (paid/unpaid) and company-wide context (headcount,
    this month's new joiners / birthdays / anniversaries).
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            from django.db.models import Sum
            from .models import EMP_check_in_check_out, AttendanceEmp, Payroll

            employee = request.user
            company = employee.company
            today = timezone.localdate()

            # ---------------- TODAY'S CHECK-IN STATUS ----------------
            todays_checkin = (
                EMP_check_in_check_out.objects
                .filter(Employee_ID=employee.employee_code, login_date=today)
                .order_by("-id")
                .first()
            )

            checked_in = bool(todays_checkin and todays_checkin.login_time)
            checked_out = bool(todays_checkin and todays_checkin.logout_time)

            # ---------------- THIS MONTH'S ATTENDANCE ----------------
            attendance_qs = AttendanceEmp.objects.filter(
                Employee_ID=employee.employee_code,
                date__year=today.year,
                date__month=today.month,
            )

            attendance_summary = {
                "present": attendance_qs.filter(status="Present").count(),
                "absent": attendance_qs.filter(status="Absent").count(),
                "half_day": attendance_qs.filter(status="Half Day").count(),
                "leave": attendance_qs.filter(
                    status__in=["Paid Leave", "Sick Leave", "Casual Leave"]
                ).count(),
            }

            # ---------------- THIS MONTH'S PAYROLL ----------------
            payroll_qs = Payroll.objects.filter(
                Employee_ID=employee.employee_code,
                month=today.month,
                year=today.year,
            )

            monthly_earning = payroll_qs.filter(status="Paid").aggregate(
                total=Sum("amount_paid")
            )["total"] or 0

            unpaid_earning = payroll_qs.filter(status="Unpaid").aggregate(
                total=Sum("net_salary")
            )["total"] or 0

            # ---------------- COMPANY-WIDE CONTEXT ----------------
            total_employees = 0
            new_joining = []
            birthdays_this_month = []
            work_anniversary = []
            holidays_this_month = []
            upcoming_holidays = []
            holidays_this_year = []
            all_holidays = []

            if company is not None:

                from Company.models import Holiday

                # Every active holiday of ALL years: manually added ones
                # (source="manual") + holiday-library imports
                # (source="automatic").
                all_holidays = list(
                    Holiday.objects.filter(
                        company=company,
                        is_active=True,
                    ).order_by("date").values(
                        "id", "name", "date", "holiday_type", "source"
                    )
                )

                holidays_this_year = [
                    h for h in all_holidays if h["date"].year == today.year
                ]

                holidays_this_month = [
                    h for h in holidays_this_year
                    if h["date"].month == today.month
                ]

                # Everything from today onwards, across years.
                upcoming_holidays = [
                    h for h in all_holidays if h["date"] >= today
                ]

                total_employees = EmployeeDT.objects.filter(
                    company=company,
                    Employee_Status__iexact="Activate",
                    is_active=True,
                ).count()

                new_joining = list(
                    EmployeeDT.objects.filter(
                        company=company,
                        Employee_Status__iexact="Activate",
                        is_active=True,
                        Date_of_Joining__year=today.year,
                        Date_of_Joining__month=today.month,
                    ).values("employee_code", "name", "Date_of_Joining")
                )

                birthdays_this_month = list(
                    EmployeeDT.objects.filter(
                        company=company,
                        Employee_Status__iexact="Activate",
                        is_active=True,
                        Date_of_Birth__month=today.month,
                    ).values("employee_code", "name", "Date_of_Birth")
                )

                work_anniversary = list(
                    EmployeeDT.objects.filter(
                        company=company,
                        Employee_Status__iexact="Activate",
                        is_active=True,
                        Date_of_Joining__month=today.month,
                        Date_of_Joining__year__lt=today.year,
                    ).values("employee_code", "name", "Date_of_Joining")
                )

            data = {
                "employee_code": employee.employee_code,
                "name": employee.name,
                "today": {
                    "checked_in": checked_in,
                    "checked_out": checked_out,
                    "login_time": todays_checkin.login_time if todays_checkin else None,
                    "logout_time": todays_checkin.logout_time if todays_checkin else None,
                },
                "attendance_this_month": attendance_summary,
                "payroll_this_month": {
                    "monthly_earning": monthly_earning,
                    "unpaid_earning": unpaid_earning,
                },
                "company": {
                    "total_employees": total_employees,
                    "new_joining": new_joining,
                    "birthdays_this_month": birthdays_this_month,
                    "work_anniversary": work_anniversary,
                    "holidays_this_month": holidays_this_month,
                    "upcoming_holidays": upcoming_holidays,
                    "holidays_this_year": holidays_this_year,
                    "all_holidays": all_holidays,
                },
            }

            return Response({
                "status": "success",
                "code": "employee_dashboard",
                "message": "Dashboard data fetched successfully.",
                "data": data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not load dashboard: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Employee Role CRUD (HR / Admin manage roles)
# Reuses the existing EmployeeRoleSerializer (Employee/serializers.py)
# and the Admin-or-HR auth/permission pair already built for
# EmployeeViewSet - no duplicate auth logic.
# ============================================================

from .employee_crud_permissions import resolve_company_for_user as _resolve_company_for_role
from .serializers import EmployeeRoleSerializer
from .models import EmployeeRole


class EmployeeRoleViewSet(ModelViewSet):
    """
    Full CRUD for HR roles / permission sets.

    GET    /api/roles/         list
    POST   /api/roles/         create
    GET    /api/roles/<id>/    retrieve
    PUT    /api/roles/<id>/    update
    PATCH  /api/roles/<id>/    partial update
    DELETE /api/roles/<id>/    delete

    Company-isolated the same way EmployeeViewSet is: a
    mismatched <id> from another company 404s instead of
    leaking data.
    """

    serializer_class = EmployeeRoleSerializer

    authentication_classes = [AdminOrEmployeeJWTAuthentication]
    permission_classes = [IsAdminOrHR]

    def get_company(self):

        company = _resolve_company_for_role(self.request.user)

        if company is None:
            raise PermissionDenied(
                "Unable to resolve your company. Access denied."
            )

        return company

    def get_queryset(self):
        return EmployeeRole.objects.filter(company=self.get_company())

    def perform_create(self, serializer):
        serializer.save(company=self.get_company())

    def perform_update(self, serializer):
        serializer.save(company=self.get_company())


# ============================================================
# ADDITIVE: Department CRUD (HR / Admin manage departments)
# Each company manages its own list of departments. Reuses the
# same Admin-or-HR auth/permission pair already built for
# EmployeeViewSet / EmployeeRoleViewSet - no duplicate auth logic.
# ============================================================

from .serializers import DepartmentSerializer
from .models import Department


class DepartmentViewSet(ModelViewSet):
    """
    Full CRUD for company departments.

    GET    /api/departments/         list
    POST   /api/departments/         create
    GET    /api/departments/<id>/    retrieve
    PUT    /api/departments/<id>/    update
    PATCH  /api/departments/<id>/    partial update
    DELETE /api/departments/<id>/    delete

    Company-isolated the same way EmployeeViewSet /
    EmployeeRoleViewSet are: a mismatched <id> from another
    company 404s instead of leaking data.
    """

    serializer_class = DepartmentSerializer

    authentication_classes = [AdminOrEmployeeJWTAuthentication]
    permission_classes = [IsAdminOrHR]

    def get_company(self):

        company = _resolve_company_for_role(self.request.user)

        if company is None:
            raise PermissionDenied(
                "Unable to resolve your company. Access denied."
            )

        return company

    def get_queryset(self):
        return Department.objects.filter(company=self.get_company())

    def perform_create(self, serializer):
        serializer.save(company=self.get_company())

    def perform_update(self, serializer):
        serializer.save(company=self.get_company())


# ============================================================
# ADDITIVE: Employee Check-In / Check-Out (self-service)
# Uses EMP_check_in_check_out + mirrors legacy check_st /
# Employ_check_id flags on EmployeeDT so any existing
# check_st == 'check_in' filters elsewhere keep working.
# ============================================================

from datetime import datetime as _datetime, timedelta as _timedelta

from .models import EMP_check_in_check_out


def _fmt_time(t):
    return t.strftime("%H:%M:%S")


def _working_hours_str(login_date, login_time_str, logout_date, logout_time_str):

    try:

        login_dt = _datetime.combine(
            login_date, _datetime.strptime(login_time_str, "%H:%M:%S").time()
        )
        logout_dt = _datetime.combine(
            logout_date, _datetime.strptime(logout_time_str, "%H:%M:%S").time()
        )

        seconds = max((logout_dt - login_dt).total_seconds(), 0)
        hours, rem = divmod(int(seconds), 3600)
        minutes, secs = divmod(rem, 60)

        return f"{hours:02d}:{minutes:02d}:{secs:02d}"

    except Exception:
        return None


class EmployeeCheckInView(APIView):
    """
    POST /employee/check-in/

    body (all optional except when your frontend requires them):
        { "latitude": 19.07, "longitude": 72.87, "location_type": "office" }
        + optional multipart "image"

    One open check-in per employee per day - repeating the call
    while already checked in (no check-out yet) is rejected.
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def post(self, request):

        try:

            employee = request.user
            today = timezone.localdate()
            now_time = timezone.localtime().time()

            already_open = EMP_check_in_check_out.objects.filter(
                Employee_ID=employee.employee_code,
                login_date=today,
                logout_time__isnull=True,
            ).exists()

            if already_open:

                return Response({
                    "status": "error",
                    "code": "already_checked_in",
                    "message": "You are already checked in today. Please check out first.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            record = EMP_check_in_check_out.objects.create(
                Employee_ID=employee.employee_code,
                company=employee.company,
                Name=employee.name,
                image=request.FILES.get("image"),
                login_date=today,
                login_time=_fmt_time(now_time),
                checkin_latitude=request.data.get("latitude") or None,
                checkin_longitude=request.data.get("longitude") or None,
                checkin_location_type=request.data.get("location_type") or None,
                comment=request.data.get("comment") or None,
            )

            employee.check_st = "check_in"
            employee.Employ_check_id = str(record.id)
            employee.save(update_fields=["check_st", "Employ_check_id"])

            return Response({
                "status": "success",
                "code": "checked_in",
                "message": "Checked in successfully.",
                "data": EmployeeCheckInOutSerializer(record).data,
            }, status=http_status.HTTP_201_CREATED)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not check in: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


class EmployeeCheckOutView(APIView):
    """
    POST /employee/check-out/

    body (all optional):
        { "latitude": 19.07, "longitude": 72.87, "location_type": "office" }
        + optional multipart "image" (stored as check_out_image)

    Closes today's open check-in record and computes
    total_working_hours from login_time -> logout_time.
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def post(self, request):

        try:

            employee = request.user
            today = timezone.localdate()
            now_time = timezone.localtime().time()

            record = EMP_check_in_check_out.objects.filter(
                Employee_ID=employee.employee_code,
                login_date=today,
                logout_time__isnull=True,
            ).order_by("-id").first()

            if not record:

                return Response({
                    "status": "error",
                    "code": "not_checked_in",
                    "message": "No open check-in found for today.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            record.logout_date = today
            record.logout_time = _fmt_time(now_time)
            record.total_working_hours = _working_hours_str(
                record.login_date, record.login_time,
                record.logout_date, record.logout_time,
            )
            record.checkout_latitude = request.data.get("latitude") or None
            record.checkout_longitude = request.data.get("longitude") or None
            record.checkout_location_type = request.data.get("location_type") or None
            record.comment = request.data.get("comment") or record.comment

            if request.FILES.get("image"):
                record.check_out_image = request.FILES.get("image")

            # ---------------- OPTIONAL: mark selected targets complete ----------------
            # body: { "targets": [1, 2, 3] } - Target ids owned by this employee
            target_ids = request.data.get("targets") or []

            if isinstance(target_ids, str):
                target_ids = [t for t in target_ids.split(",") if t.strip()]

            target_ids = [int(t) for t in target_ids if str(t).strip().isdigit()]

            if target_ids:

                from .models import Target

                selected_targets = Target.objects.filter(
                    id__in=target_ids, employee=employee
                )

                completed_list = []

                for target in selected_targets:

                    target.completed = True
                    target.completed_date = today
                    target.save()

                    completed_list.append({
                        "id": target.id,
                        "title": target.titel,
                        "description": target.description,
                        "target_date": str(target.target_date),
                        "completed_date": str(target.completed_date),
                    })

                record.completed_targets = (record.completed_targets or []) + completed_list

            record.save()

            employee.check_st = None
            employee.Employ_check_id = None
            employee.save(update_fields=["check_st", "Employ_check_id"])

            return Response({
                "status": "success",
                "code": "checked_out",
                "message": "Checked out successfully.",
                "data": EmployeeCheckInOutSerializer(record).data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not check out: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


class EmployeeCheckInStatusView(APIView):
    """
    GET /employee/check-in/status/

    Quick "am I checked in right now" poll for the frontend -
    today's open (or most recent) check-in/out record, if any.
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            employee = request.user
            today = timezone.localdate()

            record = EMP_check_in_check_out.objects.filter(
                Employee_ID=employee.employee_code,
                login_date=today,
            ).order_by("-id").first()

            data = {
                "checked_in": bool(record and record.login_time and not record.logout_time),
                "checked_out": bool(record and record.logout_time),
                "record": EmployeeCheckInOutSerializer(record).data if record else None,
            }

            return Response({
                "status": "success",
                "code": "check_in_status",
                "message": "Check-in status fetched successfully.",
                "data": data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not fetch check-in status: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Employee Self Profile (view / edit own personal info)
# ============================================================

class EmployeeProfileView(APIView):
    """
    GET   /employee/profile/
    PATCH /employee/profile/

    Personal-info self-edit only (name, contact, address, family,
    photo, etc). Salary/statutory/employment-status fields stay
    Admin/HR-only via EmployeeViewSet - see
    EmployeeSelfProfileSerializer for the exact field list.
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def get(self, request):

        from .serializers import EmployeeSelfProfileSerializer

        return Response({
            "status": "success",
            "code": "employee_profile",
            "message": "Profile fetched successfully.",
            "data": EmployeeSelfProfileSerializer(request.user).data,
        }, status=http_status.HTTP_200_OK)

    def patch(self, request):

        try:

            from .serializers import EmployeeSelfProfileSerializer

            serializer = EmployeeSelfProfileSerializer(
                request.user, data=request.data, partial=True
            )

            if not serializer.is_valid():

                return Response({
                    "status": "error",
                    "code": "validation_error",
                    "message": "Invalid profile data.",
                    "data": serializer.errors,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            serializer.save()

            return Response({
                "status": "success",
                "code": "profile_updated",
                "message": "Profile updated successfully.",
                "data": serializer.data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not update profile: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Employee's own check-in/out history (paginated)
# ============================================================

class EmployeeMyCheckInHistoryView(APIView):
    """GET /employee/check-in/history/?page=1 - own records, newest first."""

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            from django.core.paginator import Paginator

            employee = request.user

            qs = EMP_check_in_check_out.objects.filter(
                Employee_ID=employee.employee_code
            ).order_by("-login_date", "-id")

            paginator = Paginator(qs, 15)
            page = paginator.get_page(request.query_params.get("page"))

            return Response({
                "status": "success",
                "code": "my_check_in_history",
                "message": "Check-in history fetched successfully.",
                "data": {
                    "count": paginator.count,
                    "num_pages": paginator.num_pages,
                    "current_page": page.number,
                    "results": EmployeeCheckInOutSerializer(page.object_list, many=True).data,
                },
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not fetch check-in history: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Employee's own attendance list
# ============================================================

class EmployeeMyAttendanceView(APIView):
    """GET /employee/attendance/ - all of the caller's own attendance records."""

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            from .models import AttendanceEmp
            from .serializers import AttendanceEmpSerializer

            qs = AttendanceEmp.objects.filter(
                Employee_ID=request.user.employee_code
            ).order_by("-date")

            return Response({
                "status": "success",
                "code": "my_attendance",
                "message": "Attendance fetched successfully.",
                "data": AttendanceEmpSerializer(qs, many=True).data,
            }, status=http_status.HTTP_200_OK)

        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)


# ============================================================
# ADDITIVE: Employee's own payroll list
# ============================================================

class EmployeeMyPayrollView(APIView):
    """GET /employee/payroll/ - all of the caller's own payroll records."""

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            from .models import Payroll
            from .serializers import PayrollSerializer

            qs = Payroll.objects.filter(
                Employee_ID=request.user.employee_code
            ).order_by("-year", "-month")

            return Response({
                "status": "success",
                "code": "my_payroll",
                "message": "Payroll fetched successfully.",
                "data": PayrollSerializer(qs, many=True).data,
            }, status=http_status.HTTP_200_OK)

        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)


# ============================================================
# ADDITIVE: Employee's own Targets (list pending/all + create)
# ============================================================

class EmployeeMyTargetView(APIView):
    """
    GET  /employee/targets/                 - own targets
    GET  /employee/targets/?status=pending  - only incomplete ones
    POST /employee/targets/                 - create a new target for self
         body: { "titel": "...", "description": "...", "target_date": "YYYY-MM-DD" }
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            from .models import Target
            from .serializers import TargetSerializer

            qs = Target.objects.filter(employee=request.user).order_by("-target_date")

            status_filter = request.query_params.get("status")
            if status_filter == "pending":
                qs = qs.filter(completed=False)
            elif status_filter == "completed":
                qs = qs.filter(completed=True)

            return Response({
                "status": "success",
                "code": "my_targets",
                "message": "Targets fetched successfully.",
                "data": TargetSerializer(qs, many=True).data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not fetch targets: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request):

        try:

            from datetime import date as _date
            from .models import Target
            from .serializers import TargetSerializer

            employee = request.user

            target = Target.objects.create(
                employee=employee,
                company=employee.company,
                titel=request.data.get("titel"),
                description=request.data.get("description"),
                create_date=_date.today(),
                target_date=request.data.get("target_date"),
            )

            return Response({
                "status": "success",
                "code": "target_created",
                "message": "Target created successfully.",
                "data": TargetSerializer(target).data,
            }, status=http_status.HTTP_201_CREATED)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not create target: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Employee's own Daily Task (submit once/day + list)
# ============================================================

class EmployeeMyDailyTaskView(APIView):
    """
    GET  /employee/daily-tasks/                        - own tasks, newest first
    GET  /employee/daily-tasks/?task_date=&status=      - filtered
    POST /employee/daily-tasks/                         - submit today's task
         body: { "titel": "...", "description": "..." }
         Rejected if a task for today already exists (one per day,
         same rule as the legacy submit_daily_task view).
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            from .models import DailyTask
            from .serializers import DailyTaskSerializer

            qs = DailyTask.objects.filter(employee=request.user).order_by("-task_date")

            task_date = request.query_params.get("task_date")
            if task_date:
                qs = qs.filter(task_date=task_date)

            status_filter = request.query_params.get("status")
            if status_filter == "completed":
                qs = qs.filter(completed=True)
            elif status_filter == "pending":
                qs = qs.filter(completed=False)

            return Response({
                "status": "success",
                "code": "my_daily_tasks",
                "message": "Daily tasks fetched successfully.",
                "data": DailyTaskSerializer(qs, many=True).data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not fetch daily tasks: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request):

        try:

            from datetime import date as _date
            from .models import DailyTask
            from .serializers import DailyTaskSerializer

            employee = request.user
            today = _date.today()

            if DailyTask.objects.filter(employee=employee, task_date=today).exists():

                return Response({
                    "status": "error",
                    "code": "already_submitted",
                    "message": "You have already submitted a task for today.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            task = DailyTask.objects.create(
                employee=employee,
                company=employee.company,
                title=request.data.get("titel") or request.data.get("title"),
                description=request.data.get("description"),
                task_date=today,
            )

            return Response({
                "status": "success",
                "code": "daily_task_submitted",
                "message": "Task submitted successfully.",
                "data": DailyTaskSerializer(task).data,
            }, status=http_status.HTTP_201_CREATED)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not submit task: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Employee Messaging (colleague-to-colleague chat)
# ============================================================

class EmployeeColleagueListView(APIView):
    """GET /employee/colleagues/ - other employees in the same company (for chat)."""

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        from .serializers import EmployeeCRUDSerializer

        employee = request.user

        colleagues = EmployeeDT.objects.filter(
            company=employee.company
        ).exclude(employee_code=employee.employee_code)

        return Response({
            "status": "success",
            "code": "colleague_list",
            "message": "Colleagues fetched successfully.",
            "data": [
                {
                    "employee_code": c.employee_code,
                    "name": c.name,
                    "email": c.email,
                    "image": c.image.url if c.image else None,
                }
                for c in colleagues
            ],
        }, status=http_status.HTTP_200_OK)


class EmployeeMessagesView(APIView):
    """GET /employee/messages/?receiver_id=<employee_code> - conversation history."""

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def get(self, request):

        try:

            from .models import Message

            employee = request.user
            receiver_id = request.query_params.get("receiver_id")

            if not receiver_id:

                return Response({
                    "status": "error",
                    "code": "missing_receiver_id",
                    "message": "receiver_id query param is required.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            messages_qs = Message.objects.filter(
                company=employee.company,
                sender_emp_id__in=[employee.employee_code, receiver_id],
                reciver_emp_id__in=[employee.employee_code, receiver_id],
            ).order_by("timestamp")

            return Response({
                "status": "success",
                "code": "messages",
                "message": "Messages fetched successfully.",
                "data": [
                    {
                        "sender": msg.sender_emp_id,
                        "content": msg.content,
                        "timestamp": msg.timestamp.strftime("%d-%m-%y %H:%M"),
                    }
                    for msg in messages_qs
                ],
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not fetch messages: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


class EmployeeSendMessageView(APIView):
    """
    POST /employee/messages/send/
    body: { "receiver_id": "<employee_code>", "message": "..." }
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def post(self, request):

        try:

            from .models import Message

            employee = request.user
            receiver_id = request.data.get("receiver_id")
            message_text = request.data.get("message")

            if not receiver_id or not message_text:

                return Response({
                    "status": "error",
                    "code": "missing_fields",
                    "message": "receiver_id and message are required.",
                    "data": None,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            message = Message.objects.create(
                employee=employee,
                sender_emp_id=employee.employee_code,
                reciver_emp_id=receiver_id,
                company=employee.company,
                content=message_text,
            )

            return Response({
                "status": "success",
                "code": "message_sent",
                "message": "Message sent successfully.",
                "data": {
                    "sender": message.sender_emp_id,
                    "content": message.content,
                    "timestamp": message.timestamp.strftime("%H:%M"),
                },
            }, status=http_status.HTTP_201_CREATED)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not send message: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Save today's GPS location against attendance
# ============================================================

class EmployeeSaveLocationView(APIView):
    """
    POST /employee/save-location/
    body: { "latitude": 19.07, "longitude": 72.87 }

    Upserts today's AttendanceEmp row with the given coordinates
    (mirrors the legacy save_location view).
    """

    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    def post(self, request):

        try:

            from .models import AttendanceEmp

            employee = request.user
            today = timezone.localdate()

            attendance, _created = AttendanceEmp.objects.get_or_create(
                Employee_ID=employee.employee_code,
                date=today,
                defaults={
                    "status": "Present",
                    "company": employee.company,
                    "Name": employee.name,
                },
            )

            attendance.latitude = request.data.get("latitude")
            attendance.longitude = request.data.get("longitude")
            attendance.save()

            return Response({
                "status": "success",
                "code": "location_saved",
                "message": "Location saved successfully.",
                "data": None,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not save location: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
            
            