from django.utils import timezone
# ============================================================
# EMPLOYEE CRUD API - FULL / EXPANDED
# ============================================================

from datetime import date, datetime
from decimal import Decimal, InvalidOperation

from rest_framework.decorators import (
    api_view,
    authentication_classes,
    permission_classes,
    parser_classes,
)
from rest_framework.response import Response
from rest_framework import parsers
from django.db import transaction
from django.db.models import Q
from django.shortcuts import get_object_or_404

from .models import (
    EmployeeDT,
    EmployeeRole,
    EmployeeAccount,
    EmployeeDocument,
    CandidateEducation,
    CandidateExperience,
    CandidateCompensation,
    CandidateBGV,
    BankAccount,
)
from .serializers import (
    EmployeeCRUDSerializer,
    EmployeeDocumentSerializer,
    CandidateEducationSerializer,
    CandidateExperienceSerializer,
    CandidateCompensationSerializer,
    CandidateBGVSerializer,
    BankAccountSerializer,
)
from .employee_crud_permissions import (
    AdminOrEmployeeJWTAuthentication,
    IsAdminOrHR,
    resolve_company_for_user,
)


def _value(data, key, default=None):
    value = data.get(key, default)
    if value == "":
        return None
    return value


def _date_value(value):
    if value in (None, ""):
        return None
    if isinstance(value, date):
        return value
    return datetime.strptime(str(value), "%Y-%m-%d").date()


def _decimal_value(value):
    if value in (None, ""):
        return None
    try:
        return Decimal(str(value))
    except (InvalidOperation, ValueError, TypeError):
        raise ValueError(f"Invalid decimal value: {value}")


def _bool_value(value, default=None):
    if value is None:
        return default
    if isinstance(value, bool):
        return value
    return str(value).strip().lower() in ("1", "true", "yes", "on")


def _serialize_employee(e):
    return EmployeeCRUDSerializer(e).data


def _first(data, *keys, default=None):
    for key in keys:
        if key in data:
            return data.get(key)
    return default


# ============================================================
# CREATE RELATED CANDIDATE DATA
# ============================================================

