from django.db import models
from django.utils import timezone
from django.utils.timezone import now
from django.db.models.signals import pre_save
from django.dispatch import receiver
from decimal import Decimal
from datetime import date
import uuid

from Company.models import company_details

# ============================================================
# HELPER
# ============================================================

def generate_employee_code():
    return uuid.uuid4().hex[:8].upper()


def generate_candidate_id():
    return "CAN-" + uuid.uuid4().hex[:10].upper()


# ============================================================
# DAY OFF
# ============================================================

class DayOff(models.Model):

    date = models.DateField()

    employee_code = models.CharField(
        max_length=50,
        blank=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):

        return self.date.strftime("%Y-%m-%d")


# ============================================================
# EXTRA OFF
# ============================================================

class ExtraOff(models.Model):

    date = models.DateField()

    employee_code = models.CharField(
        max_length=50,
        blank=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):

        return self.date.strftime("%Y-%m-%d")


# ============================================================
# EMPLOYEE ROLE
# ============================================================

class EmployeeRole(models.Model):

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="employee_roles"
    )

    role_name = models.CharField(
        max_length=100
    )

    role_code = models.CharField(
        max_length=50
    )

    description = models.TextField(
        blank=True,
        null=True
    )

    is_active = models.BooleanField(
        default=True
    )

    # ========================================================
    # DASHBOARD
    # ========================================================

    can_view_dashboard = models.BooleanField(
        default=True
    )

    # ========================================================
    # EMPLOYEE
    # ========================================================

    can_view_employees = models.BooleanField(
        default=True
    )

    can_create_employees = models.BooleanField(
        default=False
    )

    can_edit_employees = models.BooleanField(
        default=False
    )

    can_delete_employees = models.BooleanField(
        default=False
    )

    can_manage_employees = models.BooleanField(
        default=False
    )

    # ========================================================
    # ATTENDANCE
    # ========================================================

    can_view_attendance = models.BooleanField(
        default=False
    )

    can_create_attendance = models.BooleanField(
        default=False
    )

    can_edit_attendance = models.BooleanField(
        default=False
    )

    can_delete_attendance = models.BooleanField(
        default=False
    )

    can_manage_attendance = models.BooleanField(
        default=False
    )

    # ========================================================
    # PAYROLL
    # ========================================================

    can_view_payroll = models.BooleanField(
        default=False
    )

    can_create_payroll = models.BooleanField(
        default=False
    )

    can_edit_payroll = models.BooleanField(
        default=False
    )

    can_delete_payroll = models.BooleanField(
        default=False
    )

    can_manage_payroll = models.BooleanField(
        default=False
    )

    # ========================================================
    # LEAVE
    # ========================================================

    can_view_leave = models.BooleanField(
        default=False
    )

    can_create_leave = models.BooleanField(
        default=False
    )

    can_approve_leave = models.BooleanField(
        default=False
    )

    can_manage_leave = models.BooleanField(
        default=False
    )

    # ========================================================
    # PERFORMANCE (ADDITIVE - Performance Management & OKRs)
    # ========================================================

    can_view_performance = models.BooleanField(
        default=False
    )

    can_create_performance = models.BooleanField(
        default=False
    )

    can_edit_performance = models.BooleanField(
        default=False
    )

    can_delete_performance = models.BooleanField(
        default=False
    )

    can_manage_performance = models.BooleanField(
        default=False
    )

    # ========================================================
    # EXPENSE
    # ========================================================

    can_view_expense = models.BooleanField(
        default=False
    )

    can_create_expense = models.BooleanField(
        default=False
    )

    can_edit_expense = models.BooleanField(
        default=False
    )

    can_delete_expense = models.BooleanField(
        default=False
    )

    can_manage_expense = models.BooleanField(
        default=False
    )

    # ========================================================
    # INVOICE
    # ========================================================

    can_view_invoice = models.BooleanField(
        default=False
    )

    can_create_invoice = models.BooleanField(
        default=False
    )

    can_edit_invoice = models.BooleanField(
        default=False
    )

    can_delete_invoice = models.BooleanField(
        default=False
    )

    can_manage_invoice = models.BooleanField(
        default=False
    )

    # ========================================================
    # BANK
    # ========================================================

    can_view_bank = models.BooleanField(
        default=False
    )

    can_manage_bank = models.BooleanField(
        default=False
    )

    # ========================================================
    # REPORTS
    # ========================================================

    can_view_reports = models.BooleanField(
        default=True
    )

    can_manage_reports = models.BooleanField(
        default=False
    )

    # ========================================================
    # DEVICE / BIOMETRIC
    # ========================================================

    can_view_devices = models.BooleanField(
        default=False
    )

    can_create_devices = models.BooleanField(
        default=False
    )

    can_edit_devices = models.BooleanField(
        default=False
    )

    can_delete_devices = models.BooleanField(
        default=False
    )

    can_manage_devices = models.BooleanField(
        default=False
    )

    # ========================================================
    # COMPANY
    # ========================================================

    can_view_company = models.BooleanField(
        default=False
    )

    can_edit_company = models.BooleanField(
        default=False
    )

    can_manage_company = models.BooleanField(
        default=False
    )
    
    # ========================================================
    # INSURANCE
    # ========================================================

    can_view_insurance = models.BooleanField(
        default=False
    )

    can_create_insurance = models.BooleanField(
        default=False
    )

    can_edit_insurance = models.BooleanField(
        default=False
    )

    can_delete_insurance = models.BooleanField(
        default=False
    )

    can_approve_insurance = models.BooleanField(
        default=False
    )

    can_manage_insurance = models.BooleanField(
        default=False
    )
    # ========================================================
    # ROLES
    # ========================================================

    can_view_roles = models.BooleanField(
        default=False
    )

    can_create_roles = models.BooleanField(
        default=False
    )

    can_edit_roles = models.BooleanField(
        default=False
    )

    can_delete_roles = models.BooleanField(
        default=False
    )

    can_manage_roles = models.BooleanField(
        default=False
    )

    # ========================================================
    # RECRUITMENT - Recruitment & Talent Acquisition (candidates, requisitions, interviews, offers, BGV, joining)
    # ========================================================

    can_view_recruitment = models.BooleanField(
        default=False
    )

    can_create_recruitment = models.BooleanField(
        default=False
    )

    can_edit_recruitment = models.BooleanField(
        default=False
    )

    can_delete_recruitment = models.BooleanField(
        default=False
    )

    can_manage_recruitment = models.BooleanField(
        default=False
    )

    # ========================================================
    # TRAINING - Training & Development (programs, sessions, enrollments, certificates)
    # ========================================================

    can_view_training = models.BooleanField(
        default=False
    )

    can_create_training = models.BooleanField(
        default=False
    )

    can_edit_training = models.BooleanField(
        default=False
    )

    can_delete_training = models.BooleanField(
        default=False
    )

    can_manage_training = models.BooleanField(
        default=False
    )

    # ========================================================
    # COMMUNICATION - Communication (announcements, chat, meetings, calendar)
    # ========================================================

    can_view_communication = models.BooleanField(
        default=False
    )

    can_create_communication = models.BooleanField(
        default=False
    )

    can_edit_communication = models.BooleanField(
        default=False
    )

    can_delete_communication = models.BooleanField(
        default=False
    )

    can_manage_communication = models.BooleanField(
        default=False
    )

    # ========================================================
    # TIMESHEET - Timesheet & Projects
    # ========================================================

    can_view_timesheet = models.BooleanField(
        default=False
    )

    can_create_timesheet = models.BooleanField(
        default=False
    )

    can_edit_timesheet = models.BooleanField(
        default=False
    )

    can_delete_timesheet = models.BooleanField(
        default=False
    )

    can_manage_timesheet = models.BooleanField(
        default=False
    )

    # ========================================================
    # RELATIONS - Employee Relations (cases, discipline, legal)
    # ========================================================

    can_view_relations = models.BooleanField(
        default=False
    )

    can_create_relations = models.BooleanField(
        default=False
    )

    can_edit_relations = models.BooleanField(
        default=False
    )

    can_delete_relations = models.BooleanField(
        default=False
    )

    can_manage_relations = models.BooleanField(
        default=False
    )

    # ========================================================
    # COMPLIANCE - Statutory Compliance (PF / ESIC / PT / TDS / LWF filings)
    # ========================================================

    can_view_compliance = models.BooleanField(
        default=False
    )

    can_create_compliance = models.BooleanField(
        default=False
    )

    can_edit_compliance = models.BooleanField(
        default=False
    )

    can_delete_compliance = models.BooleanField(
        default=False
    )

    can_manage_compliance = models.BooleanField(
        default=False
    )

    # ========================================================
    # AI
    # ========================================================

    can_use_ai = models.BooleanField(
        default=False
    )

    # ========================================================
    # MOBILE
    # ========================================================

    can_use_mobile_app = models.BooleanField(
        default=True
    )

    # ========================================================
    # AUDIT
    # ========================================================

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    updated_at = models.DateTimeField(
        auto_now=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )

    class Meta:

        constraints = [
            models.UniqueConstraint(
                fields=[
                    "company",
                    "role_code"
                ],
                name="unique_company_role_code"
            )
        ]

        indexes = [
            models.Index(
                fields=[
                    "company",
                    "is_active"
                ]
            )
        ]

    def __str__(self):

        return (
            f"{self.company} - "
            f"{self.role_name}"
        )


