from django.shortcuts import (
    render,
    redirect,
    get_object_or_404,
)
from django.views import View
from django.db import transaction
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateAPIView

from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.http import require_POST
from django.db.models import Q

from Company.models import (
    AuthLog,
    log_auth_event,
    blacklist_token,
    company_details,
)

# ADDITIVE: Super Admin HR dashboard summaries
from Employee.models import LeaveRequest
from PayrollHub.models import PayrollCycle, Payslip

from django.db.models import Q, Count

import csv
from django.http import HttpResponse, JsonResponse

from .models import (
    SuperAdminProfile,
    CompanyAdmin,
    CompanyUsage,
    SuperAdminAuditLog,
    CompanySubscription,
    SuperAdminSettings,
    SubscriptionPackage,
)
import time

from django.db import connection
from Employee.models import (
    EmployeeDT,
    Candidate,
    EmployeeAccount,
    EmployeeRole,
    EMP_check_in_check_out,
)

from Employee.models import LeaveRequest
from PayrollHub.models import PayrollCycle, PayrollInput, Payslip   
# Create your views here.

# ============================================================
# ADDITIVE: SuperAdmin login / logout + platform-wide auth log
# ============================================================

from django.contrib.auth import authenticate
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status as http_status
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.exceptions import TokenError

from .models import (
    SuperAdminProfile, SuperAdminAuditLog, SuperAdminSettings,
)
from Company.models import company_details

from .serializers import PlatformCompanySerializer, SuperAdminSettingsSerializer


class SuperAdminLoginPageView(View):
    """Django template shell for the existing JWT login endpoint."""

    def get(self, request):
        return render(request, "SuperAdmin/login.html")


class SuperAdminDashboardPageView(View):
    """Django template shell; data/actions use protected super-admin APIs."""

    def get(self, request):
        return render(request, "SuperAdmin/dashboard.html")
from Company.models import AuthLog, log_auth_event, blacklist_token
from Company.serializers import AuthLogSerializer
from .superadmin_authentication import (
    SuperAdminJWTAuthentication,
    IsSuperAdminAuthenticated,
)


# ============================================================
# SUPERADMIN LOGIN
# ============================================================