def _create_candidate_related_data(employee, data, files):
    """
    Creates optional child records after EmployeeDT exists.

    Supported payload prefixes:
      education_*
      experience_*
      compensation_*
      bgv_*
      bank_*

    For multiple education/experience records, callers can also
    use JSON arrays named:
      educational_history
      professional_experience

    Existing direct EmployeeDT document fields are also supported.
    """

    # --------------------------------------------------------
    # EDUCATION
    # --------------------------------------------------------
    education_json = data.get("educational_history")

    if education_json:
        import json
        try:
            education_items = json.loads(education_json)
        except (TypeError, ValueError):
            education_items = []
    else:
        education_items = []

    if isinstance(education_items, dict):
        education_items = [education_items]

    if education_items:
        for item in education_items:
            CandidateEducation.objects.create(
                employee=employee,
                highest_qualification=item.get("highest_qualification"),
                degree_course=item.get("degree_course"),
                specialization_branch=item.get("specialization_branch"),
                university_board=item.get("university_board"),
                college_institute=item.get("college_institute"),
                passing_year=item.get("passing_year") or None,
                percentage_cgpa=item.get("percentage_cgpa"),
                key_certifications=item.get("key_certifications"),
            )
    elif any(
        key in data
        for key in (
            "highest_qualification",
            "degree_course",
            "specialization_branch",
            "university_board",
            "college_institute",
            "passing_year",
            "percentage_cgpa",
            "education_key_certifications",
        )
    ):
        CandidateEducation.objects.create(
            employee=employee,
            highest_qualification=data.get("highest_qualification"),
            degree_course=data.get("degree_course"),
            specialization_branch=data.get("specialization_branch"),
            university_board=data.get("university_board"),
            college_institute=data.get("college_institute"),
            passing_year=data.get("passing_year") or None,
            percentage_cgpa=data.get("percentage_cgpa"),
            key_certifications=data.get("education_key_certifications"),
            degree_certificate=files.get("degree_certificate"),
        )

    # --------------------------------------------------------
    # EXPERIENCE
    # --------------------------------------------------------
    experience_json = data.get("professional_experience")

    if experience_json:
        import json
        try:
            experience_items = json.loads(experience_json)
        except (TypeError, ValueError):
            experience_items = []
    else:
        experience_items = []

    if isinstance(experience_items, dict):
        experience_items = [experience_items]

    if experience_items:
        for item in experience_items:
            CandidateExperience.objects.create(
                employee=employee,
                company_name=item.get("company_name"),
                designation=item.get("designation"),
                department=item.get("department"),
                start_date=item.get("start_date") or None,
                end_date=item.get("end_date") or None,
                reason_for_leaving=item.get("reason_for_leaving"),
                previous_ctc=item.get("previous_ctc") or None,
                reporting_manager=item.get("reporting_manager"),
                reporting_role=item.get("reporting_role"),
                core_responsibilities=item.get("core_responsibilities"),
            )
    elif any(
        key in data
        for key in (
            "experience_company_name",
            "experience_designation",
            "experience_department",
            "experience_start_date",
            "experience_end_date",
            "reason_for_leaving",
            "previous_ctc",
            "reporting_manager",
            "reporting_role",
            "core_responsibilities",
        )
    ):
        CandidateExperience.objects.create(
            employee=employee,
            company_name=data.get("experience_company_name"),
            designation=data.get("experience_designation"),
            department=data.get("experience_department"),
            start_date=data.get("experience_start_date") or None,
            end_date=data.get("experience_end_date") or None,
            reason_for_leaving=data.get("reason_for_leaving"),
            previous_ctc=data.get("previous_ctc") or None,
            reporting_manager=data.get("reporting_manager"),
            reporting_role=data.get("reporting_role"),
            core_responsibilities=data.get("core_responsibilities"),
            experience_reliving_proof=files.get("experience_reliving_proof"),
        )

    # --------------------------------------------------------
    # COMPENSATION - ONE TO ONE
    # --------------------------------------------------------
    compensation_keys = (
        "current_annual_ctc",
        "expected_annual_ctc",
        "offered_annual_ctc",
        "basic_salary",
        "hra",
        "special_allowance",
        "provident_fund",
        "esic",
        "professional_tax",
        "gross_salary",
        "net_in_hand_salary",
    )

    if any(key in data for key in compensation_keys):
        CandidateCompensation.objects.update_or_create(
            employee=employee,
            defaults={
                key: data.get(key) or None
                for key in compensation_keys
            },
        )

    # --------------------------------------------------------
    # BGV - ONE TO ONE
    # --------------------------------------------------------
    bgv_keys = (
        "previous_employment_verification",
        "education_verification",
        "address_verification",
        "identity_verification",
        "assigned_verification_agency",
        "remarks",
    )

    if any(key in data for key in bgv_keys) or files.get("supporting_bgv_dossier"):
        CandidateBGV.objects.update_or_create(
            employee=employee,
            defaults={
                "previous_employment_verification":
                    data.get("previous_employment_verification"),
                "education_verification":
                    data.get("education_verification"),
                "address_verification":
                    data.get("address_verification"),
                "identity_verification":
                    data.get("identity_verification"),
                "assigned_verification_agency":
                    data.get("assigned_verification_agency"),
                "supporting_bgv_dossier":
                    files.get("supporting_bgv_dossier"),
                "remarks":
                    data.get("remarks"),
            },
        )

    # --------------------------------------------------------
    # BANK - ONE OR MORE
    # --------------------------------------------------------
    if any(
        key in data
        for key in (
            "bank_name",
            "account_number",
            "ifsc_code",
            "account_type",
            "account_holder_name",
            "branch_name",
            "upi_id",
        )
    ):
        account_number = data.get("account_number")
        ifsc_code = data.get("ifsc_code")

        if account_number and ifsc_code:
            BankAccount.objects.update_or_create(
                employee=employee,
                account_number=account_number,
                ifsc_code=ifsc_code,
                defaults={
                    "bank_name": data.get("bank_name") or "",
                    "account_type": data.get("account_type"),
                    "account_holder_name": data.get("account_holder_name"),
                    "branch_name": data.get("branch_name"),
                    "cancelled_cheque": files.get("cancelled_cheque"),
                    "upi_id": data.get("upi_id"),
                    "active": True,
                },
            )

    # --------------------------------------------------------
    # GENERIC EMPLOYEE DOCUMENT
    # --------------------------------------------------------
    # Accept:
    # document_name
    # document_type
    # document / file
    #
    # Multiple documents can be sent as:
    # document_name[] / document_type[] / document[] only when
    # the client sends them as indexed fields.
    document_file = (
        files.get("document")
        or files.get("file")
    )

    document_name = data.get("document_name")
    document_type = data.get("document_type")

    if document_file and document_name and document_type:
        EmployeeDocument.objects.create(
            company=employee.company,
            employee=employee,
            document_name=document_name,
            document_type=document_type,
            file=document_file,
            is_verified=_bool_value(
                data.get("document_is_verified"),
                False,
            ),
            verified_by=data.get("document_verified_by"),
            expiry_date=data.get("document_expiry_date") or None,
            remarks=data.get("document_remarks"),
        )