# ============================================================
# ADDITIVE: DEPARTMENT
# ------------------------------------------------------------
# Each company creates and manages its own list of departments
# (e.g. Sales, Accounts, Production). This does NOT touch the
# existing free-text `Department` / `Sub_Department` /
# `team_Department` CharFields on EmployeeDT below - those are
# kept as-is for backward compatibility. A new `department` FK
# field is added on EmployeeDT (further below) that HR/Admin can
# optionally set by picking one of these company-scoped rows.
# ============================================================

class Department(models.Model):

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="departments"
    )

    name = models.CharField(
        max_length=150
    )

    code = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    description = models.TextField(
        blank=True,
        null=True
    )

    is_active = models.BooleanField(
        default=True
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    updated_at = models.DateTimeField(
        auto_now=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )

    class Meta:

        constraints = [
            models.UniqueConstraint(
                fields=[
                    "company",
                    "name"
                ],
                name="unique_company_department_name"
            )
        ]

        indexes = [
            models.Index(
                fields=[
                    "company",
                    "is_active"
                ]
            )
        ]

        ordering = ["name"]

    def __str__(self):

        return (
            f"{self.company} - "
            f"{self.name}"
        )


# ============================================================
# EMPLOYEE
# ============================================================

class EmployeeDT(models.Model):

    employee_code = models.CharField(
        max_length=8,
        unique=True,
        blank=True,
        default=generate_employee_code
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="employees"
    )

    is_active = models.BooleanField(
        default=True,
        db_index=True
    )

    # ========================================================
    # SHIFT
    # ========================================================

    SHIFT_CHOICES = [
        ("Day Shift", "Day Shift"),
        ("Night Shift", "Night Shift"),
    ]

    Work_sift = models.CharField(
        max_length=90,
        choices=SHIFT_CHOICES,
        blank=True,
        null=True
    )

    Employ_check_id = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    check_st = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    verify_image = models.ImageField(
        upload_to="atendanc/",
        blank=True,
        null=True
    )

    profile_image = models.ImageField(
        upload_to="profile_images/",
        blank=True,
        null=True
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    updated_at = models.DateTimeField(
        auto_now=True
    )

    # ========================================================
    # BASIC INFORMATION
    # ========================================================

    name = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    # Login identifier for employees (replaces the old
    # EmployeeAccount.username field). Unique so it can be
    # used to look accounts up at login time; still optional
    # since not every EmployeeDT necessarily has a linked
    # EmployeeAccount.
    email = models.EmailField(
        blank=True,
        null=True,
        unique=True
    )

    # Existing field - KEPT
    password = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    phone_number = models.CharField(
        max_length=15,
        blank=True,
        null=True
    )

    verify_code = models.CharField(
        max_length=15,
        blank=True,
        null=True
    )

    # ========================================================
    # PERSONAL
    # ========================================================

    image = models.ImageField(
        upload_to="photos/",
        blank=True,
        null=True
    )

    Date_of_Birth = models.DateField(
        verbose_name="Date of Birth",
        blank=True,
        null=True
    )

    Gender = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    Blood_Group = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    Marital_Status = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    Marriage_Anniversary = models.DateField(
        verbose_name="Marriage Anniversary",
        blank=True,
        null=True
    )

    Personal_Email = models.EmailField(
        blank=True,
        null=True
    )

    Alternate_Phone_Number = models.CharField(
        max_length=15,
        blank=True,
        null=True
    )

    Current_Address = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    Permanent_Address = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    House_Type = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    Staying_at_Current_Residence_Since = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    Living_in_Current_City_Since = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    # ========================================================
    # WORK
    # ========================================================

    Date_of_Joining = models.DateField(
        verbose_name="Date of Joining",
        blank=True,
        null=True
    )

    Basic_Salary = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        blank=True,
        null=True
    )

    Overtime_Rate = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=Decimal("50.00"),
        blank=True,
        null=True
    )

    Work_hours = models.IntegerField(
        blank=True,
        null=True
    )

    PF_Percentage = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=Decimal("0.00"),
        blank=True,
        null=True
    )

    TDS_Percentage = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=Decimal("0.00"),
        blank=True,
        null=True
    )

    ESI_Percentage = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=Decimal("0.00"),
        blank=True,
        null=True
    )

    # ========================================================
    # SATURDAY
    # ========================================================

    SATURDAY_POLICY = [
        ("OFF", "Saturday Off"),
        ("HALF", "Half Day"),
        ("FULL", "Full Working Day"),
    ]

    saturday_policy = models.CharField(
        max_length=10,
        choices=SATURDAY_POLICY,
        default="FULL"
    )

    # ========================================================
    # GOVERNMENT / STATUTORY
    # ========================================================

    aadhaar_number = models.CharField(
        max_length=12,
        blank=True,
        null=True
    )

    pan_number = models.CharField(
        max_length=10,
        blank=True,
        null=True
    )

    pf_number = models.CharField(
        max_length=25,
        blank=True,
        null=True
    )

    esi_number = models.CharField(
        max_length=25,
        blank=True,
        null=True
    )

    # ========================================================
    # EMPLOYMENT
    # ========================================================

    Probation_Period = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    Employee_Type = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    Work_Location = models.CharField(
        max_length=300,
        blank=True,
        null=True
    )

    Employee_Status = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    Work_Experience = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    Designation = models.CharField(
        max_length=200,
        blank=True,
        null=True
    )

    Job_Title = models.CharField(
        max_length=200,
        blank=True,
        null=True
    )

    Department = models.CharField(
        max_length=200,
        blank=True,
        null=True
    )

    # ADDITIVE: proper FK to the company-scoped Department model
    # above. Kept separate from the legacy `Department` CharField
    # above (not removed / not renamed) so existing code reading
    # `employee.Department` keeps working untouched. New HR/Admin
    # screens should prefer this `department` FK going forward.
    department = models.ForeignKey(
        "Department",
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        related_name="employees"
    )

    Sub_Department = models.CharField(
        max_length=200,
        blank=True,
        null=True
    )

    WORK_HISTORY = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    Resignation_Date = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    Resignation_Status = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    Notice_Period = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    Last_Working_Day = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    # ========================================================
    # TEAM
    # ========================================================

    team_Name = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    team_type = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    team_Department = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    team_Designation = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    # ========================================================
    # EDUCATION
    # ========================================================

    EDUCATIONAL_INFO = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    # ========================================================
    # FAMILY
    # ========================================================

    Family_Name = models.CharField(
        max_length=200,
        blank=True,
        null=True
    )

    Family_Relationship = models.CharField(
        max_length=200,
        blank=True,
        null=True
    )

    Family_Phone_Number = models.CharField(
        max_length=200,
        blank=True,
        null=True
    )

    # ========================================================
    # WEEK / OFF
    # ========================================================

    work_week = models.ManyToManyField(
        DayOff,
        blank=True
    )

    extra_off = models.ManyToManyField(
        ExtraOff,
        blank=True
    )

    # ========================================================
    # CANDIDATE / RECRUITMENT
    # ========================================================

    candidate_id = models.CharField(
        max_length=20,
        unique=True,
        blank=True,
        null=True,
        default=None,
        db_index=True,
    )

    applied_position = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    candidate_source = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    recruiter_name = models.CharField(
        max_length=150,
        blank=True,
        null=True,
    )

    expected_joining_date = models.DateField(
        blank=True,
        null=True,
    )

    candidate_status = models.CharField(
        max_length=50,
        default="APPLIED",
        blank=True,
    )

    same_as_current_address = models.BooleanField(
        default=False,
    )

    application_submitted = models.BooleanField(
        default=False,
    )

    application_submitted_at = models.DateTimeField(
        blank=True,
        null=True,
    )

    # Keep the existing Notice_Period field. This field is for
    # candidate-stage notice-period information when needed.
    Current_Notice_Period = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    def save(self, *args, **kwargs):
        # Generate a candidate ID only when a new employee/candidate
        # does not already have one. Keeping the database field
        # nullable prevents SQLite migrations from assigning one
        # identical UUID to every existing row.
        if not self.candidate_id:
            self.candidate_id = generate_candidate_id()

        super().save(*args, **kwargs)

    # ========================================================
    # CANDIDATE DOCUMENTS
    # ========================================================

    resume = models.FileField(
        upload_to="candidate_documents/resumes/",
        blank=True,
        null=True,
    )

    aadhaar_id_proof = models.FileField(
        upload_to="candidate_documents/id_proof/",
        blank=True,
        null=True,
    )

    pan_card = models.FileField(
        upload_to="candidate_documents/pan/",
        blank=True,
        null=True,
    )

    address_proof = models.FileField(
        upload_to="candidate_documents/address_proof/",
        blank=True,
        null=True,
    )

    passport_photo = models.ImageField(
        upload_to="candidate_documents/passport_photos/",
        blank=True,
        null=True,
    )

    educational_certificates = models.FileField(
        upload_to="candidate_documents/education/",
        blank=True,
        null=True,
    )

    key_certifications = models.TextField(
        blank=True,
        null=True,
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )

    def __str__(self):

        return (
            f"{self.employee_code} - "
            f"{self.name}"
        )

    class Meta:

        verbose_name = "User"
        verbose_name_plural = "Users"

        indexes = [
            models.Index(
                fields=[
                    "company",
                    "is_active"
                ]
            ),
            models.Index(
                fields=[
                    "company",
                    "employee_code"
                ]
            ),
            models.Index(
                fields=[
                    "company",
                    "email"
                ]
            )
        ]