class SuperAdminLoginView(APIView):
    """
    POST /superadmin/auth/login/

    body:
        {
            "username": "platform_owner",
            "password": "xxxxxxxx"
        }

    Authenticates against Django's built-in auth.User
    (django.contrib.auth.authenticate), resolves the linked
    SuperAdminProfile, issues a JWT (type="superadmin"), and
    writes one AuthLog row per attempt.
    """

    authentication_classes = []
    permission_classes = []

    def post(self, request):

        username = request.data.get("username")
        password = request.data.get("password")

        if not username or not password:

            log_auth_event(
                actor_type=AuthLog.ACTOR_SUPERADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=username,
                reason="Missing username or password",
            )

            return Response({
                "status": "error",
                "code": "missing_fields",
                "message": "Username and password are required.",
                "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        user = authenticate(
            request,
            username=username,
            password=password,
        )

        if user is None:

            log_auth_event(
                actor_type=AuthLog.ACTOR_SUPERADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=username,
                reason="Invalid credentials",
            )

            return Response({
                "status": "error",
                "code": "invalid_credentials",
                "message": "Invalid username or password.",
                "data": None,
            }, status=http_status.HTTP_401_UNAUTHORIZED)

        try:

            profile = SuperAdminProfile.objects.get(user=user)

        except SuperAdminProfile.DoesNotExist:

            log_auth_event(
                actor_type=AuthLog.ACTOR_SUPERADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=username,
                reason="No SuperAdmin profile linked to this user",
            )

            return Response({
                "status": "error",
                "code": "not_a_superadmin",
                "message": "This account is not a SuperAdmin.",
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        if not profile.is_active:

            log_auth_event(
                actor_type=AuthLog.ACTOR_SUPERADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=username,
                actor_id=profile.id,
                reason="SuperAdmin inactive",
            )

            return Response({
                "status": "error",
                "code": "superadmin_disabled",
                "message": "SuperAdmin account is inactive.",
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        refresh = RefreshToken()
        refresh["type"] = "superadmin"
        refresh["user_id"] = profile.id
        refresh["username"] = user.username

        log_auth_event(
            actor_type=AuthLog.ACTOR_SUPERADMIN,
            action=AuthLog.ACTION_LOGIN,
            status=AuthLog.STATUS_SUCCESS,
            request=request,
            identifier=username,
            actor_id=profile.id,
        )

        return Response({
            "status": "success",
            "code": "login_success",
            "message": "Login successful.",
            "data": {
                "access": str(refresh.access_token),
                "refresh": str(refresh),
                "superadmin_id": profile.id,
                "full_name": profile.full_name,
                "username": user.username,
            },
        }, status=http_status.HTTP_200_OK)


# ============================================================
# SUPERADMIN LOGOUT
# ============================================================

class SuperAdminLogoutView(APIView):
    """
    POST /superadmin/auth/logout/

    body:
        { "refresh": "<refresh_token>" }

    Requires a valid superadmin access token. Blacklists the
    refresh token and logs the logout.
    """

    authentication_classes = [SuperAdminJWTAuthentication]
    permission_classes = [IsSuperAdminAuthenticated]

    def post(self, request):

        profile = 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_SUPERADMIN,
            action=AuthLog.ACTION_LOGOUT,
            status=AuthLog.STATUS_SUCCESS,
            request=request,
            identifier=profile.user.username,
            actor_id=profile.id,
        )

        return Response({
            "status": "success",
            "code": "logout_success",
            "message": "Logged out successfully.",
            "data": None,
        }, status=http_status.HTTP_200_OK)


# ============================================================
# PLATFORM-WIDE AUTH LOG LIST
# (SuperAdmin only: sees every actor type - SuperAdmin,
# Company Admin, Employee - across every company)
# ============================================================

class PlatformAuthLogListView(APIView):
    """
    GET /superadmin/auth/logs/

    Optional query params: ?action=LOGIN|LOGOUT
                            ?status=SUCCESS|FAILED
                            ?actor_type=SUPERADMIN|COMPANY_ADMIN|EMPLOYEE
                            ?company_id=<company_id>
    """

    authentication_classes = [SuperAdminJWTAuthentication]
    permission_classes = [IsSuperAdminAuthenticated]

    def get(self, request):

        logs = AuthLog.objects.all()

        action = request.query_params.get("action")
        if action:
            logs = logs.filter(action=action.upper())

        req_status = request.query_params.get("status")
        if req_status:
            logs = logs.filter(status=req_status.upper())

        actor_type = request.query_params.get("actor_type")
        if actor_type:
            logs = logs.filter(actor_type=actor_type.upper())

        company_id = request.query_params.get("company_id")
        if company_id:
            logs = logs.filter(company__company_id=company_id)

        logs = logs[:500]

        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)


class SuperAdminDashboardView(APIView):
    """Platform overview for the super-admin dashboard."""

    authentication_classes = [SuperAdminJWTAuthentication]
    permission_classes = [IsSuperAdminAuthenticated]

    def get(self, request):
        companies = company_details.objects.all()
        data = {
            "companies_total": companies.count(),
            "companies_active": companies.filter(status=True).count(),
            "companies_pending": companies.filter(is_verified=False).count(),
            "employees_total": EmployeeDT.objects.count(),
            "recent_audit_logs": list(
                SuperAdminAuditLog.objects.select_related("company")
                .order_by("-created_at")[:10]
                .values("id", "action", "description", "company__company_id", "created_at")
            ),
        }
        return Response({"status": "success", "code": "platform_dashboard", "data": data})


class PlatformCompanyListCreateView(ListCreateAPIView):
    """GET/POST /superadmin/companies/ — platform-wide company management."""

    authentication_classes = [SuperAdminJWTAuthentication]
    permission_classes = [IsSuperAdminAuthenticated]
    serializer_class = PlatformCompanySerializer
    queryset = company_details.objects.all().order_by("-id")

    def perform_create(self, serializer):
        with transaction.atomic():
            company = serializer.save()
            SuperAdminAuditLog.objects.create(
                superadmin=self.request.user,
                company=company,
                action="CREATE_COMPANY",
                description=f"Created company {company.company_id}",
                ip_address=self.request.META.get("REMOTE_ADDR"),
            )


class PlatformCompanyDetailView(RetrieveUpdateAPIView):
    """GET/PATCH /superadmin/companies/<id>/; supports safe field updates."""

    authentication_classes = [SuperAdminJWTAuthentication]
    permission_classes = [IsSuperAdminAuthenticated]
    serializer_class = PlatformCompanySerializer
    queryset = company_details.objects.all()
    lookup_field = "company_id"

    def perform_update(self, serializer):
        company = serializer.save()
        SuperAdminAuditLog.objects.create(
            superadmin=self.request.user,
            company=company,
            action="UPDATE_COMPANY",
            description=f"Updated company {company.company_id}",
            ip_address=self.request.META.get("REMOTE_ADDR"),
        )


class PlatformCompanyStatusView(APIView):
    """POST /superadmin/companies/<id>/status/ with {"status": true|false}."""

    authentication_classes = [SuperAdminJWTAuthentication]
    permission_classes = [IsSuperAdminAuthenticated]

    def post(self, request, company_id):
        enabled = request.data.get("status")
        if not isinstance(enabled, bool):
            return Response({"status": "error", "code": "invalid_status", "message": "status must be true or false.", "data": None}, status=http_status.HTTP_400_BAD_REQUEST)
        try:
            company = company_details.objects.get(company_id=company_id)
        except company_details.DoesNotExist:
            return Response({"status": "error", "code": "company_not_found", "data": None}, status=http_status.HTTP_404_NOT_FOUND)

        company.status = enabled
        company.save(update_fields=["status"])
        action = "ACTIVATE_COMPANY" if enabled else "DEACTIVATE_COMPANY"
        SuperAdminAuditLog.objects.create(
            superadmin=request.user, company=company, action=action,
            description=f"{'Activated' if enabled else 'Deactivated'} company {company.company_id}",
            ip_address=request.META.get("REMOTE_ADDR"),
        )
        return Response({"status": "success", "code": "company_status_updated", "data": {"company_id": company.company_id, "status": company.status}})


class PlatformSettingsView(RetrieveUpdateAPIView):
    """GET/PATCH /superadmin/settings/ for the singleton platform settings row."""

    authentication_classes = [SuperAdminJWTAuthentication]
    permission_classes = [IsSuperAdminAuthenticated]
    serializer_class = SuperAdminSettingsSerializer

    def get_object(self):
        obj, _ = SuperAdminSettings.objects.get_or_create(pk=1)
        return obj

    def perform_update(self, serializer):
        serializer.save(pk=1)
        SuperAdminAuditLog.objects.create(
            superadmin=self.request.user, action="OTHER",
            description="Updated platform settings",
            ip_address=self.request.META.get("REMOTE_ADDR"),
        )



# ============================================================
# SUPERADMIN WEB PORTAL
# ADDITIVE CODE
# Existing JWT API code above remains unchanged.
# ============================================================

from functools import wraps
from datetime import timedelta

from django.shortcuts import (
    render,
    redirect,
    get_object_or_404,
)

from django.contrib import messages
from django.contrib.auth import (
    authenticate,
    login,
    logout,
)

from django.contrib.auth import get_user_model

User = get_user_model()

from django.views.decorators.http import require_POST
from django.db.models import Q, Count
from django.utils import timezone

from Company.models import company_details

from Employee.models import (
    EmployeeDT,
    EmployeeAccount,
    EmployeeRole,
)

from .models import (
    SuperAdminProfile,
    CompanyAdmin,
    CompanyUsage,
    SuperAdminAuditLog,
    CompanySubscription,
    SuperAdminSettings,
)


# ============================================================
# SUPERADMIN SESSION CHECK
# ============================================================

def superadmin_required(view_func):

    @wraps(view_func)
    def wrapper(request, *args, **kwargs):

        if not request.user.is_authenticated:

            return redirect(
                'superadmin_portal_login'
            )

        try:

            profile = SuperAdminProfile.objects.get(
                user=request.user,
                is_active=True
            )

        except SuperAdminProfile.DoesNotExist:

            logout(request)

            messages.error(
                request,
                "Super Admin profile not found or inactive."
            )

            return redirect(
                'superadmin_portal_login'
            )

        request.superadmin_profile = profile

        return view_func(
            request,
            *args,
            **kwargs
        )

    return wrapper


# ============================================================
# PORTAL LOGIN
# ============================================================

def superadmin_login_page(request):

    if request.user.is_authenticated:

        try:

            profile = SuperAdminProfile.objects.get(
                user=request.user,
                is_active=True
            )

            return redirect(
                'superadmin_dashboard'
            )

        except SuperAdminProfile.DoesNotExist:

            logout(request)

    if request.method == 'POST':

        username = request.POST.get(
            'username',
            ''
        ).strip()

        password = request.POST.get(
            'password',
            ''
        )

        if not username or not password:

            messages.error(
                request,
                "Username and password are required."
            )

            return render(
                request,
                'superadmin/login.html'
            )

        user = authenticate(
            request,
            username=username,
            password=password
        )

        if user is None:

            messages.error(
                request,
                "Invalid username or password."
            )

            return render(
                request,
                'superadmin/login.html'
            )

        try:

            profile = SuperAdminProfile.objects.get(
                user=user
            )

        except SuperAdminProfile.DoesNotExist:

            messages.error(
                request,
                "This account is not registered as a Super Admin."
            )

            return render(
                request,
                'superadmin/login.html'
            )

        if not profile.is_active:

            messages.error(
                request,
                "Super Admin account is inactive."
            )

            return render(
                request,
                'superadmin/login.html'
            )

        login(request, user)

        try:

            log_auth_event(
                actor_type=AuthLog.ACTOR_SUPERADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_SUCCESS,
                request=request,
                identifier=user.username,
                actor_id=profile.id
            )

        except Exception:
            pass

        return redirect(
            'superadmin_dashboard'
        )

    return render(
        request,
        'superadmin/login.html'
    )


# ============================================================
# PORTAL LOGOUT
# ============================================================

@superadmin_required
def superadmin_logout(request):

    profile = getattr(
        request,
        'superadmin_profile',
        None
    )

    try:

        if profile:

            log_auth_event(
                actor_type=AuthLog.ACTOR_SUPERADMIN,
                action=AuthLog.ACTION_LOGOUT,
                status=AuthLog.STATUS_SUCCESS,
                request=request,
                identifier=request.user.username,
                actor_id=profile.id
            )

    except Exception:
        pass

    logout(request)

    messages.success(
        request,
        "You have been logged out successfully."
    )

    return redirect(
        'superadmin_portal_login'
    )


# ============================================================
# DASHBOARD
# ============================================================
# ============================================================
# SUPER ADMIN DASHBOARD
# ============================================================

@superadmin_required
def superadmin_dashboard(request):

    # ========================================================
    # 1. COMPANY RESOLUTION & PARAMETERS
    # ========================================================
    companies = company_details.objects.all()
    selected_company_id = str(request.GET.get('company') or request.GET.get('company_id') or '').strip()
    selected_company = None
    if selected_company_id.isdigit():
        selected_company = companies.filter(id=int(selected_company_id)).first()
    elif selected_company_id and selected_company_id.lower() not in ["all", "", "none"]:
        selected_company = companies.filter(company_id=selected_company_id).first()
    if selected_company is None:
        selected_company_id = ''

    today = timezone.localdate()
    # Monthly Candidate Selections: safe defaults
    report_month = today.month
    report_year = today.year
    monthly_selection_report = []
    

    # ========================================================
    # 2. SAFE VARIABLE INITIALIZATION (PREVENTS UnboundLocalError)
    # ========================================================
    total_user_accounts = 0
    active_user_accounts = 0
    inactive_user_accounts = 0
    total_companies = companies.count()
    active_companies = 0
    trial_companies = 0
    suspended_companies = 0
    inactive_companies = 0
    expired_companies = 0

    hr_attendance_today = EMP_check_in_check_out.objects.none()
    hr_checkins_today = 0
    hr_checkouts_today = 0
    hr_pending_checkouts_today = 0
    hr_total_leave_requests = 0
    hr_pending_leave_requests = 0
    hr_approved_leave_requests = 0
    hr_open_payroll_cycles = 0
    hr_released_payroll_cycles = 0
    hr_current_month_payslips = 0

    hr_active_headcount = 0
    hr_active_candidates = 0
    hr_interviews_today = 0
    hr_ready_to_join = 0
    hr_on_notice_period = 0
    hr_pending_approvals = 0

    org_total_emp = 0
    org_leaders_count = 0
    org_departments_count = 0
    org_teams_count = 0
    org_locations_count = 0

    upcoming_holidays = []
    upcoming_interviews = []


    # ========================================================
    # MONTHLY CANDIDATE SELECTION REPORT
    # ========================================================

    report_month = today.month
    report_year = today.year

    monthly_selection_report = []

    total_employees = 0
    active_employees = 0
    inactive_employees = 0
    disabled_employee_logins = 0

    total_candidates = 0
    applied_candidates = 0
    shortlisted_candidates = 0
    interview_candidates = 0
    selected_candidates = 0
    offered_candidates = 0
    rejected_candidates = 0
    hired_candidates = 0

    total_admins = 0
    active_admins = 0
    inactive_admins = 0

    subscriptions = CompanySubscription.objects.none()
    expiring_soon = []
    recent_audit_logs = []
    plan_counts = {}
    company_overview = []

    company_today_attendance = EMP_check_in_check_out.objects.none()
    company_attendance_today = EMP_check_in_check_out.objects.none()
    company_attendance = EMP_check_in_check_out.objects.none()
    company_checkins_today = 0
    company_checkouts_today = 0
    company_checked_out_today = 0
    company_pending_checkouts_today = 0
    company_total_leave_requests = 0
    company_pending_leave_requests = 0
    company_open_payroll_cycles = 0
    company_current_month_payslips = 0

    selected_company_id = request.GET.get("company_id") or request.GET.get("company")
    selected_company = None
    if selected_company_id and str(selected_company_id).lower() not in ["all", "", "none"]:
        try:
            selected_company = company_details.objects.filter(
                Q(id=selected_company_id) if str(selected_company_id).isdigit() else Q(company_id=selected_company_id)
            ).first()
        except Exception:
            selected_company = None

    today = timezone.localdate()


    # ========================================================
    # ADDITIVE: PLATFORM-WIDE HR SUMMARY
    # Read-only queries against existing HR models.
    # ========================================================

    # Attendance records for today
    _base_att = (EMP_check_in_check_out.objects.filter(company=selected_company) if selected_company else EMP_check_in_check_out.objects)
    hr_attendance_today = _base_att.filter(
        is_active=True,
        login_date=today,
    )

    hr_checkins_today = hr_attendance_today.count()

    hr_checkouts_today = (
        hr_attendance_today
        .exclude(logout_time__isnull=True)
        .exclude(logout_time="")
        .count()
    )

    hr_pending_checkouts_today = max(
        hr_checkins_today - hr_checkouts_today,
        0,
    )

    # Existing leave request records
    _c_base = {"company": selected_company} if selected_company else {}
    hr_total_leave_requests = LeaveRequest.objects.filter(**_c_base).count()

    hr_pending_leave_requests = LeaveRequest.objects.filter(**_c_base).filter(
        status="Pending",
    ).count()

    hr_approved_leave_requests = LeaveRequest.objects.filter(**_c_base).filter(
        status="Approved",
    ).count()

    # Existing payroll cycle records
    hr_open_payroll_cycles = PayrollCycle.objects.filter(**_c_base).filter(
        status="OPEN",
    ).count()

    hr_released_payroll_cycles = PayrollCycle.objects.filter(**_c_base).filter(
        status="RELEASED",
    ).count()

    # Payslips released for the current month
    hr_current_month_payslips = Payslip.objects.filter(**_c_base).filter(
        month=today.month,
        year=today.year,
        status="RELEASED",
    ).count()



 
    # ========================================================
    # CANDIDATE QUERYSET INITIALIZATION
    # ========================================================
    # Initialize the queryset before using it anywhere in the view.
    # Keep the existing database connection and company filtering.

    candidates = Candidate.objects.select_related("company")

    if selected_company:
        candidates = candidates.filter(company=selected_company)


    # ========================================================
    # HIRED CANDIDATES
    # ========================================================

    hired_candidates = candidates.filter(
        candidate_status="HIRED"
    ).count()



   


    


    # ========================================================
    # PLATFORM USER ACCOUNTS
    # ========================================================
    # Counts actual Django authentication accounts.
    # This is separate from employee and candidate records.
    # Read-only: does not create or modify any records.

    total_user_accounts = User.objects.count()

    active_user_accounts = User.objects.filter(
        is_active=True
    ).count()

    inactive_user_accounts = User.objects.filter(
        is_active=False
    ).count()

    # ========================================================
    # COMPANIES
    # ========================================================

    companies = (
        company_details.objects
        .all()
    )

    total_companies = (
        1 if selected_company else companies.count()
    )

    active_companies = (
        companies
        .filter(
            company_status="ACTIVE"
        )
        .count()
    )

    trial_companies = (
        companies
        .filter(
            company_status="TRIAL"
        )
        .count()
    )

    suspended_companies = (
        companies
        .filter(
            company_status="SUSPENDED"
        )
        .count()
    )

    inactive_companies = (
        companies
        .filter(
            company_status="INACTIVE"
        )
        .count()
    )

    expired_companies = (
        companies
        .filter(
            company_status="EXPIRED"
        )
        .count()
    )


    # ========================================================
    # REAL EMPLOYEES ONLY
    # ========================================================
    #
    # IMPORTANT:
    # EmployeeDT can contain old recruitment/candidate
    # records.
    #
    # EmployeeAccount represents the actual employee login
    # account.
    #
    # Therefore employee statistics must use EmployeeAccount.
    # ========================================================

    employee_accounts = (
        EmployeeAccount.objects
        .select_related(
            "employee",
            "employee__company"
        )
        .filter(
            employee__isnull=False
        )
    )


    # ========================================================
    if selected_company:
        employee_accounts = employee_accounts.filter(employee__company=selected_company)

    # TOTAL EMPLOYEES
    # ========================================================

    total_employees = (
        employee_accounts.count()
    )


    # ========================================================
    # ACTIVE EMPLOYEES
    # ========================================================

    active_employees = (
        employee_accounts
        .filter(
            employee__is_active=True
        )
        .count()
    )


    # ========================================================
    # INACTIVE EMPLOYEES
    # ========================================================

    inactive_employees = (
        employee_accounts
        .filter(
            employee__is_active=False
        )
        .count()
    )

    # ADDITIVE: match the Django admin ("By is active -> No").
    # Counts every inactive EmployeeDT in every company, even without a login account.
    inactive_employees = EmployeeDT.objects.filter(is_active=False, **({"company": selected_company} if selected_company else {})).count()


    # ========================================================
    # DISABLED LOGIN ACCOUNTS
    # ========================================================

    disabled_employee_logins = (
        employee_accounts
        .filter(
            is_login_enabled=False
        )
        .count()
    )


    # ========================================================
    # CANDIDATES
    # ========================================================
    #
    # Candidates are completely separate from employees.
    #
    # They DO NOT count toward employee package limits.
    # ========================================================

    candidates = (
        Candidate.objects
        .select_related(
            "company"
        )
    )


    # ========================================================
    if selected_company:
        candidates = candidates.filter(company=selected_company)


    

    # TOTAL CANDIDATES
    # ========================================================

    total_candidates = (
        candidates.count()
    )


    # ========================================================
    # APPLIED CANDIDATES
    # ========================================================

    applied_candidates = (
        candidates
        .filter(
            candidate_status="APPLIED"
        )
        .count()
    )


    # ========================================================
    # SHORTLISTED CANDIDATES
    # ========================================================

    shortlisted_candidates = (
        candidates
        .filter(
            candidate_status="SHORTLISTED"
        )
        .count()
    )


    # ========================================================
    # INTERVIEW CANDIDATES
    # ========================================================

    interview_candidates = (
        candidates
        .filter(
            candidate_status="INTERVIEW"
        )
        .count()
    )


    # ========================================================
    # SELECTED CANDIDATES
    # ========================================================

    selected_candidates = (
        candidates
        .filter(
            candidate_status="SELECTED"
        )
        .count()
    )


    # ========================================================
    # OFFERED CANDIDATES
    # ========================================================

    offered_candidates = (
        candidates
        .filter(
            candidate_status="OFFERED"
        )
        .count()
    )


    # ========================================================
    # REJECTED CANDIDATES
    # ========================================================

    rejected_candidates = (
        candidates
        .filter(
            candidate_status="REJECTED"
        )
        .count()
    )


    # ========================================================
    # HIRED CANDIDATES
    # ========================================================

    hired_candidates = (
        candidates
        .filter(
            candidate_status="HIRED"
        )
        .count()
    )

    # ========================================================
    # MONTHLY CANDIDATE SELECTIONS
    # ========================================================

    # Validate the selected month.
    try:
        report_month = int(
            request.GET.get("report_month", today.month)
        )
    except (TypeError, ValueError):
        report_month = today.month

    if not 1 <= report_month <= 12:
        report_month = today.month


    # Validate the selected year.
    try:
        report_year = int(
            request.GET.get("report_year", today.year)
        )
    except (TypeError, ValueError):
        report_year = today.year

    if not 2000 <= report_year <= 2100:
        report_year = today.year


    # Start with an empty report.
    monthly_selection_report = []


    # Check which date fields actually exist on Candidate.
    candidate_field_names = {
        field.name
        for field in Candidate._meta.get_fields()
    }

    selection_date_field = next(
        (
            field_name
            for field_name in (
                "selected_at",
                "selection_date",
                "updated_at",
                "modified_at",
                "created_at",
            )
            if field_name in candidate_field_names
        ),
        None,
    )


    # Build the report only if a supported date field exists.
    if selection_date_field:

        selection_filters = {
            "candidate_status__iexact": "SELECTED",
            f"{selection_date_field}__year": report_year,
            f"{selection_date_field}__month": report_month,
        }

        monthly_candidates = (
            candidates
            .filter(**selection_filters)
            .select_related("company")
            .order_by("-" + selection_date_field)
        )

        company_selection_map = {}

        for candidate in monthly_candidates:

            company_id = candidate.company_id

            if company_id not in company_selection_map:

                company_selection_map[company_id] = {
                    "company": candidate.company,
                    "selections": [],
                    "count": 0,
                }

            company_selection_map[company_id]["selections"].append(
                candidate
            )

            company_selection_map[company_id]["count"] += 1

        monthly_selection_report = list(
            company_selection_map.values()
        )


    # ========================================================
    # ========================================================
    # ADDITIVE: HR EXECUTIVE INTELLIGENCE & TELEMETRY
    # (Parity with Executive HR Intelligence Dashboard)
    # ========================================================

    _c_filter = {"company": selected_company} if selected_company else {}
    hr_active_headcount = EmployeeDT.objects.filter(is_active=True, **_c_filter).count()
    if hr_active_headcount == 0:
        hr_active_headcount = active_employees

    hr_active_candidates = (
        candidates
        .exclude(candidate_status__in=["REJECTED", "HIRED", "JOINED", "Rejected", "Hired", "Joined"])
        .count()
    )

    try:
        from Recruitment.models import InterviewRound, JobRequisition
        hr_interviews_today = InterviewRound.objects.filter(**_c_filter).filter(
            scheduled_at__date=today
        ).count()
        upcoming_interviews = (
            InterviewRound.objects.filter(**_c_filter)
            .filter(scheduled_at__date__gte=today)
            .select_related("candidate", "company", "interviewer")
            .order_by("scheduled_at")[:10]
        )
        pending_requisitions = JobRequisition.objects.filter(**_c_filter).filter(
            approval_status__in=["Submitted", "Draft"]
        ).count()
    except Exception:
        hr_interviews_today = 0
        upcoming_interviews = []
        pending_requisitions = 0

    hr_ready_to_join = (
        candidates
        .filter(candidate_status__in=["READY_TO_JOIN", "Ready To Join", "SELECTED", "Selected"])
        .count()
    )

    try:
        from People.models import ExitClearance
        hr_on_notice_period = ExitClearance.objects.filter(
            is_active=True,
            status__in=["Serving Notice", "Under Clearance", "Initiated"],
            **_c_filter
        ).count()
        if hr_on_notice_period == 0:
            hr_on_notice_period = (
                EmployeeDT.objects
                .filter(is_active=True, **_c_filter)
                .exclude(Current_Notice_Period__in=['', None, '0', 'None', 'NA', 'N/A'])
                .count()
            )
    except Exception:
        hr_on_notice_period = 0

    hr_pending_approvals = hr_pending_leave_requests + pending_requisitions

    try:
        from Employee.models import Department
        from People.models import Branch
        org_total_emp = hr_active_headcount
        org_departments_count = Department.objects.filter(is_active=True, **_c_filter).count()
        if org_departments_count == 0:
            org_departments_count = (
                EmployeeDT.objects
                .filter(is_active=True, Department__isnull=False, **_c_filter)
                .exclude(Department="")
                .values("Department")
                .distinct()
                .count()
            )
        from People.models import EmployeeExtra
        lead_qs = EmployeeExtra.objects.filter(reporting_manager__isnull=False, **_c_filter)
        leader_ids = set(lead_qs.values_list("reporting_manager_id", flat=True))
        org_leaders_count = len(leader_ids)
        if org_leaders_count == 0:
            org_leaders_count = EmployeeDT.objects.filter(
                is_active=True, **_c_filter
            ).filter(
                Q(Designation__icontains="Lead") | Q(Designation__icontains="Manager") |
                Q(Designation__icontains="Head") | Q(Designation__icontains="Director")
            ).count()
        if org_leaders_count == 0:
            org_leaders_count = CompanyAdmin.objects.filter(is_active=True, **_c_filter).count() or (1 if selected_company else total_companies)
        org_teams_count = (
            EmployeeDT.objects
            .filter(is_active=True, team_Department__isnull=False, **_c_filter)
            .exclude(team_Department="")
            .values("team_Department")
            .distinct()
            .count()
        )
        if org_teams_count == 0:
            org_teams_count = (
                EmployeeDT.objects
                .filter(is_active=True, Sub_Department__isnull=False, **_c_filter)
                .exclude(Sub_Department="")
                .values("Sub_Department")
                .distinct()
                .count()
                or org_departments_count
            )
        org_locations_count = Branch.objects.filter(is_active=True, **_c_filter).count()
        if org_locations_count == 0:
            org_locations_count = (
                EmployeeDT.objects
                .filter(is_active=True, Work_Location__isnull=False, **_c_filter)
                .exclude(Work_Location="")
                .values("Work_Location")
                .distinct()
                .count()
            )
        if org_locations_count == 0:
            org_locations_count = (
                EmployeeDT.objects
                .filter(is_active=True, City__isnull=False, **_c_filter)
                .exclude(City="")
                .values("City")
                .distinct()
                .count()
                or (1 if selected_company else total_companies)
            )
    except Exception:
        org_total_emp = hr_active_headcount
        org_departments_count = 0
        org_leaders_count = 0
        org_teams_count = 0
        org_locations_count = total_companies

    try:
        from Company.models import Holiday
        upcoming_holidays = (
            Holiday.objects
            .filter(is_active=True, date__gte=today, **_c_filter)
            .select_related("company")
            .order_by("date")[:10]
        )
    except Exception:
        upcoming_holidays = []

    # ========================================================
    # COMPANY ADMINISTRATORS
    # ========================================================

    total_admins = (
        (CompanyAdmin.objects.filter(company=selected_company).count() if selected_company else CompanyAdmin.objects.count())
    )

    active_admins = (CompanyAdmin.objects.filter(company=selected_company, is_active=True).count() if selected_company else CompanyAdmin.objects.filter(is_active=True).count())
    inactive_admins = (CompanyAdmin.objects.filter(company=selected_company, is_active=False).count() if selected_company else CompanyAdmin.objects.filter(is_active=False).count())
    _dummy_old_admins = (
        CompanyAdmin.objects
        .filter(
            is_active=True
        )
        .count()
    )

    _dummy_old_inactive_admins = (
        CompanyAdmin.objects
        .filter(
            is_active=False
        )
        .count()
    )


    # ========================================================
    # ACTIVE SUBSCRIPTIONS
    # ========================================================

    subscriptions = (CompanySubscription.objects.filter(company=selected_company, is_active=True) if selected_company else CompanySubscription.objects.filter(is_active=True))
    _unused_old_subs = (
        CompanySubscription.objects
        .filter(
            is_active=True
        )
    )


    # ========================================================
    # EXPIRING SUBSCRIPTIONS
    # ========================================================

    expiring_soon = (
        subscriptions
        .filter(
            end_date__isnull=False,
            end_date__gte=today,
            end_date__lte=(
                today + timedelta(days=30)
            )
        )
        .select_related(
            "company"
        )[:10]
    )


    # ========================================================
    # RECENT AUDIT LOGS
    # ========================================================

    _audit_qs = (SuperAdminAuditLog.objects.filter(company=selected_company) if selected_company else SuperAdminAuditLog.objects).select_related("company", "superadmin").order_by("-created_at")[:10]
    recent_audit_logs = (
        _audit_qs
    )
    if False:
        recent_audit_logs = (
        SuperAdminAuditLog.objects
        .select_related(
            "company",
            "superadmin"
        )
        .order_by(
            "-created_at"
        )[:10]
    )


    # ========================================================
    # PLAN DISTRIBUTION
    # ========================================================

    plan_counts = {}

    for plan_code, plan_name in (
        company_details.PLAN_CHOICES
    ):

        plan_counts[plan_name] = (
            companies
            .filter(
                plan=plan_code
            )
            .count()
        )


    # ========================================================
    # COMPANY-WISE EMPLOYEE/CANDIDATE SUMMARY
    # ========================================================

    company_overview = []
    all_companies = companies
    if selected_company:
        companies = companies.filter(id=selected_company.id)

    for company in (
        companies
        .order_by(
            "Registered_Company_Name"
        )
    ):

        # ----------------------------------------------
        # REAL EMPLOYEES
        # ----------------------------------------------

        company_employee_accounts = (
            employee_accounts
            .filter(
                employee__company=company
            )
        )

        company_employee_count = (
            company_employee_accounts.count()
        )

        company_active_employee_count = (
            company_employee_accounts
            .filter(
                employee__is_active=True
            )
            .count()
        )

        company_inactive_employee_count = (
            company_employee_accounts
            .filter(
                employee__is_active=False
            )
            .count()
        )


        company_inactive_employee_count = EmployeeDT.objects.filter(
            company=company, is_active=False
        ).count()


        # ----------------------------------------------
        # CANDIDATES
        # ----------------------------------------------

        company_candidate_qs = (
            candidates
            .filter(
                company=company
            )
        )

        company_candidate_count = (
            company_candidate_qs.count()
        )

        company_applied_count = (
            company_candidate_qs
            .filter(
                candidate_status="APPLIED"
            )
            .count()
        )

        company_selected_count = (
            company_candidate_qs
            .filter(
                candidate_status="SELECTED"
            )
            .count()
        )


        # ----------------------------------------------
        # PACKAGE LIMIT
        # ----------------------------------------------

        try:

            package = (
                sync_company_package_limit(
                    company
                )
            )

            employee_limit = (
                package.get(
                    "employee_limit",
                    0
                )
            )

            package_name = (
                package.get(
                    "name",
                    "Free"
                )
            )

        except Exception:

            employee_limit = (
                getattr(
                    company,
                    "employee_limit",
                    0
                )
                or 0
            )

            package_name = (
                getattr(
                    company,
                    "plan",
                    "Free"
                )
                or "Free"
            )


        # ----------------------------------------------
        # USAGE
        # ----------------------------------------------

        if employee_limit:

            employee_usage_percentage = min(
                round(
                    (
                        company_employee_count
                        /
                        employee_limit
                    ) * 100
                ),
                100
            )

        else:

            employee_usage_percentage = 0



                # ====================================================
        # ADDITIVE: COMPANY-WISE HR SUMMARY
        # ====================================================

        company_today_attendance = company_attendance_today = (
            EMP_check_in_check_out.objects
            .filter(
                company=company,
                is_active=True,
                login_date=today,
            )
        )

        company_checkins_today = (
            company_attendance_today.count()
        )

        company_checked_out_today = company_checkouts_today = (
            company_attendance_today
            .exclude(logout_time__isnull=True)
            .exclude(logout_time="")
            .count()
        )

        company_pending_checkouts_today = max(
            company_checkins_today - company_checkouts_today,
            0,
        )

        company_leave_requests = LeaveRequest.objects.filter(
            company=company,
        )

        company_total_leave_requests = (
            company_leave_requests.count()
        )

        company_pending_leave_requests = (
            company_leave_requests
            .filter(status="Pending")
            .count()
        )

        company_payroll_cycles = PayrollCycle.objects.filter(
            company=company,
        )

        company_open_payroll_cycles = (
            company_payroll_cycles
            .filter(status="OPEN")
            .count()
        )

        company_current_month_payslips = Payslip.objects.filter(
            company=company,
            month=today.month,
            year=today.year,
            status="RELEASED",
        ).count()

        # Recruitment & HR telemetry per company
        try:
            from Recruitment.models import InterviewRound, JobRequisition
            c_interviews_today = InterviewRound.objects.filter(company=company, scheduled_at__date=today).count()
            c_pending_reqs = JobRequisition.objects.filter(company=company, approval_status__in=["Submitted", "Draft"]).count()
        except Exception:
            c_interviews_today = 0
            c_pending_reqs = 0

        c_ready_to_join = Candidate.objects.filter(
            company=company,
            candidate_status__in=["READY_TO_JOIN", "Ready To Join", "SELECTED", "Selected"]
        ).count()

        try:
            from People.models import ExitClearance
            c_notice_count = ExitClearance.objects.filter(
                company=company,
                is_active=True,
                status__in=["Serving Notice", "Under Clearance", "Initiated"]
            ).count()
            if c_notice_count == 0:
                c_notice_count = EmployeeDT.objects.filter(
                    company=company,
                    is_active=True
                ).exclude(
                    Current_Notice_Period__in=['', None, '0', 'None', 'NA', 'N/A']
                ).count()
        except Exception:
            c_notice_count = 0

        c_pending_approvals = company_pending_leave_requests + c_pending_reqs

        try:
            from Company.models import Holiday
            c_holidays_count = Holiday.objects.filter(company=company, is_active=True, date__gte=today).count()
        except Exception:
            c_holidays_count = 0

        try:
            from Employee.models import Department
            c_depts_count = Department.objects.filter(company=company, is_active=True).count()
            if c_depts_count == 0:
                c_depts_count = (
                    EmployeeDT.objects
                    .filter(company=company, is_active=True, Department__isnull=False)
                    .exclude(Department="")
                    .values("Department")
                    .distinct()
                    .count()
                )
        except Exception:
            c_depts_count = 0

        company_overview.append({

            "company":
                company,

            "employee_count":
                company_employee_count,

            "active_employee_count":
                company_active_employee_count,

            "inactive_employee_count":
                company_inactive_employee_count,

            "candidate_count":
                company_candidate_count,

            "applied_candidate_count":
                company_applied_count,

            "selected_candidate_count":
                company_selected_count,

            "employee_limit":
                employee_limit,

            "employee_usage_percentage":
                employee_usage_percentage,

            "package_name":
                package_name,

            # ADDITIVE: Attendance summary
            "today_attendance_count":
                company_today_attendance.count(),

            "checked_out_today_count":
                company_checked_out_today,

            # ADDITIVE: HR summary for dashboard template
            "hr_checkins_today":
                company_checkins_today,

            "hr_checkouts_today":
                company_checkouts_today,

            "hr_pending_checkouts_today":
                company_pending_checkouts_today,

            "hr_total_leave_requests":
                company_total_leave_requests,

            "hr_pending_leave_requests":
                company_pending_leave_requests,

            "hr_open_payroll_cycles":
                company_open_payroll_cycles,

            "hr_current_month_payslips":
                company_current_month_payslips,

            "interviews_today":
                c_interviews_today,

            "ready_to_join":
                c_ready_to_join,

            "on_notice_period":
                c_notice_count,

            "pending_approvals":
                c_pending_approvals,

            "holidays_count":
                c_holidays_count,

            "departments_count":
                c_depts_count,
        })



        company_selected_count = (
            company_candidate_qs
            .filter(
                candidate_status="SELECTED"
            )
            .count()
        )


        
        # Company-wise attendance statistics
        # Read-only Django ORM queries; no API calls.

        company_attendance = (
            EMP_check_in_check_out.objects
            .filter(company=company)
        )

        company_today_attendance = (
            company_attendance.filter(
                login_date=today
            )
        )

        company_checked_out_today = (
            company_today_attendance
            .exclude(logout_time__isnull=True)
            .exclude(logout_time="")
            .count()
        )






    # ========================================================
    # DASHBOARD CONTEXT
    # ========================================================

    context = {

        # ----------------------------------------------------
        # PLATFORM USER ACCOUNTS
        # ----------------------------------------------------

        "total_user_accounts": total_user_accounts,

        "active_user_accounts": active_user_accounts,

        "inactive_user_accounts": inactive_user_accounts,

        # ----------------------------------------------------
        # COMPANY
        # ----------------------------------------------------

        "total_companies":
            total_companies,

        "active_companies":
            active_companies,

        "trial_companies":
            trial_companies,

        "suspended_companies":
            suspended_companies,

        "inactive_companies":
            inactive_companies,

        "expired_companies":
            expired_companies,

        "companies":
            all_companies.order_by("Registered_Company_Name"),

        "selected_company":
            selected_company,

        "selected_company_id":
            str(selected_company.id) if selected_company else "",

                # ADDITIVE: HR summary
        "hr_checkins_today": hr_checkins_today,
        "hr_checkouts_today": hr_checkouts_today,
        "hr_pending_checkouts_today": (
            hr_pending_checkouts_today
        ),
        "hr_total_leave_requests": (
            hr_total_leave_requests
        ),
        "hr_pending_leave_requests": (
            hr_pending_leave_requests
        ),
        "hr_approved_leave_requests": (
            hr_approved_leave_requests
        ),
        "hr_open_payroll_cycles": (
            hr_open_payroll_cycles
        ),
        "hr_released_payroll_cycles": (
            hr_released_payroll_cycles
        ),
        "hr_active_headcount": hr_active_headcount,
        "hr_active_candidates": hr_active_candidates,
        "hr_interviews_today": hr_interviews_today,
        "hr_ready_to_join": hr_ready_to_join,
        "hr_on_notice_period": hr_on_notice_period,
        "hr_pending_approvals": hr_pending_approvals,
        "org_total_emp": org_total_emp,
        "org_leaders_count": org_leaders_count,
        "org_departments_count": org_departments_count,
        "org_teams_count": org_teams_count,
        "org_locations_count": org_locations_count,
        "upcoming_holidays": upcoming_holidays,
        "upcoming_interviews": upcoming_interviews,
        # Monthly Candidate Selections
        "report_month": report_month,
        "report_year": report_year,
        "monthly_selection_report": monthly_selection_report,

        

        "hr_current_month_payslips": (
            hr_current_month_payslips
        ),
        # ----------------------------------------------------
        # EMPLOYEES
        # ----------------------------------------------------

        "total_employees":
            total_employees,

        "active_employees":
            active_employees,

        "inactive_employees":
            inactive_employees,

        "disabled_employee_logins":
            disabled_employee_logins,


        # ----------------------------------------------------
        # CANDIDATES
        # ----------------------------------------------------

        "total_candidates":
            total_candidates,

        "applied_candidates":
            applied_candidates,

        "shortlisted_candidates":
            shortlisted_candidates,

        "interview_candidates":
            interview_candidates,

        "selected_candidates":
            selected_candidates,

        "offered_candidates":
            offered_candidates,

        "rejected_candidates":
            rejected_candidates,

        "hired_candidates":
            hired_candidates,


        # ----------------------------------------------------
        # ADMINS
        # ----------------------------------------------------

        "total_admins":
            total_admins,

        "active_admins":
            active_admins,

        "inactive_admins":
            inactive_admins,


        # ----------------------------------------------------
        # SUBSCRIPTIONS
        # ----------------------------------------------------

        "expiring_soon":
            expiring_soon,


        # ----------------------------------------------------
        # AUDIT
        # ----------------------------------------------------

        "recent_audit_logs":
            recent_audit_logs,


        # ----------------------------------------------------
        # PLANS
        # ----------------------------------------------------

        "plan_counts":
            plan_counts,


        # ----------------------------------------------------
        # COMPANY OVERVIEW
        # ----------------------------------------------------

        "company_overview":
            company_overview,
    }


    

    # ========================================================
    # RENDER
    # ========================================================

    return render(
        request,
        "superadmin/dashboard.html",
        context
    )

# ============================================================
# ============================================================
# ADDITIVE: HR INTELLIGENCE JSON API (HR SIDE DATA IN SUPERADMIN)
# ============================================================

@superadmin_required
def superadmin_hr_intelligence_api(request):
    """
    GET /portal/api/hr-intelligence/?company=<id>
    Returns all workforce, recruitment, holiday and interview data
    as live JSON matching the HR Intelligence dashboard.
    """
    today = timezone.localdate()
    selected_company_id = request.GET.get("company_id") or request.GET.get("company")
    selected_company = None
    if selected_company_id and str(selected_company_id).lower() not in ["all", "", "none"]:
        try:
            selected_company = company_details.objects.filter(
                Q(id=selected_company_id) if str(selected_company_id).isdigit() else Q(company_id=selected_company_id)
            ).first()
        except Exception:
            selected_company = None
    _c_filter = {"company": selected_company} if selected_company else {}

    active_headcount = EmployeeDT.objects.filter(is_active=True, **_c_filter).count()
    active_cands = (
        Candidate.objects
        .filter(**_c_filter)
        .exclude(candidate_status__in=["REJECTED", "HIRED", "JOINED", "Rejected", "Hired", "Joined"])
        .count()
    )

    try:
        from Recruitment.models import InterviewRound, JobRequisition
        interviews_today = InterviewRound.objects.filter(scheduled_at__date=today, **_c_filter).count()
        upcoming_interviews = (
            InterviewRound.objects.filter(**_c_filter)
            .filter(scheduled_at__date__gte=today, **_c_filter)
            .select_related("candidate", "company", "interviewer")
            .order_by("scheduled_at")[:20]
        )
        pending_reqs = JobRequisition.objects.filter(approval_status__in=["Submitted", "Draft"], **_c_filter).count()
    except Exception:
        interviews_today = 0
        upcoming_interviews = []
        pending_reqs = 0

    ready_to_join = Candidate.objects.filter(
        candidate_status__in=["READY_TO_JOIN", "Ready To Join", "SELECTED", "Selected"],
        **_c_filter
    ).count()

    try:
        from People.models import ExitClearance
        notice_count = ExitClearance.objects.filter(
            is_active=True, status__in=["Serving Notice", "Under Clearance", "Initiated"],
            **_c_filter
        ).count()
        if notice_count == 0:
            notice_count = EmployeeDT.objects.filter(is_active=True, **_c_filter).exclude(
                Current_Notice_Period__in=['', None, '0', 'None', 'NA', 'N/A']
            ).count()
    except Exception:
        notice_count = 0

    pending_leaves = LeaveRequest.objects.filter(status="Pending", **_c_filter).count()
    pending_approvals = pending_leaves + pending_reqs

    try:
        from Employee.models import Department
        from People.models import Branch, EmployeeExtra
        org_depts = Department.objects.filter(is_active=True, **_c_filter).count()
        if org_depts == 0:
            org_depts = (
                EmployeeDT.objects
                .filter(is_active=True, Department__isnull=False, **_c_filter)
                .exclude(Department="")
                .values("Department")
                .distinct()
                .count()
            )
        lead_qs = EmployeeExtra.objects.filter(reporting_manager__isnull=False, **_c_filter)
        leader_ids = set(lead_qs.values_list("reporting_manager_id", flat=True))
        org_leaders = len(leader_ids)
        if org_leaders == 0:
            org_leaders = EmployeeDT.objects.filter(
                is_active=True, **_c_filter
            ).filter(
                Q(Designation__icontains="Lead") | Q(Designation__icontains="Manager") |
                Q(Designation__icontains="Head") | Q(Designation__icontains="Director")
            ).count()
        if org_leaders == 0:
            org_leaders = CompanyAdmin.objects.filter(is_active=True, **_c_filter).count() or (1 if selected_company else company_details.objects.count())

        org_teams = (
            EmployeeDT.objects
            .filter(is_active=True, team_Department__isnull=False, **_c_filter)
            .exclude(team_Department="")
            .values("team_Department")
            .distinct()
            .count()
            or org_depts
        )
        org_locations = Branch.objects.filter(is_active=True, **_c_filter).count() or (1 if selected_company else company_details.objects.count())
    except Exception:
        org_depts = 0
        org_leaders = 1
        org_teams = 0
        org_locations = 1

    try:
        from Company.models import Holiday
        upcoming_hols = (
            Holiday.objects
            .filter(is_active=True, date__gte=today, **_c_filter)
            .select_related("company")
            .order_by("date")[:20]
        )
    except Exception:
        upcoming_hols = []

    _base_att = (EMP_check_in_check_out.objects.filter(company=selected_company) if selected_company else EMP_check_in_check_out.objects)
    hr_attendance_today = _base_att.filter(
        login_date=today,
    ).exclude(is_active=False)
    checkins_today = hr_attendance_today.count()
    checkouts_today = (
        hr_attendance_today
        .exclude(logout_time__isnull=True)
        .exclude(logout_time="")
        .count()
    )

    data = {
        "status": "SUCCESS",
        "date": today.strftime("%Y-%m-%d"),
        "filter": getattr(selected_company, "Registered_Company_Name", "All Companies"),
        "kpis": {
            "active_headcount": active_headcount,
            "active_candidates": active_cands,
            "interviews_today": interviews_today,
            "ready_to_join": ready_to_join,
            "on_notice_period": notice_count,
            "pending_approvals": pending_approvals,
        },
        "telemetry": {
            "checkins_today": checkins_today,
            "checkouts_today": checkouts_today,
            "pending_checkouts_today": max(checkins_today - checkouts_today, 0),
            "pending_leaves": pending_leaves,
            "pending_requisitions": pending_reqs,
        },
        "org_structure": {
            "total_employees": active_headcount,
            "leaders": org_leaders,
            "departments": org_depts,
            "teams": org_teams,
            "locations": org_locations,
        },
        "holidays": [
            {
                "id": h.id,
                "name": h.name,
                "date": h.date.strftime("%Y-%m-%d"),
                "day": h.date.strftime("%A"),
                "company": getattr(h.company, "Registered_Company_Name", "") or getattr(h.company, "Brand_Name", "") or "All",
                "type": getattr(h, "holiday_type", "Company"),
            }
            for h in upcoming_hols
        ],
        "interviews": [
            {
                "id": i.id,
                "interview_id": i.interview_id,
                "candidate_name": i.candidate.name if i.candidate else "Candidate",
                "candidate_code": getattr(i.candidate, "candidate_id", None) or getattr(i.candidate, "employee_code", ""),
                "round_name": i.round_name,
                "interviewer_name": i.interviewer.name if i.interviewer else "Assigned",
                "scheduled_at": i.scheduled_at.strftime("%d %b %Y, %I:%M %p") if i.scheduled_at else None,
                "mode": i.mode or "Online",
                "status": i.status,
                "company": getattr(i.company, "Registered_Company_Name", "") or "Company",
            }
            for i in upcoming_interviews
        ],
    }
    return JsonResponse(data)


# ============================================================
def _unused_old_hr_api():
    """
    GET /portal/api/hr-intelligence/
    Returns all workforce, recruitment, holiday and interview data
    as live JSON matching the HR Intelligence dashboard.
    """
    today = timezone.localdate()

    active_headcount = EmployeeDT.objects.filter(is_active=True).count()
    active_cands = (
        Candidate.objects
        .exclude(candidate_status__in=["REJECTED", "HIRED", "JOINED", "Rejected", "Hired", "Joined"])
        .count()
    )

    try:
        from Recruitment.models import InterviewRound, JobRequisition
        interviews_today = InterviewRound.objects.filter(scheduled_at__date=today).count()
        upcoming_interviews = (
            InterviewRound.objects
            .filter(scheduled_at__date__gte=today)
            .select_related("candidate", "company", "interviewer")
            .order_by("scheduled_at")[:20]
        )
        pending_reqs = JobRequisition.objects.filter(approval_status__in=["Submitted", "Draft"]).count()
    except Exception:
        interviews_today = 0
        upcoming_interviews = []
        pending_reqs = 0

    ready_to_join = Candidate.objects.filter(
        candidate_status__in=["READY_TO_JOIN", "Ready To Join", "SELECTED", "Selected"]
    ).count()

    try:
        from People.models import ExitClearance
        notice_count = ExitClearance.objects.filter(
            is_active=True, status__in=["Serving Notice", "Under Clearance", "Initiated"]
        ).count()
        if notice_count == 0:
            notice_count = EmployeeDT.objects.filter(is_active=True).exclude(
                Current_Notice_Period__in=['', None, '0', 'None', 'NA', 'N/A']
            ).count()
    except Exception:
        notice_count = 0

    pending_leaves = LeaveRequest.objects.filter(status="Pending").count()
    pending_approvals = pending_leaves + pending_reqs

    try:
        from Employee.models import Department
        from People.models import Branch
        org_depts = Department.objects.filter(is_active=True).count()
        org_leaders = CompanyAdmin.objects.filter(is_active=True).count()
        org_teams = (
            EmployeeDT.objects
            .filter(is_active=True, team_Department__isnull=False, **_c_filter)
            .exclude(team_Department="")
            .values("team_Department")
            .distinct()
            .count()
            or org_depts
        )
        org_locations = Branch.objects.filter(is_active=True).count() or company_details.objects.count()
    except Exception:
        org_depts = 0
        org_leaders = 0
        org_teams = 0
        org_locations = 0

    try:
        from Company.models import Holiday
        upcoming_hols = (
            Holiday.objects
            .filter(is_active=True, date__gte=today, **_c_filter)
            .select_related("company")
            .order_by("date")[:20]
        )
    except Exception:
        upcoming_hols = []

    _base_att = (EMP_check_in_check_out.objects.filter(company=selected_company) if selected_company else EMP_check_in_check_out.objects)
    hr_attendance_today = _base_att.filter(
        login_date=today,
    ).exclude(is_active=False)
    checkins_today = hr_attendance_today.count()
    checkouts_today = (
        hr_attendance_today
        .exclude(logout_time__isnull=True)
        .exclude(logout_time="")
        .count()
    )

    data = {
        "status": "SUCCESS",
        "date": today.strftime("%Y-%m-%d"),
        "kpis": {
            "active_headcount": active_headcount,
            "active_candidates": active_cands,
            "interviews_today": interviews_today,
            "ready_to_join": ready_to_join,
            "on_notice_period": notice_count,
            "pending_approvals": pending_approvals,
        },
        "telemetry": {
            "checkins_today": checkins_today,
            "checkouts_today": checkouts_today,
            "pending_checkouts_today": max(checkins_today - checkouts_today, 0),
            "pending_leaves": pending_leaves,
            "pending_requisitions": pending_reqs,
        },
        "org_structure": {
            "total_employees": active_headcount,
            "leaders": org_leaders,
            "departments": org_depts,
            "teams": org_teams,
            "locations": org_locations,
        },
        "holidays": [
            {
                "id": h.id,
                "name": h.name,
                "date": h.date.strftime("%Y-%m-%d"),
                "day": h.date.strftime("%A"),
                "company": getattr(h.company, "Registered_Company_Name", "") or getattr(h.company, "Brand_Name", "") or "All",
                "type": getattr(h, "holiday_type", "Company"),
            }
            for h in upcoming_hols
        ],
        "interviews": [
            {
                "id": i.id,
                "interview_id": i.interview_id,
                "candidate_name": i.candidate.name if i.candidate else "Candidate",
                "candidate_code": getattr(i.candidate, "candidate_id", None) or getattr(i.candidate, "employee_code", ""),
                "round_name": i.round_name,
                "interviewer_name": i.interviewer.name if i.interviewer else "Assigned",
                "scheduled_at": i.scheduled_at.strftime("%d %b %Y, %I:%M %p") if i.scheduled_at else None,
                "mode": i.mode or "Online",
                "status": i.status,
                "company": getattr(i.company, "Registered_Company_Name", "") or "Company",
            }
            for i in upcoming_interviews
        ],
    }
    return JsonResponse(data)


# ============================================================
# COMPANY LIST
# ============================================================

@superadmin_required
def superadmin_companies(request):

    # --------------------------------------------------------
    # SEARCH
    # --------------------------------------------------------

    search = request.GET.get(
        "search",
        ""
    ).strip()

    # --------------------------------------------------------
    # STATUS
    # --------------------------------------------------------

    selected_status = request.GET.get(
        "status",
        ""
    ).strip()

    # --------------------------------------------------------
    # PLAN
    # --------------------------------------------------------

    selected_plan = request.GET.get(
        "plan",
        ""
    ).strip()

    # ========================================================
    # COMPANY QUERY
    # ========================================================
    #
    # IMPORTANT:
    # employee_count counts ONLY EmployeeDT records that
    # have an EmployeeAccount.
    #
    # Candidate/recruitment records without an account
    # are therefore excluded.
    # ========================================================

    companies = (
        company_details.objects
        .annotate(
            employee_count=Count(
                "employees__account",
                distinct=True
            )
        )
        .order_by("-id")
    )

    # ========================================================
    # SEARCH
    # ========================================================

    if search:

        companies = companies.filter(

            Q(
                company_id__icontains=search
            )

            |

            Q(
                Registered_Company_Name__icontains=search
            )

            |

            Q(
                Brand_Name__icontains=search
            )

            |

            Q(
                Company_Official_Email__icontains=search
            )

            |

            Q(
                Industry_Type__icontains=search
            )

        )

    # ========================================================
    # STATUS FILTER
    # ========================================================

    if selected_status:

        companies = companies.filter(
            company_status=selected_status
        )

    # ========================================================
    # PLAN FILTER
    # ========================================================

    if selected_plan:

        companies = companies.filter(
            plan=selected_plan
        )

    # ========================================================
    # PLATFORM STATISTICS
    # ========================================================

    all_companies = company_details.objects.all()

    # --------------------------------------------------------
    # TOTAL COMPANIES
    # --------------------------------------------------------

    total_companies = (
        all_companies.count()
    )

    # --------------------------------------------------------
    # ACTIVE COMPANIES
    # --------------------------------------------------------

    active_companies = (
        all_companies
        .filter(
            company_status="ACTIVE"
        )
        .count()
    )

    # --------------------------------------------------------
    # TOTAL REAL EMPLOYEES
    # --------------------------------------------------------
    #
    # EmployeeAccount represents a real employee login/account.
    #
    # The 33 candidate/recruitment EmployeeDT records do not
    # have an EmployeeAccount, so they are excluded.
    # --------------------------------------------------------

    total_employees = (
        EmployeeAccount.objects
        .filter(
            employee__is_active=True,
            is_active=True,
        )
        .count()
    )

    # ========================================================
    # CONTEXT
    # ========================================================

    # ADDITIVE: pending recruitment candidates per company
    from .views_b2b import pending_candidates_qs
    _cand_ids = pending_candidates_qs().values("pk")
    _cand_counts = {
        row["company_id"]: row["n"]
        for row in _cand_ids.model.objects.filter(pk__in=_cand_ids)
        .values("company_id").annotate(n=Count("id"))
    }
    companies = list(companies)
    for _c in companies:
        _c.candidate_count = _cand_counts.get(_c.pk, 0)

    context = {

        "companies":
            companies,

        "search":
            search,

        "selected_status":
            selected_status,

        "selected_plan":
            selected_plan,

        "status_choices":
            company_details.COMPANY_STATUS_CHOICES,

        "plan_choices":
            company_details.PLAN_CHOICES,

        "total_companies":
            total_companies,

        "active_companies":
            active_companies,

        "total_employees":
            total_employees,

    }

    # ========================================================
    # RENDER
    # ========================================================

    return render(
        request,
        "superadmin/companies.html",
        context
    )


# ============================================================
# COMPANY DETAIL
# ============================================================

@superadmin_required
def superadmin_company_detail(
    request,
    company_id
):

    company = get_object_or_404(
        company_details,
        id=company_id
    )

    usage, created = CompanyUsage.objects.get_or_create(
        company=company
    )

    usage.refresh()

    employees = (
        EmployeeDT.objects
        .filter(company=company)
        .order_by('-id')[:20]
    )

    admins = (
        CompanyAdmin.objects
        .filter(company=company)
        .select_related('user', 'employee')
        .order_by('-id')
    )

    # FIX: 'selected_company' is not defined in this view (NameError -> 500).
    # Original line kept below as a comment; this page is already scoped to `company`.
    # subscriptions = (CompanySubscription.objects.filter(company=selected_company, is_active=True) if selected_company else CompanySubscription.objects.filter(is_active=True))
    subscriptions = CompanySubscription.objects.filter(company=company, is_active=True)
    _unused_old_subs = (
        CompanySubscription.objects
        .filter(company=company)
        .order_by('-created_at')[:10]
    )

    audit_logs = (
        SuperAdminAuditLog.objects
        .filter(company=company)
        .select_related('superadmin')
        .order_by('-created_at')[:20]
    )

    employee_percentage = 0

    if company.employee_limit:

        employee_percentage = min(
            100,
            round(
                usage.total_employees /
                company.employee_limit *
                100
            )
        )

    admin_percentage = 0

    if company.admin_limit:

        admin_percentage = min(
            100,
            round(
                usage.total_admins /
                company.admin_limit *
                100
            )
        )

    context = {

        'company': company,

        'usage': usage,

        'employees': employees,

        'admins': admins,

        'subscriptions': subscriptions,

        'audit_logs': audit_logs,

        'employee_percentage':
            employee_percentage,

        'admin_percentage':
            admin_percentage,

        'status_choices':
            company_details.COMPANY_STATUS_CHOICES,

        'plan_choices':
            company_details.PLAN_CHOICES,
    }

    return render(
        request,
        'superadmin/company_detail.html',
        context
    )


# ============================================================
# COMPANY STATUS
# ============================================================

@require_POST
@superadmin_required
def superadmin_company_status(
    request,
    company_id
):

    company = get_object_or_404(
        company_details,
        id=company_id
    )

    new_status = request.POST.get(
        'company_status'
    )

    valid_statuses = dict(
        company_details.COMPANY_STATUS_CHOICES
    )

    if new_status not in valid_statuses:

        messages.error(
            request,
            "Invalid company status."
        )

        return redirect(
            'superadmin_company_detail',
            company_id=company.id
        )

    old_status = company.company_status

    company.company_status = new_status

    company.status = (
        new_status in ['ACTIVE', 'TRIAL']
    )

    company.company_status = new_status

    company.status = (
        new_status in ['ACTIVE', 'TRIAL']
    )

    company.save(
        update_fields=[
            'company_status',
            'status'
        ]
    )

    action_map = {

        'ACTIVE':
            'ACTIVATE_COMPANY',

        'INACTIVE':
            'DEACTIVATE_COMPANY',

        'SUSPENDED':
            'SUSPEND_COMPANY',

        'TRIAL':
            'OTHER',

        'EXPIRED':
            'OTHER',
    }

    try:

        SuperAdminAuditLog.objects.create(

            superadmin=request.superadmin_profile,

            company=company,

            action=action_map.get(
                new_status,
                'OTHER'
            ),

            description=(
                f"Company status changed "
                f"from {old_status} "
                f"to {new_status}."
            ),

            ip_address=(
                request.META.get(
                    'REMOTE_ADDR'
                )
            )
        )

    except Exception:
        pass

    messages.success(
        request,
        f"Company status changed to {new_status}."
    )

    return redirect(
        'superadmin_company_detail',
        company_id=company.id
    )


# ============================================================
# COMPANY SUBSCRIPTION
# ============================================================

@require_POST
@superadmin_required
def superadmin_company_subscription(
    request,
    company_id
):

    company = get_object_or_404(
        company_details,
        id=company_id
    )

    plan = request.POST.get(
        'plan'
    )

    valid_plans = dict(
        company_details.PLAN_CHOICES
    )

    if plan not in valid_plans:

        messages.error(
            request,
            "Invalid subscription plan."
        )

        return redirect(
            'superadmin_company_detail',
            company_id=company.id
        )

    try:

        employee_limit = int(
            request.POST.get(
                'employee_limit',
                company.employee_limit
            )
        )

        admin_limit = int(
            request.POST.get(
                'admin_limit',
                company.admin_limit
            )
        )

        hr_limit = int(
            request.POST.get(
                'hr_limit',
                company.hr_limit
            )
        )

        device_limit = int(
            request.POST.get(
                'device_limit',
                company.device_limit
            )
        )

        amount = request.POST.get(
            'amount',
            '0'
        )

        end_date = request.POST.get(
            'end_date'
        ) or None

    except (TypeError, ValueError):

        messages.error(
            request,
            "Please enter valid numeric limits."
        )

        return redirect(
            'superadmin_company_detail',
            company_id=company.id
        )

    if min(
        employee_limit,
        admin_limit,
        hr_limit,
        device_limit
    ) < 0:

        messages.error(
            request,
            "Limits cannot be negative."
        )

        return redirect(
            'superadmin_company_detail',
            company_id=company.id
        )

    today = timezone.localdate()

    CompanySubscription.objects.filter(
        company=company,
        is_active=True
    ).update(
        is_active=False
    )

    subscription = CompanySubscription.objects.create(

        company=company,

        plan=plan,

        employee_limit=employee_limit,

        admin_limit=admin_limit,

        device_limit=device_limit,

        start_date=today,

        end_date=end_date,

        amount=amount,

        is_active=True
    )

    company.plan = plan

    company.employee_limit = employee_limit

    company.admin_limit = admin_limit

    company.hr_limit = hr_limit

    company.device_limit = device_limit

    company.subscription_start_date = today

    company.subscription_end_date = end_date

    company.save()

    try:

        SuperAdminAuditLog.objects.create(

            superadmin=request.superadmin_profile,

            company=company,

            action='UPDATE_COMPANY',

            description=(
                f"Subscription updated to "
                f"{plan}. "
                f"Employee limit: "
                f"{employee_limit}, "
                f"Admin limit: "
                f"{admin_limit}, "
                f"HR limit: "
                f"{hr_limit}, "
                f"Device limit: "
                f"{device_limit}."
            ),

            ip_address=request.META.get(
                'REMOTE_ADDR'
            )
        )

    except Exception:
        pass

    messages.success(
        request,
        "Subscription updated successfully."
    )

    return redirect(
        'superadmin_company_detail',
        company_id=company.id
    )


# ============================================================
# COMPANY ADMINS
# ============================================================

@superadmin_required
def superadmin_admins(request):

    admins = (
        CompanyAdmin.objects
        .select_related(
            'company',
            'user',
            'employee'
        )
        .order_by('-id')
    )

    search = request.GET.get(
        'search',
        ''
    ).strip()

    if search:

        admins = admins.filter(

            Q(admin_name__icontains=search) |

            Q(email__icontains=search) |

            Q(company__Registered_Company_Name__icontains=search) |

            Q(company__Brand_Name__icontains=search)
        )

    context = {

        'admins': admins,

        'search': search,
    }

    return render(
        request,
        'superadmin/admins.html',
        context
    )


@superadmin_required
def superadmin_employees(request):

    # ========================================================
    # REAL EMPLOYEES ONLY
    # ========================================================
    #
    # EmployeeAccount identifies a real employee.
    #
    # Old EmployeeDT records without an EmployeeAccount
    # are legacy candidate/recruitment records and are
    # intentionally excluded from this page.
    # ========================================================

    employees = (
        EmployeeDT.objects
        .select_related("company", "account")
        .order_by("-id")
    )

    # Normal list = real employees (with login account).
    # Inactive list = every inactive record, same as Django admin.
    if request.GET.get("status", "").strip() not in ("inactive", "candidates", "all"):  # ADDITIVE: candidates/all
        employees = employees.filter(account__isnull=False)

    # ========================================================
    # FILTERS
    # ========================================================

    search = request.GET.get(
        "search",
        ""
    ).strip()

    company_id = request.GET.get(
        "company",
        ""
    ).strip()

    status = request.GET.get(
        "status",
        ""
    ).strip()

    # ========================================================
    # SEARCH
    # ========================================================

    if search:

        employees = employees.filter(

            Q(
                name__icontains=search
            )

            |

            Q(
                email__icontains=search
            )

            |

            Q(
                employee_code__icontains=search
            )

            |

            Q(
                company__Registered_Company_Name__icontains=search
            )

            |

            Q(
                company__Brand_Name__icontains=search
            )
        )

    # ========================================================
    # COMPANY FILTER
    # ========================================================

    if company_id:

        employees = employees.filter(
            company_id=company_id
        )

    # ========================================================
    # STATUS FILTER
    # ========================================================

    if status == "active":

        employees = employees.filter(
            is_active=True
        )

    elif status == "inactive":

        employees = employees.filter(
            is_active=False
        )

    # ========================================================
    # ADDITIVE: show recruitment candidates on this page too
    #   status=candidates -> only pending candidates
    #   status=all        -> employees + candidates
    # (same candidate rule the company HR panel uses)
    # ========================================================
    from .views_b2b import pending_candidates_qs
    _pending_candidate_ids = (
        pending_candidates_qs()
        .values("pk")
    )
    if status == "candidates":
        employees = employees.filter(pk__in=_pending_candidate_ids)

    # ========================================================
    # ALL COMPANIES
    # ========================================================

    companies = (
        company_details.objects
        .all()
        .order_by(
            "Registered_Company_Name"
        )
    )

    # ========================================================
    # REAL EMPLOYEE COUNTS
    # ========================================================

    total_employees = employees.count()

    active_employees = (
        employees
        .filter(
            is_active=True
        )
        .count()
    )

    inactive_employees = (
        employees
        .filter(
            is_active=False
        )
        .count()
    )

    # ========================================================
    # COMPANY-WISE EMPLOYEE GROUPS
    # ========================================================


    # ADDITIVE: pending candidates per company (for the header chip)
    cand_counts = {
        row["company_id"]: row["n"]
        for row in _pending_candidate_ids.model.objects
        .filter(pk__in=_pending_candidate_ids)
        .values("company_id")
        .annotate(n=Count("id"))
    }

    company_groups = []

    for company in companies:

        # ----------------------------------------------------
        # PACKAGE
        # ----------------------------------------------------

        package = sync_company_package_limit(
            company
        )

        employee_limit = package.get(
            "employee_limit",
            getattr(
                company,
                "employee_limit",
                0
            )
        )

        # ----------------------------------------------------
        # REAL EMPLOYEES OF THIS COMPANY
        # ----------------------------------------------------

        company_employees = (
            employees
            .filter(
                company_id=company.id
            )
        )

        employee_count = (
            company_employees.count()
        )

        # ----------------------------------------------------
        # USAGE
        # ----------------------------------------------------

        if employee_limit:

            usage_percentage = min(
                100,
                round(
                    (
                        employee_count
                        /
                        employee_limit
                    )
                    * 100
                )
            )

        else:

            usage_percentage = 0

        # ----------------------------------------------------
        # AVAILABLE SLOTS
        # ----------------------------------------------------

        available_slots = max(
            employee_limit
            -
            employee_count,
            0
        )

        # ----------------------------------------------------
        # LIMIT STATUS
        # ----------------------------------------------------

        limit_reached = (
            employee_count
            >=
            employee_limit
            if employee_limit
            else False
        )

        over_limit = (
            employee_count
            >
            employee_limit
            if employee_limit
            else False
        )

        # ----------------------------------------------------
        # COMPANY GROUP
        # ----------------------------------------------------

        company_groups.append({

            "company":
                company,

            "employees":
                company_employees,

            "count":
                employee_count,

            "limit":
                employee_limit,

            "available":
                available_slots,

            "package":
                package,

            "usage_percentage":
                usage_percentage,

            "limit_reached":
                limit_reached,

            "over_limit":
                over_limit,
            "candidate_count":
                cand_counts.get(company.id, 0),
        })

    # ========================================================
    # CONTEXT
    # ========================================================

    context = {

        "employees":
            employees,

        "companies":
            companies,

        "company_groups":
            company_groups,

        "search":
            search,

        "selected_company":
            company_id,

        "selected_status":
            status,

        "total_employees":
            total_employees,

        "active_employees":
            active_employees,

        "inactive_employees":
            inactive_employees,
    }

    return render(
        request,
        "superadmin/employees.html",
        context
    )
# ============================================================
# ADD EMPLOYEE
# ============================================================
@superadmin_required
@transaction.atomic
def superadmin_employee_add(request):

    companies = (
        company_details.objects
        .all()
        .order_by("Registered_Company_Name")
    )

    if request.method != "POST":

        return render(
            request,
            "superadmin/employee_form.html",
            {
                "companies": companies,
                "form_data": {},
                "editing": False,
                "limit_reached": False,
            }
        )

    # ========================================================
    # READ FORM DATA
    # ========================================================

    company_id = request.POST.get(
        "company",
        ""
    ).strip()

    name = request.POST.get(
        "name",
        ""
    ).strip()

    email = request.POST.get(
        "email",
        ""
    ).strip()

    employee_code = request.POST.get(
        "employee_code",
        ""
    ).strip()

    # Checkbox/toggle can submit either 1, true, on, etc.
    is_active = request.POST.get(
        "is_active",
        "0"
    ) in ["1", "true", "True", "on", "yes"]

    # ========================================================
    # VALIDATION
    # ========================================================

    if not company_id:

        messages.error(
            request,
            "Please select a company."
        )

        return render(
            request,
            "superadmin/employee_form.html",
            {
                "companies": companies,
                "form_data": request.POST,
                "editing": False,
            }
        )

    if not name:

        messages.error(
            request,
            "Employee name is required."
        )

        return render(
            request,
            "superadmin/employee_form.html",
            {
                "companies": companies,
                "form_data": request.POST,
                "editing": False,
            }
        )

    if not email:

        messages.error(
            request,
            "Employee email is required."
        )

        return render(
            request,
            "superadmin/employee_form.html",
            {
                "companies": companies,
                "form_data": request.POST,
                "editing": False,
            }
        )

    try:

        # ====================================================
        # COMPANY
        # ====================================================

        company = get_object_or_404(
            company_details,
            id=company_id
        )

        # ====================================================
        # PACKAGE LIMIT
        # ====================================================

        package = sync_company_package_limit(
            company
        )

        employee_limit = package.get(
            "employee_limit",
            0
        )

        # ====================================================
        # REAL EMPLOYEE COUNT
        # EmployeeAccount = real employee
        # ====================================================

        current_employee_count = (
            EmployeeAccount.objects
            .filter(
                employee__company=company,
                employee__is_active=True,
                is_active=True,
            )
            .count()
        )

        # ====================================================
        # PACKAGE CHECK
        # ====================================================

        if (
            is_active
            and employee_limit
            and current_employee_count >= employee_limit
        ):

            messages.error(
                request,
                (
                    f"Employee limit reached for "
                    f"{company.Brand_Name or company.Registered_Company_Name}. "
                    f"Current employees: "
                    f"{current_employee_count}. "
                    f"Package limit: "
                    f"{employee_limit}. "
                    f"Please upgrade the company package."
                )
            )

            return render(
                request,
                "superadmin/employee_form.html",
                {
                    "companies": companies,
                    "form_data": request.POST,
                    "editing": False,
                    "selected_company": company.id,
                    "employee_count": current_employee_count,
                    "employee_limit": employee_limit,
                    "package": package,
                    "limit_reached": True,
                }
            )

        # ====================================================
        # DUPLICATE EMAIL
        # ====================================================

        existing_employee = (
            EmployeeDT.objects
            .filter(
                email__iexact=email
            )
            .first()
        )

        if existing_employee:

            messages.error(
                request,
                (
                    f"Employee email already exists. "
                    f"Employee: {existing_employee.name}, "
                    f"Company: "
                    f"{existing_employee.company.Brand_Name or existing_employee.company.Registered_Company_Name}."
                )
            )

            return render(
                request,
                "superadmin/employee_form.html",
                {
                    "companies": companies,
                    "form_data": request.POST,
                    "editing": False,
                    "selected_company": company.id,
                }
            )

        # ====================================================
        # DUPLICATE EMPLOYEE CODE
        # ====================================================

        if employee_code:

            if EmployeeDT.objects.filter(
                employee_code=employee_code
            ).exists():

                messages.error(
                    request,
                    "Employee code already exists."
                )

                return render(
                    request,
                    "superadmin/employee_form.html",
                    {
                        "companies": companies,
                        "form_data": request.POST,
                        "editing": False,
                        "selected_company": company.id,
                    }
                )

        # ====================================================
        # CREATE EMPLOYEE
        # ====================================================

        employee = EmployeeDT()

        employee.company = company

        employee.name = name

        employee.email = email

        employee.is_active = is_active

        employee.candidate_status = "JOINED"

        employee.Employee_Status = (
            "Activate"
            if is_active
            else "Deactivate"
        )

        if employee_code:

            employee.employee_code = (
                employee_code
            )

        employee.save()

        # ====================================================
        # CREATE / GET EMPLOYEE ROLE
        # ====================================================

        role, created_role = (
            EmployeeRole.objects.get_or_create(

                company=company,

                role_code="EMPLOYEE",

                defaults={
                    "role_name": "Employee"
                }
            )
        )

        # ====================================================
        # CREATE EMPLOYEE LOGIN ACCOUNT
        # ====================================================

        EmployeeAccount.objects.create(

            employee=employee,

            role=role,

            is_login_enabled=is_active,

            is_verified=False,

            is_active=is_active,

            failed_login_attempts=0,
        )

        # ====================================================
        # AUDIT LOG
        # ====================================================

        try:

            SuperAdminAuditLog.objects.create(

                superadmin=
                    request.superadmin_profile,

                company=company,

                action="OTHER",

                description=(
                    f"Created employee "
                    f"{employee.name} "
                    f"({employee.employee_code}) "
                    f"under "
                    f"{company.Brand_Name or company.Registered_Company_Name}"
                ),

                ip_address=
                    request.META.get(
                        "REMOTE_ADDR"
                    ),
            )

        except Exception:

            # Audit failure must not prevent employee creation.
            pass

        # ====================================================
        # SUCCESS
        # ====================================================

        messages.success(
            request,
            (
                f"Employee {employee.name} "
                f"was created successfully under "
                f"{company.Brand_Name or company.Registered_Company_Name}."
            )
        )
        messages.success(
            request,
            f"Employee {employee.name} was created successfully..."
        )

        return redirect(
            "superadmin_employees"
        )

    except Exception as exc:

        # ====================================================
        # IMPORTANT
        # SHOW ACTUAL DATABASE ERROR
        # ====================================================

        messages.error(
            request,
            (
                "Employee could not be created. "
                f"Backend error: {str(exc)}"
            )
        )

        return render(
            request,
            "superadmin/employee_form.html",
            {
                "companies": companies,
                "form_data": request.POST,
                "editing": False,
                "selected_company": company_id,
            }
        )
# ============================================================
# EDIT EMPLOYEE
# ============================================================

@superadmin_required
def superadmin_employee_edit(
    request,
    employee_id
):

    employee = get_object_or_404(
        EmployeeDT,
        id=employee_id
    )

    companies = (
        company_details.objects
        .all()
        .order_by(
            "Registered_Company_Name"
        )
    )

    if request.method == "POST":

        company_id = request.POST.get(
            "company"
        )

        name = request.POST.get(
            "name",
            ""
        ).strip()

        email = request.POST.get(
            "email",
            ""
        ).strip()

        employee_code = request.POST.get(
            "employee_code",
            ""
        ).strip()

        is_active = (
            request.POST.get("is_active")
            == "1"
        )

        # ----------------------------------------------------
        # VALIDATION
        # ----------------------------------------------------

        if not company_id:

            messages.error(
                request,
                "Please select a company."
            )

        elif not name:

            messages.error(
                request,
                "Employee name is required."
            )

        elif not email:

            messages.error(
                request,
                "Employee email is required."
            )

        else:

            company = get_object_or_404(
                company_details,
                id=company_id
            )

            # ------------------------------------------------
            # CHECK EMPLOYEE CODE
            # ------------------------------------------------

            if employee_code:

                duplicate = (
                    EmployeeDT.objects
                    .filter(
                        employee_code=employee_code
                    )
                    .exclude(
                        id=employee.id
                    )
                    .exists()
                )

                if duplicate:

                    messages.error(
                        request,
                        "Employee code already exists."
                    )

                    return render(
                        request,
                        "superadmin/employee_form.html",
                        {
                            "employee": employee,
                            "companies": companies,
                            "form_data": request.POST,
                            "editing": True,
                        }
                    )


            # ------------------------------------------------
            # CHECK EMAIL
            # ------------------------------------------------

            duplicate_email = (
                EmployeeDT.objects
                .filter(email__iexact=email)
                .exclude(id=employee.id)
                .exists()
            )

            if duplicate_email:

                messages.error(
                    request,
                    (
                        "This email is already used by another employee. "
                        "Please use a different email."
                    )
                )

                return render(
                    request,
                    "superadmin/employee_form.html",
                    {
                        "employee": employee,
                        "companies": companies,
                        "form_data": request.POST,
                        "editing": True,
                    }
                )

            # ------------------------------------------------
            # CHECK NEW COMPANY EMPLOYEE LIMIT
            # ------------------------------------------------

            moving_to_new_company = (
                employee.company_id != company.id
            )

            if (
                moving_to_new_company
                and is_active
                and company.employee_limit
                and company.active_employees()
                >= company.employee_limit
            ):

                messages.error(
                    request,
                    (
                        "The selected company has "
                        "reached its employee limit."
                    )
                )

                return render(
                    request,
                    "superadmin/employee_form.html",
                    {
                        "employee": employee,
                        "companies": companies,
                        "form_data": request.POST,
                        "editing": True,
                    }
                )

            # ------------------------------------------------
            # SAVE OLD COMPANY
            # ------------------------------------------------

            old_company = employee.company

            # ------------------------------------------------
            # UPDATE EMPLOYEE
            # ------------------------------------------------

            employee.company = company

            employee.name = name

            employee.email = email

            employee.is_active = is_active

            if employee_code:

                employee.employee_code = (
                    employee_code
                )

            employee.save()

            # ------------------------------------------------
            # AUDIT LOG
            # ------------------------------------------------

            try:

                if old_company.id != company.id:

                    description = (
                        f"Employee {employee.name} "
                        f"moved from "
                        f"{old_company.Brand_Name or old_company.Registered_Company_Name} "
                        f"to "
                        f"{company.Brand_Name or company.Registered_Company_Name}"
                    )

                else:

                    description = (
                        f"Updated employee "
                        f"{employee.name}"
                    )

                SuperAdminAuditLog.objects.create(

                    superadmin=
                        request.superadmin_profile,

                    company=company,

                    action="OTHER",

                    description=description,

                    ip_address=
                        request.META.get(
                            "REMOTE_ADDR"
                        ),
                )

            except Exception:

                pass

            messages.success(
                request,
                "Employee updated successfully."
            )

            return redirect(
                "superadmin_employees"
            )

    return render(
        request,
        "superadmin/employee_form.html",
        {
            "employee": employee,
            "companies": companies,
            "form_data": {},
            "editing": True,
        }
    )
# ============================================================
# EMPLOYEE STATUS
# ============================================================

# ============================================================
# EMPLOYEE STATUS
# ============================================================

@require_POST
@superadmin_required
@transaction.atomic
def superadmin_employee_status(
    request,
    employee_id
):

    employee = get_object_or_404(
        EmployeeDT,
        Q(candidate_status__iexact="JOINED")
        | Q(account__isnull=False)
        | Q(is_active=False),
        id=employee_id,
    )

    new_status = (
        request.POST.get("status")
    )

    if new_status == "active":

        employee.is_active = True

    elif new_status == "inactive":

        employee.is_active = False

    else:

        messages.error(
            request,
            "Invalid employee status."
        )

        return redirect(
            "superadmin_employees"
        )

    employee.save(
        update_fields=[
            "is_active",
            "updated_at",
        ]
    )

    # ========================================================
    # LOGIN ACCOUNT
    # ========================================================

    account = (
        EmployeeAccount.objects
        .filter(
            employee=employee
        )
        .first()
    )

    if account:

        if new_status == "inactive":

            account.is_active = False

            account.is_login_enabled = False

        else:

            account.is_active = True

            account.is_login_enabled = True

        account.save(
            update_fields=[
                "is_active",
                "is_login_enabled",
                "updated_at",
            ]
        )

    # ========================================================
    # AUDIT
    # ========================================================

    try:

        SuperAdminAuditLog.objects.create(

            superadmin=
                request.superadmin_profile,

            company=employee.company,

            action="OTHER",

            description=(

                f"Employee "
                f"{employee.name} "
                f"status changed to "
                f"{'Active' if employee.is_active else 'Inactive'}"

            ),

            ip_address=
                request.META.get(
                    "REMOTE_ADDR"
                ),

        )

    except Exception:

        pass

    messages.success(

        request,

        (
            "Employee status and login access "
            "updated successfully."
        )

    )

    return redirect(
        "superadmin_employees"
    )

# ============================================================
# AUDIT LOGS
# ============================================================

@superadmin_required
def superadmin_audit_logs(request):

    logs = (
        SuperAdminAuditLog.objects
        .select_related(
            'company',
            'superadmin'
        )
        .order_by('-created_at')
    )

    search = request.GET.get(
        'search',
        ''
    ).strip()

    action = request.GET.get(
        'action',
        ''
    )

    if search:

        logs = logs.filter(

            Q(description__icontains=search) |

            Q(company__Registered_Company_Name__icontains=search) |

            Q(company__Brand_Name__icontains=search)
        )

    if action:

        logs = logs.filter(
            action=action
        )

    context = {

        'logs': logs,

        'search': search,

        'selected_action': action,

        'action_choices':
            SuperAdminAuditLog.ACTION_CHOICES,
    }

    return render(
        request,
        'superadmin/audit_logs.html',
        context
    )


# ============================================================
# PLATFORM SETTINGS
# ============================================================

@superadmin_required
def superadmin_settings(request):

    settings_obj, created = (
        SuperAdminSettings.objects.get_or_create(
            id=1
        )
    )

    if request.method == 'POST':

        settings_obj.platform_name = (
            request.POST.get(
                'platform_name',
                settings_obj.platform_name
            )
        )

        settings_obj.support_email = (
            request.POST.get(
                'support_email'
            ) or None
        )

        settings_obj.support_phone = (
            request.POST.get(
                'support_phone'
            ) or None
        )

        try:

            settings_obj.default_employee_limit = int(
                request.POST.get(
                    'default_employee_limit',
                    settings_obj.default_employee_limit
                )
            )

            settings_obj.default_admin_limit = int(
                request.POST.get(
                    'default_admin_limit',
                    settings_obj.default_admin_limit
                )
            )

            settings_obj.default_hr_limit = int(
                request.POST.get(
                    'default_hr_limit',
                    settings_obj.default_hr_limit
                )
            )

            settings_obj.default_device_limit = int(
                request.POST.get(
                    'default_device_limit',
                    settings_obj.default_device_limit
                )
            )

            settings_obj.default_trial_days = int(
                request.POST.get(
                    'default_trial_days',
                    settings_obj.default_trial_days
                )
            )

        except ValueError:

            messages.error(
                request,
                "Please enter valid numeric values."
            )

            return redirect(
                'superadmin_settings'
            )

        settings_obj.allow_new_company_registration = (
            request.POST.get(
                'allow_new_company_registration'
            ) == 'on'
        )

        settings_obj.maintenance_mode = (
            request.POST.get(
                'maintenance_mode'
            ) == 'on'
        )

        settings_obj.save()

        messages.success(
            request,
            "Platform settings updated successfully."
        )

        return redirect(
            'superadmin_settings'
        )

    return render(
        request,
        'superadmin/settings.html',
        {
            'settings_obj': settings_obj
        }
    )


# ============================================================
# SUPERADMIN PROFILE
# ============================================================

@superadmin_required
def superadmin_profile(request):

    profile = request.superadmin_profile

    if request.method == 'POST':

        profile.full_name = request.POST.get(
            'full_name',
            profile.full_name
        )

        profile.phone_number = request.POST.get(
            'phone_number',
            profile.phone_number
        )

        profile.save()

        messages.success(
            request,
            "Profile updated successfully."
        )

        return redirect(
            'superadmin_profile'
        )

    return render(
        request,
        'superadmin/profile.html',
        {
            'profile': profile
        }
    )





from django.contrib import messages
from django.db import transaction
from django.shortcuts import render, redirect
from django.utils import timezone


@superadmin_required
def superadmin_company_add(request):

    form_data = {}

    if request.method == "POST":

        form_data = request.POST.copy()

        try:

            with transaction.atomic():

                # --------------------------------------------------
                # CREATE COMPANY OBJECT
                # --------------------------------------------------

                company = company_details()


                # --------------------------------------------------
                # BASIC INFORMATION
                # --------------------------------------------------

                company.Registered_Company_Name = request.POST.get(
                    "Registered_Company_Name",
                    ""
                ).strip()

                company.Brand_Name = request.POST.get(
                    "Brand_Name",
                    ""
                ).strip()

                company.Company_Official_Email = request.POST.get(
                    "Company_Official_Email",
                    ""
                ).strip()

                company.Company_Official_Contact = request.POST.get(
                    "Company_Official_Contact",
                    ""
                ).strip()

                company.Website = request.POST.get(
                    "Website",
                    ""
                ).strip()

                company.Domain_Name = request.POST.get(
                    "Domain_Name",
                    ""
                ).strip()

                company.Industry_Type = request.POST.get(
                    "Industry_Type",
                    ""
                ).strip()


                # --------------------------------------------------
                # ADDRESS
                # --------------------------------------------------

                if hasattr(company, "Registered_Address"):

                    company.Registered_Address = request.POST.get(
                        "Registered_Address",
                        ""
                    ).strip()

                if hasattr(company, "Corporate_Address"):

                    company.Corporate_Address = request.POST.get(
                        "Corporate_Address",
                        ""
                    ).strip()


                # --------------------------------------------------
                # PLAN
                # --------------------------------------------------

                plan = request.POST.get(
                    "plan",
                    "FREE"
                )

                if plan not in [
                    "FREE",
                    "BASIC",
                    "PRO",
                    "ENTERPRISE"
                ]:
                    plan = "FREE"

                company.plan = plan


                # --------------------------------------------------
                # COMPANY STATUS
                # --------------------------------------------------

                company_status = request.POST.get(
                    "company_status",
                    "TRIAL"
                )

                if company_status not in [
                    "ACTIVE",
                    "INACTIVE",
                    "SUSPENDED",
                    "TRIAL",
                    "EXPIRED"
                ]:
                    company_status = "TRIAL"

                company.company_status = company_status


                # --------------------------------------------------
                # STATUS BOOLEAN
                # --------------------------------------------------

                if hasattr(company, "status"):

                    company.status = (
                        company_status in ["ACTIVE", "TRIAL"]
                    )


                # --------------------------------------------------
                # LIMITS
                # --------------------------------------------------

                employee_limit = request.POST.get(
                    "employee_limit",
                    "10"
                )

                admin_limit = request.POST.get(
                    "admin_limit",
                    "1"
                )

                hr_limit = request.POST.get(
                    "hr_limit",
                    "1"
                )

                device_limit = request.POST.get(
                    "device_limit",
                    "1"
                )


                if hasattr(company, "employee_limit"):

                    company.employee_limit = int(
                        employee_limit or 10
                    )


                if hasattr(company, "admin_limit"):

                    company.admin_limit = int(
                        admin_limit or 1
                    )


                if hasattr(company, "hr_limit"):

                    company.hr_limit = int(
                        hr_limit or 1
                    )


                if hasattr(company, "device_limit"):

                    company.device_limit = int(
                        device_limit or 1
                    )


                # --------------------------------------------------
                # NOTES
                # --------------------------------------------------

                if hasattr(company, "notes"):

                    company.notes = request.POST.get(
                        "notes",
                        ""
                    ).strip()


                # --------------------------------------------------
                # CREATED BY SUPER ADMIN
                # --------------------------------------------------

                if hasattr(company, "created_by_superadmin"):

                    # This field is BooleanField
                    # Therefore it must receive True or False.
                    company.created_by_superadmin = True


                # --------------------------------------------------
                # ADDITIVE: login identity + welcome email prep
                # The form collects Company_Official_Email but the
                # company login uses company.email / company.password
                # / company.contact_no (unique). Fill only if empty.
                # --------------------------------------------------

                from .company_mail import (
                    generate_temp_password,
                    send_company_welcome_email,
                )

                if not company.Registered_Company_Name:
                    company.Registered_Company_Name = request.POST.get(
                        "registered_company_name", ""
                    ).strip()

                if not company.Registered_Company_Name:
                    raise Exception("Registered company name is required.")

                if not company.email:
                    company.email = company.Company_Official_Email

                if not company.email:
                    raise Exception("Company official email is required.")

                if company_details.objects.filter(
                    email__iexact=company.email
                ).exists():
                    raise Exception(
                        "A company with this email already exists."
                    )

                if not company.contact_no:
                    company.contact_no = company.Company_Official_Contact

                if not company.contact_no:
                    raise Exception("Company contact number is required.")

                if company_details.objects.filter(
                    contact_no=company.contact_no
                ).exists():
                    raise Exception(
                        "A company with this contact number already exists."
                    )

                # Created by a SuperAdmin -> no OTP step; without this the
                # emailed credentials fail with company_not_verified.
                if hasattr(company, "is_verified"):
                    company.is_verified = True

                welcome_password = None

                if not company.password:
                    welcome_password = generate_temp_password()
                    company.password = welcome_password

                # --------------------------------------------------
                # SAVE TO DATABASE
                # --------------------------------------------------

                company.save()


                # --------------------------------------------------
                # AUDIT LOG
                # --------------------------------------------------

                try:

                    SuperAdminAuditLog.objects.create(

                        superadmin=request.user,

                        company=company,

                        action="CREATE_COMPANY",

                        description=(
                            f"Company created: "
                            f"{company.Registered_Company_Name}"
                        ),

                        ip_address=(
                            request.META.get("REMOTE_ADDR")
                        )

                    )

                except Exception:

                    # Audit logging should not prevent
                    # company creation.
                    pass


                # ---- ADDITIVE: welcome email (after commit; a mail
                # failure must never undo the company creation) ----

                def _send_welcome(company=company, pw=welcome_password):

                    try:

                        sent_to = send_company_welcome_email(company, pw)

                        messages.info(
                            request,
                            f"Welcome email sent to {sent_to}."
                        )

                    except Exception as mail_error:

                        messages.warning(
                            request,
                            "Company created, but the welcome email "
                            f"could not be sent: {mail_error}"
                        )

                transaction.on_commit(_send_welcome)


                messages.success(
                    request,
                    "Company created successfully."
                )


                return redirect(
                    "superadmin_companies"
                )


        except ValueError:

            form_data = request.POST

            return render(
                request,
                "superadmin/company_form.html",
                {
                    "form_data": form_data,
                    "form_errors": [
                        "Employee, admin, HR and device limits must be valid numbers."
                    ]
                }
            )


        except Exception as e:

            form_data = request.POST

            return render(
                request,
                "superadmin/company_form.html",
                {
                    "form_data": form_data,
                    "form_errors": [
                        str(e)
                    ]
                }
            )


    # ------------------------------------------------------
    # GET REQUEST
    # ------------------------------------------------------

    return render(
        request,
        "superadmin/company_form.html",
        {
            "form_data": {},
            "form_errors": []
        }
    )






@superadmin_required
def superadmin_network(request):

    health = []

    # DATABASE
    start = time.perf_counter()

    try:

        with connection.cursor() as cursor:

            cursor.execute(
                "SELECT 1"
            )

            cursor.fetchone()

        elapsed = (
            time.perf_counter() - start
        ) * 1000

        health.append({
            "type": "DATABASE",
            "status": "UP",
            "response_time": round(
                elapsed,
                2
            ),
            "message":
                "Database connection healthy."
        })

    except Exception as exc:

        health.append({
            "type": "DATABASE",
            "status": "DOWN",
            "response_time": None,
            "message": str(exc)
        })


    return render(
        request,
        "superadmin/network.html",
        {
            "health": health
        }
    )





# ============================================================
# SUPER ADMIN REPORTS
# ============================================================

@superadmin_required
def superadmin_reports(request):

    companies = company_details.objects.all()

    employees = EmployeeDT.objects.select_related("company", "account").filter(account__isnull=False)

    total_companies = companies.count()

    active_companies = companies.filter(
        company_status="ACTIVE"
    ).count()

    inactive_companies = companies. filter(
        company_status="INACTIVE"
    ).count()

    total_employees = employees.count()

    active_employees = employees.filter(
        is_active=True
    ).count()

    inactive_employees = employees.filter(
        is_active=False
    ).count()

    company_report = []

    for company in companies.order_by(
        "Registered_Company_Name"
    ):

        company_employees = employees.filter(
            company=company
        )

        company_report.append({
            "company": company,
            "total": company_employees.count(),
            "active": company_employees.filter(
                is_active=True
            ).count(),
            "inactive": company_employees.filter(
                is_active=False
            ).count(),
        })

    context = {
        "total_companies": total_companies,
        "active_companies": active_companies,
        "inactive_companies": inactive_companies,

        "total_employees": total_employees,
        "active_employees": active_employees,
        "inactive_employees": inactive_employees,

        "company_report": company_report,
    }

    return render(
        request,
        "superadmin/reports.html",
        context
    )



# ============================================================
# EMPLOYEE CSV EXPORT
# ============================================================

@superadmin_required
def superadmin_employee_export(request):

    search = request.GET.get(
        "search",
        ""
    ).strip()

    company_id = request.GET.get(
        "company",
        ""
    ).strip()

    status = request.GET.get(
        "status",
        ""
    ).strip()

    employees = (
        EmployeeDT.objects
        .select_related("company")
        .all()
        .order_by(
            "company__Registered_Company_Name",
            "name"
        )
    )

    if search:

        employees = employees.filter(
            Q(name__icontains=search)
            |
            Q(email__icontains=search)
            |
            Q(employee_code__icontains=search)
            |
            Q(
                company__Registered_Company_Name__icontains=search
            )
            |
            Q(
                company__Brand_Name__icontains=search
            )
        )

    if company_id:
        employees = employees.filter(
            company_id=company_id
        )

    if status == "active":
        employees = employees.filter(
            is_active=True
        )

    elif status == "inactive":
        employees = employees.filter(
            is_active=False
        )

    response = HttpResponse(
        content_type="text/csv"
    )

    response["Content-Disposition"] = (
        'attachment; filename="peoplesuite_employees.csv"'
    )

    writer = csv.writer(response)

    writer.writerow([
        "Employee Code",
        "Employee Name",
        "Email",
        "Company",
        "Company Email",
        "Status",
    ])

    for employee in employees:

        company = employee.company

        company_name = (
            company.Brand_Name
            or company.Registered_Company_Name
        )

        writer.writerow([
            employee.employee_code,
            employee.name,
            employee.email,
            company_name,
            company.Company_Official_Email,
            "Active"
            if employee.is_active
            else "Inactive",
        ])

    return response



import io

# ============================================================
# EMPLOYEE CSV IMPORT
# ============================================================

@superadmin_required
def superadmin_employee_import(request):

    companies = (
        company_details.objects
        .all()
        .order_by(
            "Registered_Company_Name"
        )
    )

    if request.method == "POST":

        company_id = request.POST.get(
            "company"
        )

        csv_file = request.FILES.get(
            "employee_file"
        )

        if not company_id:

            messages.error(
                request,
                "Please select a company."
            )

            return redirect(
                "superadmin_employee_import"
            )

        if not csv_file:

            messages.error(
                request,
                "Please select a CSV file."
            )

            return redirect(
                "superadmin_employee_import"
            )

        if not csv_file.name.lower().endswith(
            ".csv"
        ):

            messages.error(
                request,
                "Only CSV files are supported."
            )

            return redirect(
                "superadmin_employee_import"
            )

        company = get_object_or_404(
            company_details,
            id=company_id
        )

        try:

            decoded_file = (
                csv_file
                .read()
                .decode("utf-8-sig")
            )

            reader = csv.DictReader(
                io.StringIO(decoded_file)
            )

            created_count = 0
            skipped_count = 0

            for row in reader:

                name = (
                    row.get("name", "")
                    .strip()
                )

                email = (
                    row.get("email", "")
                    .strip()
                )

                employee_code = (
                    row.get(
                        "employee_code",
                        ""
                    )
                    .strip()
                )

                if not name or not email:

                    skipped_count += 1
                    continue

                if EmployeeDT.objects.filter(
                    email=email
                ).exists():

                    skipped_count += 1
                    continue

                if employee_code:

                    if EmployeeDT.objects.filter(
                        employee_code=employee_code
                    ).exists():

                        skipped_count += 1
                        continue

                # Check company employee limit
                if (
                    company.employee_limit
                    and company.active_employees()
                    >= company.employee_limit
                ):
                    skipped_count += 1
                    continue

                employee = EmployeeDT(

                    company=company,

                    name=name,

                    email=email,

                    is_active=True,

                    candidate_status="JOINED",

                    Employee_Status="Activate",

                )

                if employee_code:
                    employee.employee_code = (
                        employee_code
                    )

                employee.save()

                EmployeeAccount.objects.get_or_create(

                    employee=employee,

                    defaults={

                        "is_login_enabled": False,

                        "is_verified": False,

                        "is_active": True,

                    }

                )

                created_count += 1

            messages.success(
                request,
                f"{created_count} employees imported successfully. "
                f"{skipped_count} rows skipped."
            )

            return redirect(
                "superadmin_employees"
            )

        except Exception as exc:

            messages.error(
                request,
                f"Import failed: {exc}"
            )

    return render(
        request,
        "superadmin/employee_import.html",
        {
            "companies": companies
        }
    )





# ============================================================
# SECURITY CENTER
# ============================================================

@superadmin_required
def superadmin_security(request):

    logs = (
        AuthLog.objects
        .select_related("company")
        .order_by("-created_at")
    )

    search = request.GET.get(
        "search",
        ""
    ).strip()

    status = request.GET.get(
        "status",
        ""
    ).strip()

    if search:

        logs = logs.filter(
            Q(identifier__icontains=search)
            |
            Q(ip_address__icontains=search)
            |
            Q(
                company__Brand_Name__icontains=search
            )
            |
            Q(
                company__Registered_Company_Name__icontains=search
            )
        )

    if status:

        logs = logs.filter(
            status=status
        )

    context = {
        "logs": logs[:200],
        "search": search,
        "selected_status": status,
    }

    return render(
        request,
        "superadmin/security.html",
        context
    )





# ============================================================
# EDIT COMPANY
# SUPER ADMIN HAS FULL PLATFORM MANAGEMENT ACCESS
# ============================================================

@superadmin_required
def superadmin_company_edit(request, company_id):

    company = get_object_or_404(
        company_details,
        id=company_id
    )

    if request.method == "POST":

        try:

            with transaction.atomic():

                # ------------------------------------------------
                # BASIC COMPANY INFORMATION
                # ------------------------------------------------

                company.Registered_Company_Name = (
                    request.POST.get(
                        "Registered_Company_Name",
                        company.Registered_Company_Name
                    ).strip()
                )

                company.Brand_Name = (
                    request.POST.get(
                        "Brand_Name",
                        company.Brand_Name
                    ).strip()
                )

                company.Company_Official_Email = (
                    request.POST.get(
                        "Company_Official_Email",
                        company.Company_Official_Email
                    ).strip()
                )

                company.Company_Official_Contact = (
                    request.POST.get(
                        "Company_Official_Contact",
                        company.Company_Official_Contact
                    ).strip()
                )

                company.Website = (
                    request.POST.get(
                        "Website",
                        company.Website
                    ).strip()
                )

                company.Domain_Name = (
                    request.POST.get(
                        "Domain_Name",
                        company.Domain_Name
                    ).strip()
                )

                company.Industry_Type = (
                    request.POST.get(
                        "Industry_Type",
                        company.Industry_Type
                    ).strip()
                )


                # ------------------------------------------------
                # ADDRESS
                # ------------------------------------------------

                if hasattr(
                    company,
                    "Registered_Address"
                ):

                    company.Registered_Address = (
                        request.POST.get(
                            "Registered_Address",
                            company.Registered_Address
                        ).strip()
                    )


                if hasattr(
                    company,
                    "Corporate_Address"
                ):

                    company.Corporate_Address = (
                        request.POST.get(
                            "Corporate_Address",
                            company.Corporate_Address
                        ).strip()
                    )


                # ------------------------------------------------
                # STATUS
                # ------------------------------------------------

                company_status = request.POST.get(
                    "company_status",
                    company.company_status
                )

                valid_statuses = dict(
                    company_details.COMPANY_STATUS_CHOICES
                )

                if company_status in valid_statuses:

                    company.company_status = (
                        company_status
                    )

                    company.status = (
                        company_status
                        in ["ACTIVE", "TRIAL"]
                    )


                # ------------------------------------------------
                # PLAN
                # ------------------------------------------------

                plan = request.POST.get(
                    "plan",
                    company.plan
                )

                valid_plans = dict(
                    company_details.PLAN_CHOICES
                )

                if plan in valid_plans:

                    company.plan = plan


                # ------------------------------------------------
                # LIMITS
                # ------------------------------------------------

                for field_name in [
                    "employee_limit",
                    "admin_limit",
                    "hr_limit",
                    "device_limit",
                ]:

                    if hasattr(
                        company,
                        field_name
                    ):

                        value = request.POST.get(
                            field_name
                        )

                        if value not in [
                            None,
                            ""
                        ]:

                            value = int(value)

                            if value < 0:

                                raise ValueError(
                                    f"{field_name} cannot be negative."
                                )

                            setattr(
                                company,
                                field_name,
                                value
                            )


                # ------------------------------------------------
                # COMPANY NOTES
                # ------------------------------------------------

                if hasattr(
                    company,
                    "notes"
                ):

                    company.notes = (
                        request.POST.get(
                            "notes",
                            company.notes
                        ).strip()
                    )


                # ------------------------------------------------
                # SAVE
                # ------------------------------------------------

                company.save()


                # ------------------------------------------------
                # AUDIT
                # ------------------------------------------------

                try:

                    SuperAdminAuditLog.objects.create(

                        superadmin=(
                            request.superadmin_profile
                        ),

                        company=company,

                        action="UPDATE_COMPANY",

                        description=(
                            "Company information updated "
                            "by Super Admin."
                        ),

                        ip_address=(
                            request.META.get(
                                "REMOTE_ADDR"
                            )
                        )

                    )

                except Exception:

                    pass


            messages.success(
                request,
                "Company information updated successfully."
            )

            return redirect(
                "superadmin_company_detail",
                company_id=company.id
            )


        except (TypeError, ValueError) as exc:

            messages.error(
                request,
                f"Please check the entered values: {exc}"
            )


    return render(
        request,
        "superadmin/company_edit.html",
        {
            "company": company,

            "status_choices":
                company_details.COMPANY_STATUS_CHOICES,

            "plan_choices":
                company_details.PLAN_CHOICES,
        }
    )





# ============================================================
# SUBSCRIPTION PACKAGES
# ============================================================

# ============================================================
# SUBSCRIPTION PACKAGES
# ============================================================

@superadmin_required
def superadmin_packages(request):

    packages = (
        SubscriptionPackage.objects
        .all()
        .order_by(
            "sort_order",
            "monthly_price"
        )
    )

    return render(
        request,
        "superadmin/packages.html",
        {
            "packages": packages
        }
    )


# ============================================================
# ADD PACKAGE
# ============================================================

@superadmin_required
def superadmin_package_add(request):

    if request.method == "POST":

        try:

            name = request.POST.get(
                "name",
                ""
            ).strip()

            code = request.POST.get(
                "code",
                ""
            ).strip().upper()

            plan = request.POST.get(
                "plan",
                "BASIC"
            )

            description = request.POST.get(
                "description",
                ""
            ).strip()

            monthly_price = request.POST.get(
                "monthly_price",
                "0"
            )

            yearly_price = request.POST.get(
                "yearly_price",
                "0"
            )

            billing_cycle = request.POST.get(
                "billing_cycle",
                "MONTHLY"
            )

            employee_limit = int(
                request.POST.get(
                    "employee_limit",
                    "10"
                )
            )

            admin_limit = int(
                request.POST.get(
                    "admin_limit",
                    "1"
                )
            )

            hr_limit = int(
                request.POST.get(
                    "hr_limit",
                    "1"
                )
            )

            device_limit = int(
                request.POST.get(
                    "device_limit",
                    "1"
                )
            )

            trial_days = int(
                request.POST.get(
                    "trial_days",
                    "14"
                )
            )

            sort_order = int(
                request.POST.get(
                    "sort_order",
                    "0"
                )
            )

            if not name:

                messages.error(
                    request,
                    "Package name is required."
                )

                return redirect(
                    "superadmin_package_add"
                )

            if not code:

                messages.error(
                    request,
                    "Package code is required."
                )

                return redirect(
                    "superadmin_package_add"
                )

            if (
                employee_limit < 0
                or admin_limit < 0
                or hr_limit < 0
                or device_limit < 0
                or trial_days < 0
            ):

                messages.error(
                    request,
                    "Package limits cannot be negative."
                )

                return redirect(
                    "superadmin_package_add"
                )

            if SubscriptionPackage.objects.filter(
                code=code
            ).exists():

                messages.error(
                    request,
                    "A package with this code already exists."
                )

                return redirect(
                    "superadmin_package_add"
                )

            package = SubscriptionPackage.objects.create(

                name=name,

                code=code,

                plan=plan,

                description=description,

                monthly_price=monthly_price,

                yearly_price=yearly_price,

                billing_cycle=billing_cycle,

                employee_limit=employee_limit,

                admin_limit=admin_limit,

                hr_limit=hr_limit,

                device_limit=device_limit,

                trial_days=trial_days,

                attendance_enabled=(
                    request.POST.get(
                        "attendance_enabled"
                    ) == "on"
                ),

                leave_enabled=(
                    request.POST.get(
                        "leave_enabled"
                    ) == "on"
                ),

                payroll_enabled=(
                    request.POST.get(
                        "payroll_enabled"
                    ) == "on"
                ),

                recruitment_enabled=(
                    request.POST.get(
                        "recruitment_enabled"
                    ) == "on"
                ),

                performance_enabled=(
                    request.POST.get(
                        "performance_enabled"
                    ) == "on"
                ),

                employee_self_service=(
                    request.POST.get(
                        "employee_self_service"
                    ) == "on"
                ),

                reports_enabled=(
                    request.POST.get(
                        "reports_enabled"
                    ) == "on"
                ),

                api_access_enabled=(
                    request.POST.get(
                        "api_access_enabled"
                    ) == "on"
                ),

                audit_logs_enabled=(
                    request.POST.get(
                        "audit_logs_enabled"
                    ) == "on"
                ),

                is_active=(
                    request.POST.get(
                        "is_active"
                    ) == "on"
                ),

                is_public=(
                    request.POST.get(
                        "is_public"
                    ) == "on"
                ),

                sort_order=sort_order,
            )


            messages.success(
                request,
                f"{package.name} package created successfully."
            )

            return redirect(
                "superadmin_packages"
            )

        except (
            TypeError,
            ValueError
        ):

            messages.error(
                request,
                "Please enter valid package values."
            )

            return redirect(
                "superadmin_package_add"
            )

        except Exception as exc:

            messages.error(
                request,
                f"Package creation failed: {exc}"
            )

            return redirect(
                "superadmin_package_add"
            )


    return render(
        request,
        "superadmin/package_form.html"
    )


# ============================================================
# ADD PACKAGE
# ============================================================

@superadmin_required
def superadmin_package_add(request):

    if request.method == "POST":

        try:

            name = request.POST.get(
                "name",
                ""
            ).strip()

            code = request.POST.get(
                "code",
                ""
            ).strip().upper()

            plan = request.POST.get(
                "plan",
                "BASIC"
            )

            description = request.POST.get(
                "description",
                ""
            ).strip()

            monthly_price = request.POST.get(
                "monthly_price",
                "0"
            )

            yearly_price = request.POST.get(
                "yearly_price",
                "0"
            )

            billing_cycle = request.POST.get(
                "billing_cycle",
                "MONTHLY"
            )

            employee_limit = int(
                request.POST.get(
                    "employee_limit",
                    "10"
                )
            )

            admin_limit = int(
                request.POST.get(
                    "admin_limit",
                    "1"
                )
            )

            hr_limit = int(
                request.POST.get(
                    "hr_limit",
                    "1"
                )
            )

            device_limit = int(
                request.POST.get(
                    "device_limit",
                    "1"
                )
            )

            trial_days = int(
                request.POST.get(
                    "trial_days",
                    "14"
                )
            )

            sort_order = int(
                request.POST.get(
                    "sort_order",
                    "0"
                )
            )

            if not name:

                messages.error(
                    request,
                    "Package name is required."
                )

                return redirect(
                    "superadmin_package_add"
                )

            if not code:

                messages.error(
                    request,
                    "Package code is required."
                )

                return redirect(
                    "superadmin_package_add"
                )

            if (
                employee_limit < 0
                or admin_limit < 0
                or hr_limit < 0
                or device_limit < 0
                or trial_days < 0
            ):

                messages.error(
                    request,
                    "Package limits cannot be negative."
                )

                return redirect(
                    "superadmin_package_add"
                )

            if SubscriptionPackage.objects.filter(
                code=code
            ).exists():

                messages.error(
                    request,
                    "A package with this code already exists."
                )

                return redirect(
                    "superadmin_package_add"
                )

            package = SubscriptionPackage.objects.create(

                name=name,

                code=code,

                plan=plan,

                description=description,

                monthly_price=monthly_price,

                yearly_price=yearly_price,

                billing_cycle=billing_cycle,

                employee_limit=employee_limit,

                admin_limit=admin_limit,

                hr_limit=hr_limit,

                device_limit=device_limit,

                trial_days=trial_days,

                attendance_enabled=(
                    request.POST.get(
                        "attendance_enabled"
                    ) == "on"
                ),

                leave_enabled=(
                    request.POST.get(
                        "leave_enabled"
                    ) == "on"
                ),

                payroll_enabled=(
                    request.POST.get(
                        "payroll_enabled"
                    ) == "on"
                ),

                recruitment_enabled=(
                    request.POST.get(
                        "recruitment_enabled"
                    ) == "on"
                ),

                performance_enabled=(
                    request.POST.get(
                        "performance_enabled"
                    ) == "on"
                ),

                employee_self_service=(
                    request.POST.get(
                        "employee_self_service"
                    ) == "on"
                ),

                reports_enabled=(
                    request.POST.get(
                        "reports_enabled"
                    ) == "on"
                ),

                api_access_enabled=(
                    request.POST.get(
                        "api_access_enabled"
                    ) == "on"
                ),

                audit_logs_enabled=(
                    request.POST.get(
                        "audit_logs_enabled"
                    ) == "on"
                ),

                is_active=(
                    request.POST.get(
                        "is_active"
                    ) == "on"
                ),

                is_public=(
                    request.POST.get(
                        "is_public"
                    ) == "on"
                ),

                sort_order=sort_order,
            )


            messages.success(
                request,
                f"{package.name} package created successfully."
            )

            return redirect(
                "superadmin_packages"
            )

        except (
            TypeError,
            ValueError
        ):

            messages.error(
                request,
                "Please enter valid package values."
            )

            return redirect(
                "superadmin_package_add"
            )

        except Exception as exc:

            messages.error(
                request,
                f"Package creation failed: {exc}"
            )

            return redirect(
                "superadmin_package_add"
            )


    return render(
        request,
        "superadmin/package_form.html"
    )





# ============================================================
# CONVERT CANDIDATE -> EMPLOYEE
# ============================================================

@require_POST
@superadmin_required
@transaction.atomic
def superadmin_candidate_convert(
    request,
    candidate_id
):

    candidate = get_object_or_404(
        Candidate.objects.select_related("company"),
        id=candidate_id
    )

    # --------------------------------------------------------
    # MUST BE SELECTED
    # --------------------------------------------------------

    if (
        candidate.candidate_status or ""
    ).upper() != "SELECTED":

        messages.error(
            request,
            "Candidate must reach the Selected stage before employee conversion."
        )

        return redirect(
            "superadmin_candidate_detail",
            candidate_id=candidate.id
        )

    # --------------------------------------------------------
    # ALREADY CONVERTED
    # --------------------------------------------------------

    if candidate.converted_to_employee:

        messages.info(
            request,
            "This candidate has already been converted to an employee."
        )

        return redirect(
            "superadmin_candidate_detail",
            candidate_id=candidate.id
        )

    # --------------------------------------------------------
    # EMAIL REQUIRED
    # --------------------------------------------------------

    if not candidate.email:

        messages.error(
            request,
            "Candidate email is required before conversion."
        )

        return redirect(
            "superadmin_candidate_detail",
            candidate_id=candidate.id
        )

    # --------------------------------------------------------
    # FIND EXISTING LEGACY EMPLOYEE
    # --------------------------------------------------------
    #
    # IMPORTANT:
    # Your 33 migrated candidates already have old
    # EmployeeDT records.
    #
    # Reuse the existing EmployeeDT record instead of
    # creating another EmployeeDT record.
    # --------------------------------------------------------

    employee = (
        EmployeeDT.objects
        .filter(
            company=candidate.company,
            email__iexact=candidate.email
        )
        .first()
    )

    # --------------------------------------------------------
    # CREATE ONLY IF NO EXISTING EMPLOYEE RECORD
    # --------------------------------------------------------

    if employee is None:

        employee = EmployeeDT.objects.create(

            company=candidate.company,

            name=candidate.name,

            email=candidate.email,

            phone_number=candidate.phone,

            applied_position=candidate.applied_position,

            candidate_source=candidate.candidate_source,

            recruiter_name=candidate.recruiter_name,

            candidate_status="JOINED",

            Employee_Status="Activate",

            is_active=True,

            Date_of_Joining=timezone.localdate(),

        )

    else:

        # ----------------------------------------------------
        # REUSE EXISTING LEGACY EmployeeDT
        # ----------------------------------------------------

        employee.candidate_status = "JOINED"

        employee.Employee_Status = "Activate"

        employee.is_active = True

        if not employee.Date_of_Joining:

            employee.Date_of_Joining = (
                timezone.localdate()
            )

        employee.save(
            update_fields=[
                "candidate_status",
                "Employee_Status",
                "is_active",
                "Date_of_Joining",
            ]
        )

    # --------------------------------------------------------
    # EMPLOYEE ROLE
    # --------------------------------------------------------

    role, _ = EmployeeRole.objects.get_or_create(

        company=employee.company,

        role_code="EMPLOYEE",

        defaults={
            "role_name": "Employee"
        }

    )

    # --------------------------------------------------------
    # EMPLOYEE LOGIN ACCOUNT
    # --------------------------------------------------------

    account, created = (
        EmployeeAccount.objects.get_or_create(

            employee=employee,

            defaults={
                "role": role,
                "is_login_enabled": True,
                "is_verified": True,
                "is_active": True,
            }
        )
    )

    if not created:

        account.role = role

        account.is_login_enabled = True

        account.is_verified = True

        account.is_active = True

        account.failed_login_attempts = 0

        account.save()

    # --------------------------------------------------------
    # UPDATE CANDIDATE
    # --------------------------------------------------------

    candidate.candidate_status = "HIRED"

    candidate.converted_to_employee = True

    candidate.converted_employee = employee

    candidate.save(
        update_fields=[
            "candidate_status",
            "converted_to_employee",
            "converted_employee",
            "updated_at",
        ]
    )

    # --------------------------------------------------------
    # AUDIT LOG
    # --------------------------------------------------------

    try:

        SuperAdminAuditLog.objects.create(

            superadmin=
                request.superadmin_profile,

            company=
                candidate.company,

            action="OTHER",

            description=(
                f"Candidate {candidate.name} "
                f"({candidate.candidate_id}) "
                f"converted to employee "
                f"({employee.employee_code})"
            ),

            ip_address=
                request.META.get(
                    "REMOTE_ADDR"
                ),
        )

    except Exception:

        pass

    messages.success(
        request,
        (
            f"{candidate.name} has been converted "
            f"to an employee successfully."
        )
    )

    return redirect(
        "superadmin_employees"
    )


# ============================================================
# SUPER ADMIN CANDIDATE MANAGEMENT
# ============================================================

@superadmin_required
def superadmin_candidates(request):

    search = request.GET.get(
        "search",
        ""
    ).strip()

    company_id = request.GET.get(
        "company",
        ""
    ).strip()

    status = request.GET.get(
        "status",
        ""
    ).strip()

    # ============================================================
    # CANDIDATES ONLY
    # ============================================================

    candidates = (
        Candidate.objects
        .select_related("company")
        .all()
        .order_by("-created_at", "-id")
    )

    # ============================================================
    # SEARCH
    # ============================================================

    if search:

        candidates = candidates.filter(
            Q(
                name__icontains=search
            )
            |
            Q(
                email__icontains=search
            )
            |
            Q(
                candidate_id__icontains=search
            )
            |
            Q(
                applied_position__icontains=search
            )
            |
            Q(
                company__Brand_Name__icontains=search
            )
            |
            Q(
                company__Registered_Company_Name__icontains=search
            )
        )

    # ============================================================
    # COMPANY
    # ============================================================

    if company_id:

        candidates = candidates.filter(
            company_id=company_id
        )

    # ============================================================
    # STATUS
    # ============================================================

    if status:

        candidates = candidates.filter(
            candidate_status=status.upper()
        )

    # ============================================================
    # COMPANIES
    # ============================================================

    companies = (
        company_details.objects
        .all()
        .order_by(
            "Registered_Company_Name"
        )
    )

    # ============================================================
    # STATUS LIST
    # ============================================================

    candidate_statuses = [
        "APPLIED",
        "SHORTLISTED",
        "INTERVIEW",
        "SELECTED",
        "OFFERED",
        "REJECTED",
        "HIRED",
    ]

    # ============================================================
    # GLOBAL COUNTS
    # ============================================================

    total_candidates = (
        Candidate.objects
        .count()
    )

    applied_candidates = (
        Candidate.objects
        .filter(
            candidate_status="APPLIED"
        )
        .count()
    )

    shortlisted_candidates = (
        Candidate.objects
        .filter(
            candidate_status="SHORTLISTED"
        )
        .count()
    )

    interview_candidates = (
        Candidate.objects
        .filter(
            candidate_status="INTERVIEW"
        )
        .count()
    )

    selected_candidates = (
        Candidate.objects
        .filter(
            candidate_status="SELECTED"
        )
        .count()
    )

    rejected_candidates = (
        Candidate.objects
        .filter(
            candidate_status="REJECTED"
        )
        .count()
    )

    hired_candidates = (
        Candidate.objects
        .filter(
            candidate_status="HIRED"
        )
        .count()
    )

    # ========================================================
    # ADDITIVE: include the REAL company-wise recruitment
    # candidates (EmployeeDT rows used by the company HR panel).
    # Existing Candidate rows are kept; sync copies are not
    # shown twice.
    # ========================================================
    from types import SimpleNamespace
    from django.urls import reverse
    from .views_b2b import (
        candidates_base_qs, filter_stage, stage_of, grouped_stage_counts,
        BUCKETS, STAGE_LABELS, LEGACY_COPY_MARKER,
    )

    candidates = candidates.exclude(notes__icontains=LEGACY_COPY_MARKER)

    pipeline_qs = (
        candidates_base_qs()
        .select_related("company")
        .order_by("-created_at", "-id")
    )

    if search:
        pipeline_qs = pipeline_qs.filter(
            Q(name__icontains=search)
            | Q(email__icontains=search)
            | Q(candidate_id__icontains=search)
            | Q(applied_position__icontains=search)
            | Q(company__Brand_Name__icontains=search)
            | Q(company__Registered_Company_Name__icontains=search)
        )

    if company_id:
        pipeline_qs = pipeline_qs.filter(company_id=company_id)

    if status:
        _codes = [status.upper()]
        if status.upper() == "OFFERED":
            _codes += ["OFFER_SENT", "OFFER_ACCEPTED"]
        if status.upper() == "HIRED":
            _codes += ["JOINED"]
        pipeline_qs = filter_stage(pipeline_qs, _codes)

    pipeline_rows = []
    for _c in pipeline_qs:
        _code = stage_of(_c)
        pipeline_rows.append(SimpleNamespace(
            id=_c.pk,
            name=_c.name,
            email=_c.email,
            phone=_c.phone_number,
            company=_c.company,
            candidate_id=_c.candidate_id,
            applied_position=_c.applied_position,
            candidate_status=_code,
            stage_label=STAGE_LABELS.get(_code, _code.title()),
            converted_to_employee=(_code == "JOINED"),
            is_pipeline=True,
            created_at=_c.created_at,
            detail_url=(
                reverse("superadmin_b2b_company", args=[_c.company_id])
                + "?tab=candidates&q=" + (_c.candidate_id or _c.name or "")
            ),
        ))

    candidates = list(candidates) + pipeline_rows
    candidates.sort(key=lambda x: x.created_at, reverse=True)

    # ---- counts: add recruitment candidates to the existing counters ----
    _stage_totals = {}
    for _by_stage in grouped_stage_counts(candidates_base_qs()).values():
        for _k, _n in _by_stage.items():
            _stage_totals[_k] = _stage_totals.get(_k, 0) + _n

    def _sum(*codes):
        return sum(_stage_totals.get(c, 0) for c in codes)

    total_candidates += sum(_stage_totals.values())
    applied_candidates += _sum("APPLIED", "SCREENING")
    shortlisted_candidates += _sum("SHORTLISTED")
    interview_candidates += _sum("INTERVIEW", "FEEDBACK_PENDING")
    selected_candidates += _sum("SELECTED")
    rejected_candidates += _sum("REJECTED")
    hired_candidates += _sum("JOINED")

    # status dropdown (the template reads `status_choices`, it was never passed)
    status_choices = list(Candidate.STATUS_CHOICES) + [
        (code, STAGE_LABELS[code])
        for code in (
            "SCREENING", "FEEDBACK_PENDING", "OFFER_SENT", "OFFER_ACCEPTED",
            "DOCS_PENDING", "BGV", "READY_TO_JOIN", "JOINED",
        )
    ]

    return render(
        request,
        "superadmin/candidates.html",
        {
            "candidates": candidates,

            "companies": companies,

            "search": search,

            "selected_company": company_id,

            "selected_status": status,

            "candidate_statuses": candidate_statuses,
            "status_choices": status_choices,

            "total_candidates": total_candidates,

            "applied_candidates": applied_candidates,

            "shortlisted_candidates": shortlisted_candidates,

            "interview_candidates": interview_candidates,

            "selected_candidates": selected_candidates,

            "rejected_candidates": rejected_candidates,

            "hired_candidates": hired_candidates,
        }
    )


# ============================================================
# PACKAGE / COMPANY EMPLOYEE LIMIT HELPER
# ============================================================

def sync_company_package_limit(company):
    """
    Return the effective employee limit for a company.

    Priority:
    1. Active CompanySubscription employee_limit
    2. Company employee_limit
    3. Active SubscriptionPackage matching company.plan
    4. 0 = no configured limit

    This helper is additive and does not remove or change
    existing company/package data.
    """

    # --------------------------------------------------------
    # 1. ACTIVE COMPANY SUBSCRIPTION
    # --------------------------------------------------------

    try:
        subscription = (
            CompanySubscription.objects
            .filter(
                company=company,
                is_active=True
            )
            .order_by("-id")
            .first()
        )

        if subscription:
            return {
                "employee_limit": (
                    subscription.employee_limit
                    or 0
                ),

                "admin_limit": (
                    getattr(
                        subscription,
                        "admin_limit",
                        0
                    )
                    or 0
                ),

                "device_limit": (
                    getattr(
                        subscription,
                        "device_limit",
                        0
                    )
                    or 0
                ),
            }

    except Exception:
        pass

    # --------------------------------------------------------
    # 2. COMPANY'S EXISTING EMPLOYEE LIMIT
    # --------------------------------------------------------

    company_limit = getattr(
        company,
        "employee_limit",
        0
    ) or 0

    if company_limit:
        return {
            "employee_limit": company_limit,
            "admin_limit": (
                getattr(
                    company,
                    "admin_limit",
                    0
                )
                or 0
            ),
            "device_limit": (
                getattr(
                    company,
                    "device_limit",
                    0
                )
                or 0
            ),
        }

    # --------------------------------------------------------
    # 3. FALLBACK TO SUBSCRIPTION PACKAGE
    # --------------------------------------------------------

    try:

        plan = getattr(
            company,
            "plan",
            None
        )

        if plan:

            package = (
                SubscriptionPackage.objects
                .filter(
                    plan=plan,
                    is_active=True
                )
                .order_by(
                    "sort_order",
                    "id"
                )
                .first()
            )

            if package:

                return {
                    "employee_limit": (
                        package.employee_limit
                        or 0
                    ),

                    "admin_limit": (
                        getattr(
                            package,
                            "admin_limit",
                            0
                        )
                        or 0
                    ),

                    "device_limit": (
                        getattr(
                            package,
                            "device_limit",
                            0
                        )
                        or 0
                    ),
                }

    except Exception:
        pass

    # --------------------------------------------------------
    # 4. NO LIMIT CONFIGURED
    # --------------------------------------------------------

    return {
        "employee_limit": 0,
        "admin_limit": 0,
        "device_limit": 0,
    }




# ============================================================
# SYNC OLD EMPLOYEE-BASED CANDIDATES
# ============================================================
#
# Older recruitment records were stored inside EmployeeDT.
# We DO NOT delete those records.
#
# This helper copies only candidate/recruitment records into
# the new Candidate table.
#
# Actual employees with EmployeeAccount are NOT copied.
# ============================================================
def sync_legacy_candidates():
    """
    Copy eligible legacy candidate records from EmployeeDT
    into Candidate without deleting existing records.

    Existing employee records are not modified.
    Existing Candidate records are preserved.
    """

    legacy_candidates = (
        EmployeeDT.objects
        .select_related("company")
        .filter(account__isnull=True)
        .exclude(candidate_status__isnull=True)
        .exclude(candidate_status="")
        .exclude(candidate_status="JOINED")
    )

    created_count = 0

    status_map = {
        "APPLIED": "APPLIED",
        "SCREENING": "SHORTLISTED",
        "SHORTLISTED": "SHORTLISTED",
        "INTERVIEW": "INTERVIEW",
        "SELECTED": "SELECTED",
        "OFFERED": "OFFERED",
        "REJECTED": "REJECTED",
        "ON_HOLD": "APPLIED",
    }

    for old_employee in legacy_candidates:

        # Company is required for a candidate record.
        if not old_employee.company:
            continue

        # Use the old EmployeeDT ID to prevent duplicate copies.
        legacy_marker = (
            f"Legacy EmployeeDT ID: {old_employee.pk}"
        )

        if Candidate.objects.filter(
            notes__icontains=legacy_marker
        ).exists():
            continue

        candidate_name = (
            old_employee.name or "Unnamed Candidate"
        )

        candidate_email = (
            old_employee.email or ""
        ).strip()

        if not candidate_email:
            candidate_email = (
                f"legacy-{old_employee.pk}@candidate.local"
            )

        old_status = (
            old_employee.candidate_status or "APPLIED"
        ).upper()

        new_status = status_map.get(
            old_status,
            "APPLIED",
        )

        # EmployeeDT has no notes field.
        # Store only the migration marker in Candidate.notes.
        final_notes = legacy_marker

        Candidate.objects.create(
            company=old_employee.company,
            name=candidate_name,
            email=candidate_email,
            phone=old_employee.phone_number or "",
            applied_position=(
                old_employee.applied_position or ""
            ),
            candidate_source=(
                old_employee.candidate_source
                or "Legacy EmployeeDT"
            ),
            recruiter_name=(
                old_employee.recruiter_name or ""
            ),
            candidate_status=new_status,
            resume=(
                old_employee.resume
                if old_employee.resume
                else None
            ),
            notes=final_notes,
            is_active=(
                old_employee.is_active
                if old_employee.is_active is not None
                else True
            ),
            converted_to_employee=False,
        )

        created_count += 1

    return created_count






# ============================================================
# CANDIDATE DETAIL
# ============================================================

@superadmin_required
def superadmin_candidate_detail(request, candidate_id):

    candidate = get_object_or_404(
        Candidate.objects.select_related("company"),
        id=candidate_id
    )

    # --------------------------------------------------------
    # UPDATE CANDIDATE
    # --------------------------------------------------------

    if request.method == "POST":

        action = request.POST.get(
            "action",
            ""
        ).strip()

        # ----------------------------------------------------
        # UPDATE STATUS
        # ----------------------------------------------------

        if action == "status":

            new_status = (
                request.POST.get(
                    "candidate_status",
                    ""
                )
                .strip()
                .upper()
            )

            valid_statuses = {
                value
                for value, label
                in Candidate.STATUS_CHOICES
            }

            if new_status not in valid_statuses:

                messages.error(
                    request,
                    "Invalid candidate status."
                )

            else:

                candidate.candidate_status = new_status

                candidate.save(
                    update_fields=[
                        "candidate_status",
                        "updated_at",
                    ]
                )

                messages.success(
                    request,
                    "Candidate status updated successfully."
                )

            return redirect(
                "superadmin_candidate_detail",
                candidate_id=candidate.id
            )

        # ----------------------------------------------------
        # SAVE RECRUITMENT NOTES
        # ----------------------------------------------------

        if action == "notes":

            notes = request.POST.get(
                "notes",
                ""
            ).strip()

            candidate.notes = notes

            candidate.save(
                update_fields=[
                    "notes",
                    "updated_at",
                ]
            )

            messages.success(
                request,
                "Recruitment notes saved successfully."
            )

            return redirect(
                "superadmin_candidate_detail",
                candidate_id=candidate.id
            )

    # --------------------------------------------------------
    # LEGACY MIGRATION MESSAGE PROTECTION
    # --------------------------------------------------------
    #
    # Old migrated candidates may still contain the automatic
    # migration text in notes.
    #
    # Do not display that text as recruitment notes.
    # --------------------------------------------------------

    display_notes = candidate.notes or ""

    migration_prefix = (
        "Migrated from existing EmployeeDT record"
    )

    if display_notes.strip().startswith(
        migration_prefix
    ):

        display_notes = ""

    # --------------------------------------------------------
    # EMPLOYEE CONVERSION STATE
    # --------------------------------------------------------

    can_convert = (
        (
            candidate.candidate_status or ""
        ).upper()
        == "SELECTED"
        and not candidate.converted_to_employee
    )

    return render(
        request,
        "superadmin/candidate_detail.html",
        {
            "candidate": candidate,

            "status_choices":
                Candidate.STATUS_CHOICES,

            "display_notes":
                display_notes,

            "can_convert":
                can_convert,
        }
    )
    
    
# ============================================================
# ATTENDANCE PHOTOS - BACKEND (replace the old
# superadmin_attendance_photos function with everything below)
# Existing filters (company / search / date) behave the same.
# NEW: status filter, page size, live stats, CSV export.
# Nothing is deleted or modified in the database.
# ============================================================
 
import csv
from datetime import date
 
from django.core.paginator import Paginator
from django.db.models import Count, Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
 
from Employee.models import EMP_check_in_check_out
 
# --- reusable conditions -----------------------------------
CHECKED_OUT_Q = (
    Q(logout_date__isnull=False)
    | Q(logout_time__isnull=False)
    | (Q(check_out_image__isnull=False) & ~Q(check_out_image=""))
)
NO_PHOTO_Q = Q(image__isnull=True) | Q(image="")
NO_LOCATION_Q = Q(checkin_latitude__isnull=True) | Q(checkin_longitude__isnull=True)
 
PAGE_SIZES = [10, 25, 50, 100]
STATUS_FILTERS = {"checked_out", "pending", "no_photo", "no_location"}
 
 
def _attendance_base_queryset(request):
    """Company + search + date filters shared by page and export."""
    qs = EMP_check_in_check_out.objects.select_related("company")
 
    company = request.GET.get("company", "").strip()
    search = request.GET.get("search", "").strip()
    selected_date = request.GET.get("date", "").strip()
    date_error = ""
 
    if company:
        qs = qs.filter(company_id=company)
 
    if search:
        qs = qs.filter(Q(Name__icontains=search) | Q(Employee_ID__icontains=search))
 
    if selected_date:
        try:
            date.fromisoformat(selected_date)
            qs = qs.filter(Q(login_date=selected_date) | Q(logout_date=selected_date))
        except ValueError:
            date_error = "Please select a valid attendance date."
            selected_date = ""
 
    return qs, company, search, selected_date, date_error
 
 
def _apply_status(qs, status):
    if status == "checked_out":
        return qs.filter(CHECKED_OUT_Q)
    if status == "pending":
        return qs.exclude(CHECKED_OUT_Q)
    if status == "no_photo":
        return qs.filter(NO_PHOTO_Q)
    if status == "no_location":
        return qs.filter(NO_LOCATION_Q)
    return qs
 
 
def _ordered(qs):
    return qs.order_by("-login_date", "-login_time", "-logout_date", "-logout_time", "-id")
 
 
@superadmin_required
def superadmin_attendance_photos(request):
    companies = company_details.objects.all().order_by("Registered_Company_Name")
 
    base_qs, selected_company, search, selected_date, date_error = (
        _attendance_base_queryset(request)
    )
 
    # Stats are computed BEFORE the status chip so counts stay visible.
    stats = base_qs.aggregate(
        total=Count("id"),
        checked_out=Count("id", filter=CHECKED_OUT_Q),
        no_photo=Count("id", filter=NO_PHOTO_Q),
        no_location=Count("id", filter=NO_LOCATION_Q),
    )
    stats["pending"] = stats["total"] - stats["checked_out"]
 
    selected_status = request.GET.get("status", "").strip()
    if selected_status not in STATUS_FILTERS:
        selected_status = ""
 
    records = _ordered(_apply_status(base_qs, selected_status))
 
    try:
        per_page = int(request.GET.get("per_page", 25))
    except ValueError:
        per_page = 25
    if per_page not in PAGE_SIZES:
        per_page = 25
 
    total_records = records.count()
    page_obj = Paginator(records, per_page).get_page(request.GET.get("page"))
 
    # Query string without "page" so pagination keeps every filter.
    params = request.GET.copy()
    params.pop("page", None)
 
    # Same, but also without "status" - used by the status chips.
    chip_params = params.copy()
    chip_params.pop("status", None)
 
    return render(
        request,
        "superadmin/attendance_photos.html",
        {
            "companies": companies,
            "attendance_records": page_obj.object_list,
            "page_obj": page_obj,
            "total_records": total_records,
            "selected_company": selected_company,
            "search": search,
            "selected_date": selected_date,
            "selected_status": selected_status,
            "per_page": per_page,
            "page_sizes": PAGE_SIZES,
            "stats": stats,
            "query_string": params.urlencode(),
            "chip_query": chip_params.urlencode(),
            "date_error": date_error,
        },
    )
  
 
@superadmin_required
def superadmin_attendance_export(request):
    """CSV of every record matching the current filters (not just one page)."""
    base_qs, *_ = _attendance_base_queryset(request)
    status = request.GET.get("status", "").strip()
    records = _ordered(_apply_status(base_qs, status))
 
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="peoplesuite_attendance.csv"'
    response.write("\ufeff")  # so Excel opens UTF-8 correctly
 
    writer = csv.writer(response)
    writer.writerow([
        "Company", "Employee ID", "Employee Name",
        "Check-in Date", "Check-in Time", "Check-in Latitude", "Check-in Longitude",
        "Check-in Photo URL",
        "Check-out Date", "Check-out Time", "Check-out Latitude", "Check-out Longitude",
        "Check-out Photo URL",
    ])
 
    def url(f):
        return request.build_absolute_uri(f.url) if f else ""
 
    for r in records.iterator():
        c = r.company
        writer.writerow([
            (c.Brand_Name or c.Registered_Company_Name) if c else "",
            r.Employee_ID, r.Name,
            r.login_date, r.login_time, r.checkin_latitude, r.checkin_longitude,
            url(r.image),
            r.logout_date, r.logout_time, r.checkout_latitude, r.checkout_longitude,
            url(r.check_out_image),
        ])
    return response
    
     
    
    