# ============================================================
# ADD EMPLOYEE / CANDIDATE
# ============================================================

@api_view(["POST"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
@parser_classes([
    parsers.MultiPartParser,
    parsers.FormParser,
    parsers.JSONParser,
])
@transaction.atomic
def add_employee(request):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    data = request.data
    files = request.FILES

    name = data.get("name")
    email = data.get("email")

    if not name or not email:
        return Response({
            "status": False,
            "message": "name and email are required",
        }, status=400)

    if EmployeeDT.objects.filter(
        company=company,
        email__iexact=email,
    ).exists():
        return Response({
            "status": False,
            "message": "Email already exists in your company",
        }, status=400)

    # --------------------------------------------------------
    # Full EmployeeDT field mapping.
    # Existing fields are intentionally retained.
    # --------------------------------------------------------
    employee_fields = {
        "name": name,
        "email": email,
        "phone_number": data.get("phone_number"),
        "password": data.get("password"),
        "verify_code": data.get("verify_code"),

        "Work_sift": data.get("Work_sift"),
        "Employ_check_id": data.get("Employ_check_id"),
        "check_st": data.get("check_st"),

        "Date_of_Birth": _date_value(data.get("Date_of_Birth") or data.get("date_of_birth")),
        "Gender": data.get("Gender") or data.get("gender"),
        "Blood_Group": data.get("Blood_Group"),
        "Marital_Status": data.get("Marital_Status"),
        "Marriage_Anniversary": _date_value(data.get("Marriage_Anniversary")),
        "Personal_Email": data.get("Personal_Email"),
        "Alternate_Phone_Number": data.get("Alternate_Phone_Number"),
        "Current_Address": data.get("Current_Address") or data.get("address"),
        "Permanent_Address": data.get("Permanent_Address"),
        "House_Type": data.get("House_Type"),
        "Staying_at_Current_Residence_Since": data.get("Staying_at_Current_Residence_Since"),
        "Living_in_Current_City_Since": data.get("Living_in_Current_City_Since"),

        "Date_of_Joining": _date_value(
            data.get("Date_of_Joining") or data.get("joining_date")
        ),
        "Basic_Salary": _decimal_value(data.get("Basic_Salary")) if data.get("Basic_Salary") not in (None, "") else None,
        "Overtime_Rate": _decimal_value(data.get("Overtime_Rate")) if data.get("Overtime_Rate") not in (None, "") else None,
        "Work_hours": data.get("Work_hours") or None,
        "PF_Percentage": _decimal_value(data.get("PF_Percentage")) if data.get("PF_Percentage") not in (None, "") else None,
        "TDS_Percentage": _decimal_value(data.get("TDS_Percentage")) if data.get("TDS_Percentage") not in (None, "") else None,
        "ESI_Percentage": _decimal_value(data.get("ESI_Percentage")) if data.get("ESI_Percentage") not in (None, "") else None,
        "saturday_policy": data.get("saturday_policy") or "FULL",

        "aadhaar_number": data.get("aadhaar_number"),
        "pan_number": data.get("pan_number"),
        "pf_number": data.get("pf_number"),
        "esi_number": data.get("esi_number"),

        "Probation_Period": data.get("Probation_Period"),
        "Employee_Type": data.get("Employee_Type") or data.get("employee_type"),
        "Work_Location": data.get("Work_Location"),
        "Employee_Status": data.get("Employee_Status") or data.get("employee_status"),
        "Work_Experience": data.get("Work_Experience"),
        "Designation": data.get("Designation") or data.get("designation"),
        "Job_Title": data.get("Job_Title"),
        "Department": data.get("Department") or data.get("department"),
        "Sub_Department": data.get("Sub_Department"),
        "WORK_HISTORY": data.get("WORK_HISTORY"),
        "Resignation_Date": data.get("Resignation_Date"),
        "Resignation_Status": data.get("Resignation_Status"),
        "Notice_Period": data.get("Notice_Period"),
        "Last_Working_Day": data.get("Last_Working_Day"),

        "team_Name": data.get("team_Name"),
        "team_type": data.get("team_type"),
        "team_Department": data.get("team_Department"),
        "team_Designation": data.get("team_Designation"),

        "EDUCATIONAL_INFO": data.get("EDUCATIONAL_INFO"),
        "Family_Name": data.get("Family_Name"),
        "Family_Relationship": data.get("Family_Relationship"),
        "Family_Phone_Number": data.get("Family_Phone_Number"),

        # Candidate
        "applied_position": data.get("applied_position"),
        "candidate_source": data.get("candidate_source") or data.get("source"),
        "recruiter_name": data.get("recruiter_name") or data.get("recruiter"),
        "expected_joining_date": _date_value(data.get("expected_joining_date")),
        "candidate_status": data.get("candidate_status") or "APPLIED",
        "same_as_current_address": _bool_value(
            data.get("same_as_current_address"),
            False,
        ),
        "Current_Notice_Period": data.get("Current_Notice_Period") or data.get("notice_period"),
    }

    # If same-address was selected, copy current to permanent.
    if employee_fields["same_as_current_address"]:
        employee_fields["Permanent_Address"] = employee_fields["Current_Address"]

    # Files stored directly on EmployeeDT - kept for backward
    # compatibility with the expanded model.
    employee_fields["verify_image"] = files.get("verify_image")
    employee_fields["profile_image"] = files.get("profile_image")
    employee_fields["image"] = files.get("image")
    employee_fields["resume"] = files.get("resume")
    employee_fields["aadhaar_id_proof"] = files.get("aadhaar_id_proof")
    employee_fields["pan_card"] = files.get("pan_card")
    employee_fields["address_proof"] = files.get("address_proof")
    employee_fields["passport_photo"] = files.get("passport_photo")
    employee_fields["educational_certificates"] = files.get(
        "educational_certificates"
    )

    employee = EmployeeDT.objects.create(
        company=company,
        is_active=_bool_value(data.get("is_active"), True),
        **employee_fields,
    )

    # M2M old fields remain supported.
    # Send IDs in work_week_ids / extra_off_ids.
    work_week_ids = data.getlist("work_week_ids") if hasattr(data, "getlist") else []
    extra_off_ids = data.getlist("extra_off_ids") if hasattr(data, "getlist") else []

    if work_week_ids:
        employee.work_week.set(work_week_ids)

    if extra_off_ids:
        employee.extra_off.set(extra_off_ids)

    _create_candidate_related_data(employee, data, files)

    # Optional employee login account.
    username = data.get("username")
    role_code = data.get("role_code")

    if username or role_code:
        role = None

        if role_code:
            role, _ = EmployeeRole.objects.get_or_create(
                company=company,
                role_code=role_code,
                defaults={
                    "role_name": role_code.replace("_", " ").title(),
                },
            )

        EmployeeAccount.objects.get_or_create(
            employee=employee,
            defaults={
                "role": role,
                "is_login_enabled": _bool_value(
                    data.get("is_login_enabled"),
                    True,
                ),
                "is_verified": _bool_value(
                    data.get("is_verified"),
                    True,
                ),
            },
        )

    # Review / submit state.
    if _bool_value(data.get("application_submitted"), False):
        employee.application_submitted = True
        employee.application_submitted_at = timezone.now()
        employee.save(
            update_fields=[
                "application_submitted",
                "application_submitted_at",
                "updated_at",
            ]
        )

    return Response({
        "status": True,
        "message": "Employee / candidate created successfully",
        "data": _serialize_employee(employee),
    }, status=201)


# ============================================================
# UPDATE EMPLOYEE / CANDIDATE
# ============================================================

@api_view(["POST", "PUT", "PATCH"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
@parser_classes([
    parsers.MultiPartParser,
    parsers.FormParser,
    parsers.JSONParser,
])
@transaction.atomic
def update_employee(request, employee_id):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    employee = get_object_or_404(
        EmployeeDT,
        id=employee_id,
        company=company,
    )

    data = request.data
    files = request.FILES

    # Editable EmployeeDT fields. employee_code and company are
    # deliberately never changed by this endpoint.
    editable_fields = [
        "name",
        "phone_number",
        "verify_code",
        "Work_sift",
        "Employ_check_id",
        "check_st",
        "Date_of_Birth",
        "Gender",
        "Blood_Group",
        "Marital_Status",
        "Marriage_Anniversary",
        "Personal_Email",
        "Alternate_Phone_Number",
        "Current_Address",
        "Permanent_Address",
        "House_Type",
        "Staying_at_Current_Residence_Since",
        "Living_in_Current_City_Since",
        "Date_of_Joining",
        "Basic_Salary",
        "Overtime_Rate",
        "Work_hours",
        "PF_Percentage",
        "TDS_Percentage",
        "ESI_Percentage",
        "saturday_policy",
        "aadhaar_number",
        "pan_number",
        "pf_number",
        "esi_number",
        "Probation_Period",
        "Employee_Type",
        "Work_Location",
        "Employee_Status",
        "Work_Experience",
        "Designation",
        "Job_Title",
        "Department",
        "Sub_Department",
        "WORK_HISTORY",
        "Resignation_Date",
        "Resignation_Status",
        "Notice_Period",
        "Last_Working_Day",
        "team_Name",
        "team_type",
        "team_Department",
        "team_Designation",
        "EDUCATIONAL_INFO",
        "Family_Name",
        "Family_Relationship",
        "Family_Phone_Number",
        "applied_position",
        "candidate_source",
        "recruiter_name",
        "candidate_status",
        "Current_Notice_Period",
    ]

    for field in editable_fields:
        if field not in data:
            continue

        value = data.get(field)

        if field in (
            "Date_of_Birth",
            "Marriage_Anniversary",
            "Date_of_Joining",
        ):
            value = _date_value(value)

        if field in (
            "Basic_Salary",
            "Overtime_Rate",
            "PF_Percentage",
            "TDS_Percentage",
            "ESI_Percentage",
        ):
            value = _decimal_value(value)

        setattr(employee, field, value)

    # Candidate aliases used by the frontend.
    if "gender" in data:
        employee.Gender = data.get("gender")

    if "department" in data:
        employee.Department = data.get("department")

    if "designation" in data:
        employee.Designation = data.get("designation")

    if "employee_type" in data:
        employee.Employee_Type = data.get("employee_type")

    if "employee_status" in data:
        employee.Employee_Status = data.get("employee_status")

    if "joining_date" in data:
        employee.Date_of_Joining = _date_value(data.get("joining_date"))

    if "date_of_birth" in data:
        employee.Date_of_Birth = _date_value(data.get("date_of_birth"))

    if "address" in data:
        employee.Current_Address = data.get("address")

    if "expected_joining_date" in data:
        employee.expected_joining_date = _date_value(
            data.get("expected_joining_date")
        )

    if "same_as_current_address" in data:
        employee.same_as_current_address = _bool_value(
            data.get("same_as_current_address"),
            False,
        )

        if employee.same_as_current_address:
            employee.Permanent_Address = employee.Current_Address

    if "application_submitted" in data:
        submitted = _bool_value(
            data.get("application_submitted"),
            False,
        )
        employee.application_submitted = submitted

        if submitted and not employee.application_submitted_at:
            employee.application_submitted_at = timezone.now()

    # Email remains company-scoped by this project's existing
    # CRUD rule.
    new_email = data.get("email")

    if new_email and new_email != employee.email:
        if EmployeeDT.objects.filter(
            company=company,
            email__iexact=new_email,
        ).exclude(id=employee.id).exists():
            return Response({
                "status": False,
                "message": "Email already exists in your company",
            }, status=400)

        employee.email = new_email

    # Existing login behavior is retained.
    if data.get("password"):
        employee.password = data.get("password")

    # Existing and new document fields.
    file_fields = [
        "verify_image",
        "profile_image",
        "image",
        "resume",
        "aadhaar_id_proof",
        "pan_card",
        "address_proof",
        "passport_photo",
        "educational_certificates",
    ]

    for field in file_fields:
        if files.get(field):
            setattr(employee, field, files.get(field))

    employee.save()

    _create_candidate_related_data(employee, data, files)

    # Update/create login account if requested.
    role_code = data.get("role_code")

    if role_code or "is_login_enabled" in data or "is_verified" in data:
        role = None

        if role_code:
            role, _ = EmployeeRole.objects.get_or_create(
                company=company,
                role_code=role_code,
                defaults={
                    "role_name": role_code.replace("_", " ").title(),
                },
            )

        account, _ = EmployeeAccount.objects.get_or_create(
            employee=employee
        )

        if role is not None:
            account.role = role

        if "is_login_enabled" in data:
            account.is_login_enabled = _bool_value(
                data.get("is_login_enabled"),
                account.is_login_enabled,
            )

        if "is_verified" in data:
            account.is_verified = _bool_value(
                data.get("is_verified"),
                account.is_verified,
            )

        account.save()

    return Response({
        "status": True,
        "message": "Employee / candidate updated successfully",
        "data": _serialize_employee(employee),
    })


# ============================================================
# LIST EMPLOYEES / CANDIDATES
# ============================================================

@api_view(["GET"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
def list_employees(request):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    employees = EmployeeDT.objects.filter(
        company=company
    ).prefetch_related(
        "documents",
        "educational_history",
        "professional_experience",
        "bank_accounts",
    )

    search = request.GET.get("search")

    if search:
        employees = employees.filter(
            Q(name__icontains=search)
            | Q(email__icontains=search)
            | Q(phone_number__icontains=search)
            | Q(employee_code__icontains=search)
            | Q(candidate_id__icontains=search)
            | Q(Department__icontains=search)
            | Q(Designation__icontains=search)
            | Q(Job_Title__icontains=search)
            | Q(applied_position__icontains=search)
            | Q(candidate_source__icontains=search)
            | Q(recruiter_name__icontains=search)
            | Q(candidate_status__icontains=search)
        )

    is_active = request.GET.get("is_active")
    if is_active is not None:
        employees = employees.filter(
            is_active=_bool_value(is_active, False)
        )

    department = request.GET.get("department")
    if department:
        employees = employees.filter(
            Department__iexact=department
        )

    candidate_status = request.GET.get("candidate_status")
    if candidate_status:
        employees = employees.filter(
            candidate_status__iexact=candidate_status
        )

    candidate_source = request.GET.get("candidate_source")
    if candidate_source:
        employees = employees.filter(
            candidate_source__iexact=candidate_source
        )

    employees = employees.order_by("-id")

    data = [_serialize_employee(e) for e in employees]

    return Response({
        "status": True,
        "count": len(data),
        "data": data,
    })


# ============================================================
# EMPLOYEE / CANDIDATE DETAIL
# ============================================================

@api_view(["GET"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
def employee_detail(request):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    employee_code = request.GET.get("employee_code")
    candidate_id = request.GET.get("candidate_id")

    if not employee_code and not candidate_id:
        return Response({
            "status": False,
            "message": "employee_code or candidate_id required",
        }, status=400)

    if candidate_id:
        employee = get_object_or_404(
            EmployeeDT,
            candidate_id=candidate_id,
            company=company,
        )
    else:
        employee = get_object_or_404(
            EmployeeDT,
            employee_code=employee_code,
            company=company,
        )

    return Response({
        "status": True,
        "data": _serialize_employee(employee),
    })


# ============================================================
# EMPLOYEE DOCUMENT LIST
# ============================================================

@api_view(["GET"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
def employee_documents(request, employee_id):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    employee = get_object_or_404(
        EmployeeDT,
        id=employee_id,
        company=company,
    )

    documents = employee.documents.all()

    return Response({
        "status": True,
        "count": documents.count(),
        "data": EmployeeDocumentSerializer(
            documents,
            many=True,
        ).data,
    })


# ============================================================
# ADD EMPLOYEE DOCUMENT
# ============================================================

@api_view(["POST"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
@parser_classes([
    parsers.MultiPartParser,
    parsers.FormParser,
])
def add_employee_document(request, employee_id):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    employee = get_object_or_404(
        EmployeeDT,
        id=employee_id,
        company=company,
    )

    document_file = (
        request.FILES.get("file")
        or request.FILES.get("document")
    )

    document_name = request.data.get("document_name")
    document_type = request.data.get("document_type")

    if not document_file or not document_name or not document_type:
        return Response({
            "status": False,
            "message": "document_name, document_type and file are required",
        }, status=400)

    document = EmployeeDocument.objects.create(
        company=company,
        employee=employee,
        document_name=document_name,
        document_type=document_type,
        file=document_file,
        is_verified=_bool_value(
            request.data.get("is_verified"),
            False,
        ),
        verified_by=request.data.get("verified_by"),
        expiry_date=_date_value(
            request.data.get("expiry_date")
        ),
        remarks=request.data.get("remarks"),
    )

    return Response({
        "status": True,
        "message": "Employee document uploaded successfully",
        "data": EmployeeDocumentSerializer(document).data,
    }, status=201)


# ============================================================
# DELETE EMPLOYEE DOCUMENT
# ============================================================

@api_view(["DELETE", "POST"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
def delete_employee_document(request, document_id):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    document = get_object_or_404(
        EmployeeDocument,
        id=document_id,
        company=company,
    )

    document.delete()

    return Response({
        "status": True,
        "message": "Employee document deleted successfully",
    })


# ============================================================
# BANK ACCOUNT LIST
# ============================================================

@api_view(["GET"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
def employee_bank_accounts(request, employee_id):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    employee = get_object_or_404(
        EmployeeDT,
        id=employee_id,
        company=company,
    )

    accounts = employee.bank_accounts.all()

    return Response({
        "status": True,
        "count": accounts.count(),
        "data": BankAccountSerializer(
            accounts,
            many=True,
        ).data,
    })


# ============================================================
# DELETE EMPLOYEE
# ============================================================

@api_view(["POST", "DELETE"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHR])
def delete_employee(request):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    data = request.data
    employee_code = data.get("employee_code")
    candidate_id = data.get("candidate_id")

    if not employee_code and not candidate_id:
        return Response({
            "status": False,
            "message": "employee_code or candidate_id required",
        }, status=400)

    if candidate_id:
        employee = get_object_or_404(
            EmployeeDT,
            candidate_id=candidate_id,
            company=company,
        )
    else:
        employee = get_object_or_404(
            EmployeeDT,
            employee_code=employee_code,
            company=company,
        )

    employee.delete()

    return Response({
        "status": True,
        "message": "Employee deleted successfully",
    }) 