# ============================================================
# EMPLOYEE DOCUMENTS
# ============================================================

def employee_document_upload_path(instance, filename):
    """
    Store documents under:
    media/companies/<company>/<employee_code>/<document_type>/<filename>
    """
    company_name = str(instance.company).strip() if instance.company else "company"
    company_name = "".join(
        char if char.isalnum() else "-"
        for char in company_name
    ).strip("-").lower()

    employee_code = instance.employee.employee_code or "employee"
    document_type = instance.document_type or "other"
    document_type = "".join(
        char if char.isalnum() else "-"
        for char in document_type
    ).strip("-").lower()

    return (
        f"companies/{company_name}/"
        f"employees/{employee_code}/"
        f"{document_type}/{filename}"
    )


class EmployeeDocument(models.Model):

    DOCUMENT_TYPE_CHOICES = [
        ("AADHAAR", "Aadhaar / ID Proof"),
        ("PAN", "PAN Card"),
        ("RESUME", "Resume"),
        ("ADDRESS_PROOF", "Address Proof"),
        ("PASSPORT_PHOTO", "Passport Photo"),
        ("EDUCATION", "Educational Certificate"),
        ("EXPERIENCE", "Experience / Relieving Letter"),
        ("BANK", "Cancelled Cheque / Bank Proof"),
        ("OFFER_LETTER", "Offer Letter"),
        ("APPOINTMENT_LETTER", "Appointment Letter"),
        ("SALARY_SLIP", "Salary Slip"),
        ("PF", "PF Document"),
        ("ESIC", "ESIC Document"),
        ("BGV", "Background Verification"),
        ("OTHER", "Other"),
    ]

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="employee_documents",
        db_index=True,
    )

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="documents",
    )

    document_type = models.CharField(
        max_length=50,
        choices=DOCUMENT_TYPE_CHOICES,
        db_index=True,
    )

    document_name = models.CharField(
        max_length=255,
        help_text="Human-readable document name, e.g. Rahul Aadhaar Card",
    )

    file = models.FileField(
        upload_to=employee_document_upload_path,
    )

    is_verified = models.BooleanField(
        default=False,
    )

    verified_by = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    verified_at = models.DateTimeField(
        blank=True,
        null=True,
    )

    expiry_date = models.DateField(
        blank=True,
        null=True,
    )

    remarks = models.TextField(
        blank=True,
        null=True,
    )

    uploaded_at = models.DateTimeField(
        auto_now_add=True,
    )

    updated_at = models.DateTimeField(
        auto_now=True,
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def save(self, *args, **kwargs):
        # Always keep the document company synchronized
        # with the employee's company for B2B tenant safety.
        if self.employee_id:
            self.company_id = self.employee.company_id
        super().save(*args, **kwargs)

    class Meta:
        ordering = ["-uploaded_at"]
        indexes = [
            models.Index(
                fields=["company", "employee"]
            ),
            models.Index(
                fields=["company", "document_type"]
            ),
            models.Index(
                fields=["employee", "document_type"]
            ),
        ]

    def __str__(self):
        return (
            f"{self.company} - "
            f"{self.employee.name or self.employee.employee_code} - "
            f"{self.document_name}"
        )


# ============================================================
# CANDIDATE EDUCATIONAL HISTORY
# ============================================================

class CandidateEducation(models.Model):

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="educational_history",
    )

    highest_qualification = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    degree_course = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    specialization_branch = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    university_board = models.CharField(
        max_length=250,
        blank=True,
        null=True,
    )

    college_institute = models.CharField(
        max_length=250,
        blank=True,
        null=True,
    )

    passing_year = models.PositiveIntegerField(
        blank=True,
        null=True,
    )

    percentage_cgpa = models.CharField(
        max_length=50,
        blank=True,
        null=True,
    )

    key_certifications = models.TextField(
        blank=True,
        null=True,
    )

    degree_certificate = models.FileField(
        upload_to="candidate_documents/degree_certificates/",
        blank=True,
        null=True,
    )

    created_at = models.DateTimeField(auto_now_add=True)

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    class Meta:
        ordering = ["-passing_year", "-created_at"]
        indexes = [
            models.Index(fields=["employee"]),
        ]

    def __str__(self):
        return f"{self.employee} - {self.degree_course or self.highest_qualification or 'Education'}"


# ============================================================
# CANDIDATE PROFESSIONAL EXPERIENCE
# ============================================================

class CandidateExperience(models.Model):

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="professional_experience",
    )

    company_name = models.CharField(
        max_length=250,
        blank=True,
        null=True,
    )

    designation = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    department = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    start_date = models.DateField(
        blank=True,
        null=True,
    )

    end_date = models.DateField(
        blank=True,
        null=True,
    )

    reason_for_leaving = models.TextField(
        blank=True,
        null=True,
    )

    previous_ctc = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    reporting_manager = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    reporting_role = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    core_responsibilities = models.TextField(
        blank=True,
        null=True,
    )

    experience_reliving_proof = models.FileField(
        upload_to="candidate_documents/experience/",
        blank=True,
        null=True,
    )

    created_at = models.DateTimeField(auto_now_add=True)

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    class Meta:
        ordering = ["-start_date", "-created_at"]
        indexes = [
            models.Index(fields=["employee"]),
            models.Index(fields=["company_name"]),
        ]

    def __str__(self):
        return f"{self.employee} - {self.company_name or 'Experience'}"


# ============================================================
# CANDIDATE COMPENSATION PACKAGE
# ============================================================

class CandidateCompensation(models.Model):

    employee = models.OneToOneField(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="compensation_package",
    )

    current_annual_ctc = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    expected_annual_ctc = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    offered_annual_ctc = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    basic_salary = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    hra = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    special_allowance = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    provident_fund = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    esic = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    professional_tax = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    gross_salary = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    net_in_hand_salary = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        blank=True,
        null=True,
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):
        return f"Compensation - {self.employee}"


# ============================================================
# CANDIDATE BACKGROUND VERIFICATION
# ============================================================

class CandidateBGV(models.Model):

    employee = models.OneToOneField(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="bgv",
    )

    previous_employment_verification = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    education_verification = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    address_verification = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    identity_verification = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    assigned_verification_agency = models.CharField(
        max_length=250,
        blank=True,
        null=True,
    )

    supporting_bgv_dossier = models.FileField(
        upload_to="candidate_documents/bgv/",
        blank=True,
        null=True,
    )

    remarks = models.TextField(
        blank=True,
        null=True,
    )

    verified_at = models.DateTimeField(
        blank=True,
        null=True,
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):
        return f"BGV - {self.employee}"


# ============================================================
# EMPLOYEE ACCOUNT / LOGIN
# ============================================================

class EmployeeAccount(models.Model):

    employee = models.OneToOneField(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="account"
    )

    role = models.ForeignKey(
        EmployeeRole,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        related_name="employee_accounts"
    )

    is_login_enabled = models.BooleanField(
        default=True
    )

    is_verified = models.BooleanField(
        default=False
    )

    last_login = models.DateTimeField(
        blank=True,
        null=True
    )

    failed_login_attempts = models.PositiveIntegerField(
        default=0
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    updated_at = models.DateTimeField(
        auto_now=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):

        return (
            f"{self.employee.email} - "
            f"{self.employee.name}"
        )


# ============================================================
# BANK ACCOUNT
# ============================================================

class BankAccount(models.Model):

    SAVINGS = "SAVINGS"
    CURRENT = "CURRENT"

    ACCOUNT_TYPE_CHOICES = [
        (SAVINGS, "Savings"),
        (CURRENT, "Current"),
    ]

    employee = models.ForeignKey(
        EmployeeDT,
        related_name="bank_accounts",
        on_delete=models.CASCADE
    )

    bank_name = models.CharField(
        max_length=100
    )

    account_number = models.CharField(
        max_length=50,
        db_index=True
    )

    ifsc_code = models.CharField(
        max_length=15
    )

    account_type = models.CharField(
        max_length=20,
        choices=ACCOUNT_TYPE_CHOICES,
        blank=True,
        null=True
    )

    # ========================================================
    # B2B / B2C BANKING & PAYROLL PROOF
    # ========================================================

    account_holder_name = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    branch_name = models.CharField(
        max_length=200,
        blank=True,
        null=True,
    )

    cancelled_cheque = models.FileField(
        upload_to="candidate_documents/bank_proof/",
        blank=True,
        null=True,
    )

    is_verified = models.BooleanField(
        default=False
    )

    active = models.BooleanField(
        default=True
    )

    upi_id = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        help_text="Payee UPI ID"
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    deactivated_at = models.DateTimeField(
        blank=True,
        null=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    class Meta:

        constraints = [
            models.UniqueConstraint(
                fields=[
                    "employee",
                    "account_number",
                    "ifsc_code"
                ],
                name="uniq_employee_account"
            )
        ]

        indexes = [
            models.Index(
                fields=["employee"]
            )
        ]

    def deactivate(self):

        self.active = False

        self.deactivated_at = timezone.now()

        self.save(
            update_fields=[
                "active",
                "deactivated_at"
            ]
        )

    def __str__(self):

        return (
            f"{self.bank_name} - "
            f"{self.account_number} - "
            f"{self.employee}"
        )


# ============================================================
# PAYROLL
# ============================================================

class Payroll(models.Model):

    Employee_ID = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    name = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        related_name="payrolls"
    )

    month = models.IntegerField()

    year = models.IntegerField()

    basic_salary = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    present_days = models.IntegerField(
        default=0
    )

    half_days = models.IntegerField(
        default=0
    )

    overtime_hours = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=Decimal("0.00")
    )

    full_day_salary = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    half_day_salary = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    overtime_pay = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    gross_salary = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    total_deductions = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    net_salary = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    PF_deduction = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00"),
        blank=True,
        null=True
    )

    TDS_deduction = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00"),
        blank=True,
        null=True
    )

    ESI_deduction = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00"),
        blank=True,
        null=True
    )

    insurance_deduction = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00"),
        blank=True,
    )

    total_working_hr = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=Decimal("0.00")
    )

    SHIFT_CHOICES = [
        ("Paid", "Paid"),
        ("Unpaid", "Unpaid"),
    ]

    status = models.CharField(
        max_length=90,
        choices=SHIFT_CHOICES,
        default="Unpaid",
        blank=True,
        null=True
    )

    class PaymentMethod(models.TextChoices):

        BANK_TRANSFER = "BANK", "Bank Transfer"
        UPI = "UPI", "UPI"
        CASH = "CASH", "Cash"
        CHEQUE = "CHEQUE", "Cheque"
        WALLET = "WALLET", "Wallet"

    payment_method = models.CharField(
        max_length=10,
        choices=PaymentMethod.choices,
        default=PaymentMethod.BANK_TRANSFER
    )

    upi_id = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        help_text="Payee UPI ID"
    )

    upi_txn_id = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        help_text="Gateway transaction/UTR"
    )

    payment_account_json = models.JSONField(
        blank=True,
        null=True,
        help_text="Method-specific payment meta"
    )

    payment_date = models.DateField(
        blank=True,
        null=True
    )

    amount_paid = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        blank=True,
        null=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    class Meta:

        unique_together = (
            "Employee_ID",
            "month",
            "year"
        )

# ============================================================
# MESSAGE
# ============================================================

class Message(models.Model):

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="messages"
    )

    sender_emp_id = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    reciver_emp_id = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="messages"
    )

    content = models.TextField()

    timestamp = models.DateTimeField(
        auto_now_add=True
    )

    msg_status = models.BooleanField(
        default=False,
        blank=True,
        null=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )


# ============================================================
# TARGET
# ============================================================

class Target(models.Model):

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="targets"
    )

    titel = models.CharField(
        max_length=100
    )

    description = models.TextField(
        blank=True,
        null=True
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="targets"
    )

    create_date = models.DateField()

    target_date = models.DateField()

    completed = models.BooleanField(
        default=False
    )

    completed_date = models.DateField(
        blank=True,
        null=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):

        return (
            f"{self.titel} "
            f"({self.description} - "
            f"{self.target_date})"
        )


# ============================================================
# EMPLOYEE CHECK IN / CHECK OUT
# ============================================================

class EMP_check_in_check_out(models.Model):

    Employee_ID = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        related_name="employee_checkins"
    )

    Name = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    image = models.ImageField(
        upload_to="photos/check_in/",
        blank=True,
        null=True
    )

    check_out_image = models.ImageField(
        upload_to="photos/check_out/",
        blank=True,
        null=True
    )

    login_date = models.DateField(
        verbose_name="login date",
        blank=True,
        null=True
    )

    login_time = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    logout_date = models.DateField(
        blank=True,
        null=True
    )

    logout_time = models.CharField(
        max_length=500,
        blank=True,
        null=True
    )

    total_working_hours = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    comment = models.TextField(
        blank=True,
        null=True
    )

    checkin_latitude = models.FloatField(
        blank=True,
        null=True
    )

    checkin_longitude = models.FloatField(
        blank=True,
        null=True
    )

    checkout_latitude = models.FloatField(
        blank=True,
        null=True
    )

    checkout_longitude = models.FloatField(
        blank=True,
        null=True
    )

    checkin_location_type = models.CharField(
        max_length=50,
        choices=[
            ("office", "Office"),
            ("outside", "Outside Office")
        ],
        blank=True,
        null=True
    )

    checkout_location_type = models.CharField(
        max_length=50,
        choices=[
            ("office", "Office"),
            ("outside", "Outside Office")
        ],
        blank=True,
        null=True
    )

    completed_targets = models.JSONField(
        default=list,
        blank=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):

        return (
            f"{self.Name} - "
            f"{self.login_date}"
        )


# ============================================================
# DAILY TASK
# ============================================================

class DailyTask(models.Model):

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="daily_tasks"
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="daily_tasks"
    )

    title = models.CharField(
        max_length=150
    )

    description = models.TextField(
        blank=True,
        null=True
    )

    task_date = models.DateField()

    completed = models.BooleanField(
        default=False
    )

    completed_time = models.TimeField(
        blank=True,
        null=True
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):

        return (
            f"{self.title} - "
            f"{self.employee.name} "
            f"({self.task_date})"
        )


# ============================================================
# ATTENDANCE
# ============================================================

class AttendanceEmp(models.Model):

    STATUS_CHOICES = [
        ("Present", "Present"),
        ("Absent", "Absent"),
        ("Half Day", "Half Day"),
        ("Holiday", "Holiday"),
        ("Paid Leave", "Paid Leave"),
        ("Sick Leave", "Sick Leave"),
        ("Casual Leave", "Casual Leave"),
    ]

    Employee_ID = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        related_name="attendance_records"
    )

    Name = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

    date = models.DateField(
        blank=True,
        null=True
    )

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        blank=True,
        null=True
    )

    total_working_hours = models.CharField(
        max_length=50,
        blank=True,
        null=True
    )

    image = models.ImageField(
        upload_to="photos/",
        blank=True,
        null=True
    )

    comment = models.TextField(
        max_length=200,
        blank=True,
        null=True
    )

    check_in_id = models.ForeignKey(
        EMP_check_in_check_out,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        related_name="attendance_records"
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):

        return (
            f"{self.Employee_ID} - "
            f"{self.date}"
        )

    class Meta:

        indexes = [
            models.Index(
                fields=[
                    "company",
                    "date"
                ]
            ),
            models.Index(
                fields=[
                    "company",
                    "Employee_ID"
                ]
            )
        ]


# ============================================================
# EMPLOYEE CODE UPDATE SIGNAL
# ============================================================

@receiver(
    pre_save,
    sender=EmployeeDT
)
def update_employee_id_in_related(
    sender,
    instance,
    **kwargs
):

    if not instance.pk:
        return

    try:

        old_instance = EmployeeDT.objects.get(
            pk=instance.pk
        )

    except EmployeeDT.DoesNotExist:

        return

    if (
        old_instance.employee_code !=
        instance.employee_code
    ):

        EMP_check_in_check_out.objects.filter(
            Employee_ID=old_instance.employee_code
        ).update(
            Employee_ID=instance.employee_code
        )

        AttendanceEmp.objects.filter(
            Employee_ID=old_instance.employee_code
        ).update(
            Employee_ID=instance.employee_code
        )

        Payroll.objects.filter(
            Employee_ID=old_instance.employee_code
        ).update(
            Employee_ID=instance.employee_code
        )

        LeaveRequest.objects.filter(
            Employee_ID=old_instance.employee_code
        ).update(
            Employee_ID=instance.employee_code
        )

# ============================================================
# LEAVE REQUEST (additive)
# ------------------------------------------------------------
# Leave used to exist only as an AttendanceEmp.status value.
# This model stores the actual request (who, when, why, status)
# so HR/Admin can see totals / pending and approve / reject.
#
# On APPROVAL the matching AttendanceEmp rows are written
# ("Paid Leave" / "Sick Leave" / "Casual Leave" / "Absent" for
# unpaid), so payroll_engine picks it up with no other change.
# ============================================================

class LeaveRequest(models.Model):

    LEAVE_TYPE_CHOICES = [
        ("Paid Leave", "Paid Leave"),
        ("Sick Leave", "Sick Leave"),
        ("Casual Leave", "Casual Leave"),
        ("Unpaid Leave", "Unpaid Leave"),
    ]

    STATUS_CHOICES = [
        ("Pending", "Pending"),
        ("Approved", "Approved"),
        ("Rejected", "Rejected"),
        ("Cancelled", "Cancelled"),
    ]

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="leave_requests"
    )

    Employee_ID = models.CharField(
        max_length=100,
        db_index=True
    )

    Name = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        help_text="Employee name snapshot at the time of the request"
    )

    leave_type = models.CharField(
        max_length=20,
        choices=LEAVE_TYPE_CHOICES,
        default="Casual Leave"
    )

    from_date = models.DateField()

    to_date = models.DateField()

    total_days = models.DecimalField(
        max_digits=5,
        decimal_places=1,
        default=Decimal("0"),
        help_text="Working days in the range (Sundays and company holidays excluded)"
    )

    reason = models.TextField(
        blank=True,
        null=True
    )

    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default="Pending",
        db_index=True
    )

    reviewed_by = models.CharField(
        max_length=150,
        blank=True,
        null=True
    )

    reviewed_at = models.DateTimeField(
        blank=True,
        null=True
    )

    review_comment = models.TextField(
        blank=True,
        null=True
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    updated_at = models.DateTimeField(
        auto_now=True
    )

    # ---- audit fields (same convention as the other models) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )

    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )

    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )

    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):
        return (
            f"{self.Employee_ID} - {self.leave_type} "
            f"{self.from_date} to {self.to_date} ({self.status})"
        )

    class Meta:
        ordering = ["-created_at", "-id"]
        indexes = [
            models.Index(fields=["company", "status"]),
            models.Index(fields=["company", "from_date"]),
        ]

# ============================================================
# ADDITIVE: Leave / WFH engine models (see leave_models.py)
# ============================================================
from .leave_models import *  # noqa: E402,F401,F403    



# ============================================================
# ADDITIVE: Performance Management & OKRs models (see performance_models.py)
# ============================================================
from .performance_models import *  # noqa: E402,F401,F403





class Candidate(models.Model):

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )

    STATUS_CHOICES = [
        ("APPLIED", "Applied"),
        ("SHORTLISTED", "Shortlisted"),
        ("INTERVIEW", "Interview"),
        ("SELECTED", "Selected"),
        ("OFFERED", "Offered"),
        ("REJECTED", "Rejected"),
        ("HIRED", "Hired"),
    ]

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="superadmin_candidates",
    )

    candidate_id = models.CharField(
        max_length=30,
        unique=True,
        blank=True,
        default="",
    )

    name = models.CharField(max_length=150)

    email = models.EmailField(max_length=254)

    phone = models.CharField(
        max_length=20,
        blank=True,
        default="",
    )

    applied_position = models.CharField(
        max_length=200,
        blank=True,
        default="",
    )

    candidate_source = models.CharField(
        max_length=100,
        blank=True,
        default="",
    )

    recruiter_name = models.CharField(
        max_length=150,
        blank=True,
        default="",
    )

    candidate_status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default="APPLIED",
        db_index=True,
    )

    resume = models.FileField(
        upload_to="candidate_resumes/",
        blank=True,
        null=True,
    )

    notes = models.TextField(
        blank=True,
        default="",
    )

    is_active = models.BooleanField(default=True)

    converted_to_employee = models.BooleanField(default=False)

    converted_employee = models.ForeignKey(
        "EmployeeDT",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="converted_candidate_records",
    )

    created_at = models.DateTimeField(auto_now_add=True)

    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.candidate_id:
            self.candidate_id = generate_candidate_id()

        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.candidate_id} - {self.name}"
        
        
