import uuid
from decimal import Decimal
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from apps.localization.bs_calendar import ad_to_bs


class Designation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="designations")
    code = models.CharField(max_length=24)
    title = models.CharField(max_length=120)

    class Meta:
        db_table = "designations"
        unique_together = [("company", "code")]
        ordering = ["title"]

    def __str__(self) -> str:
        return self.title


class WorkShift(models.Model):
    class ShiftType(models.TextChoices):
        GENERAL = "GENERAL", "General Office"
        MORNING = "MORNING", "Morning"
        DAY = "DAY", "Day"
        EVENING = "EVENING", "Evening"
        NIGHT = "NIGHT", "Night"
        ROTATIONAL = "ROTATIONAL", "Rotational"
        SITE = "SITE", "Site Shift"
        LABOUR = "LABOUR", "Construction Labour Shift"
        CUSTOM = "CUSTOM", "Custom"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="shifts")
    name = models.CharField(max_length=80)
    shift_type = models.CharField(max_length=20, choices=ShiftType.choices, default=ShiftType.GENERAL)
    start_time = models.TimeField()
    end_time = models.TimeField()
    break_minutes = models.PositiveSmallIntegerField(default=60)
    grace_minutes = models.PositiveSmallIntegerField(default=15)
    is_cross_midnight = models.BooleanField(default=False)
    night_allowance_amount = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    weekly_off_days = models.JSONField(default=list, blank=True)  # e.g. ["SAT"]
    working_days_per_month = models.PositiveSmallIntegerField(default=26)
    standard_hours = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("8.00"))
    overtime_multiplier = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("1.50"))

    class Meta:
        db_table = "shifts"


class EmployeeDetail(models.Model):
    """HR workforce extension linked 1:1 to accounting.EmployeeProfile & Party subledger."""

    class EmploymentType(models.TextChoices):
        PERMANENT = "PERMANENT", "Permanent Staff"
        TEMPORARY = "TEMPORARY", "Temporary Staff"
        PROJECT_BASED = "PROJECT_BASED", "Project-Based Engineer/Staff"
        SKILLED_LABOR = "SKILLED_LABOR", "Skilled Construction Labor"
        UNSKILLED_LABOR = "UNSKILLED_LABOR", "Unskilled Labor"
        DAILY_WAGE = "DAILY_WAGE", "Daily Wage Worker"
        CONTRACT = "CONTRACT", "Contractual Employee"
        CONSULTANT = "CONSULTANT", "Consultant"

    class Status(models.TextChoices):
        ACTIVE = "ACTIVE", "Active"
        ON_LEAVE = "ON_LEAVE", "On Leave"
        SUSPENDED = "SUSPENDED", "Suspended"
        RESIGNED = "RESIGNED", "Resigned"
        TERMINATED = "TERMINATED", "Terminated"
        ARCHIVED = "ARCHIVED", "Archived"

    class EmploymentCategory(models.TextChoices):
        PERMANENT = "PERMANENT", "Permanent"
        FIXED_TERM = "FIXED_TERM", "Fixed-Term Contract"
        TEMPORARY = "TEMPORARY", "Temporary"
        PROBATION = "PROBATION", "Probation"
        PART_TIME = "PART_TIME", "Part-Time"
        DAILY_WAGE = "DAILY_WAGE", "Daily Wage"
        HOURLY = "HOURLY", "Hourly Worker"
        CASUAL = "CASUAL", "Casual Worker"
        TRAINEE = "TRAINEE", "Trainee / Apprentice"
        PROJECT_BASED = "PROJECT_BASED", "Project-Based Worker"
        OTHER = "OTHER", "Other"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="hr_employees")
    employee_profile = models.OneToOneField(
        "accounting.EmployeeProfile", on_delete=models.CASCADE, related_name="hr_detail"
    )
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="staff_employee",
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.SET_NULL, null=True, blank=True, related_name="staff_employees"
    )
    designation_obj = models.ForeignKey(Designation, on_delete=models.SET_NULL, null=True, blank=True)
    grade_code = models.CharField(max_length=32, blank=True)
    reporting_manager = models.ForeignKey(
        "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="direct_reports"
    )
    assigned_project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True, related_name="hr_assigned_staff")
    assigned_site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True, related_name="hr_assigned_staff")
    cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)
    employee_category = models.CharField(max_length=24, default="STAFF")
    employment_category = models.CharField(max_length=24, choices=EmploymentCategory.choices, default=EmploymentCategory.PERMANENT)
    shift = models.ForeignKey(WorkShift, on_delete=models.SET_NULL, null=True, blank=True)
    employment_type = models.CharField(max_length=20, choices=EmploymentType.choices, default=EmploymentType.PERMANENT)
    joining_date = models.DateField(null=True, blank=True)
    probation_end_date = models.DateField(null=True, blank=True)
    contract_end_date = models.DateField(null=True, blank=True)
    confirmation_date = models.DateField(null=True, blank=True)
    exit_date = models.DateField(null=True, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    gender = models.CharField(max_length=20, blank=True)
    nationality = models.CharField(max_length=64, default="Nepali", blank=True)
    marital_status = models.CharField(max_length=20, blank=True)
    personal_address = models.TextField(blank=True)
    province = models.CharField(max_length=80, blank=True)
    district = models.CharField(max_length=80, blank=True)
    local_level = models.CharField(max_length=120, blank=True)
    ward = models.CharField(max_length=16, blank=True)
    emergency_contact_name = models.CharField(max_length=120, blank=True)
    emergency_contact_phone = models.CharField(max_length=32, blank=True)
    citizenship_no = models.CharField(max_length=48, blank=True)
    passport_no = models.CharField(max_length=48, blank=True)
    work_permit_no = models.CharField(max_length=48, blank=True)
    bank_name = models.CharField(max_length=120, blank=True)
    bank_branch = models.CharField(max_length=120, blank=True)
    bank_account_no = models.CharField(max_length=48, blank=True)
    bank_account_holder = models.CharField(max_length=160, blank=True)
    payment_method = models.CharField(max_length=20, default="BANK_TRANSFER")  # BANK_TRANSFER|CASH|CHEQUE
    pan_no = models.CharField(max_length=20, blank=True)
    ssf_no = models.CharField(max_length=40, blank=True)
    epf_account_no = models.CharField(max_length=40, blank=True)
    insurance_policy_no = models.CharField(max_length=64, blank=True)
    retirement_scheme = models.CharField(max_length=24, default="PF")  # SSF|PF|APPROVED_FUND|NONE
    pf_enrolled = models.BooleanField(default=True)
    ssf_enrolled = models.BooleanField(default=False)
    is_married_tax = models.BooleanField(default=False)
    hourly_rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("250.00"))
    daily_rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE)
    version = models.PositiveIntegerField(default=1)

    class Meta:
        db_table = "employees"


class SalaryStructure(models.Model):
    class ProrationMethod(models.TextChoices):
        CALENDAR_DAYS = "CALENDAR_DAYS", "Calendar Days in Month"
        FIXED_30 = "FIXED_30", "Fixed 30-Day Basis"
        WORKING_DAYS = "WORKING_DAYS", "Scheduled Working Days"
        CONTRACT_HOURS = "CONTRACT_HOURS", "Contractual Hours"
        DAILY_RATE = "DAILY_RATE", "Daily Rate"
        HOURLY_RATE = "HOURLY_RATE", "Hourly Rate"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.CASCADE, related_name="salary_structures")
    effective_from = models.DateField()
    effective_to = models.DateField(null=True, blank=True)
    proration_method = models.CharField(max_length=24, choices=ProrationMethod.choices, default=ProrationMethod.CALENDAR_DAYS)
    basic_salary = models.DecimalField(max_digits=14, decimal_places=2)
    dearness_allowance = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    site_allowance = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    conveyance_allowance = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    house_rent_allowance = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    other_allowances_json = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    is_current = models.BooleanField(default=True)
    version = models.PositiveIntegerField(default=1)

    class Meta:
        db_table = "employee_salary_structures"
        ordering = ["-effective_from"]


class AttendanceRecord(models.Model):
    class Status(models.TextChoices):
        PRESENT = "PRESENT", "Present"
        ABSENT = "ABSENT", "Absent"
        HALF_DAY = "HALF_DAY", "Half Day"
        LEAVE = "LEAVE", "Approved Leave"
        HOLIDAY = "HOLIDAY", "Holiday"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="attendance_records")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT, related_name="attendance")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    shift = models.ForeignKey(WorkShift, on_delete=models.SET_NULL, null=True, blank=True)
    attendance_date = models.DateField(db_index=True)
    check_in = models.TimeField(null=True, blank=True)
    check_out = models.TimeField(null=True, blank=True)
    break_start = models.TimeField(null=True, blank=True)
    break_end = models.TimeField(null=True, blank=True)
    actual_working_hours = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))
    approved_working_hours = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))
    late_minutes = models.PositiveSmallIntegerField(default=0)
    early_departure_minutes = models.PositiveSmallIntegerField(default=0)
    overtime_hours = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.PRESENT)
    source = models.CharField(max_length=16, default="MANUAL")  # MANUAL | BIOMETRIC | MOBILE | OFFLINE | BULK
    original_snapshot = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "attendance_records"
        unique_together = [("company", "employee", "attendance_date")]
        ordering = ["-attendance_date"]


class LeaveRequest(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="leave_requests")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT)
    leave_type = models.CharField(max_length=32, default="ANNUAL")
    start_date = models.DateField()
    end_date = models.DateField()
    days = models.DecimalField(max_digits=5, decimal_places=1, default=Decimal("1.0"))
    is_paid = models.BooleanField(default=True)
    reason = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=24, default="PENDING")  # PENDING | SUPERVISOR_REC | MANAGER_APPROVED | APPROVED | REJECTED
    recommended_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    hr_confirmed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")

    class Meta:
        db_table = "leave_requests"


class Timesheet(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted"
        APPROVED = "APPROVED", "Supervisor Approved"
        POSTED_TO_PAYROLL = "POSTED_TO_PAYROLL", "Included in Payroll"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="timesheets")
    timesheet_no = models.CharField(max_length=40)
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT, related_name="timesheets")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    period_start = models.DateField()
    period_end = models.DateField()
    total_regular_hours = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal("0.00"))
    total_overtime_hours = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal("0.00"))
    total_labor_cost = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.DRAFT, db_index=True)
    submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "timesheets"
        unique_together = [("company", "timesheet_no")]
        ordering = ["-period_end"]


class TimesheetLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    timesheet = models.ForeignKey(Timesheet, on_delete=models.CASCADE, related_name="lines")
    work_date = models.DateField()
    work_activity = models.CharField(max_length=120)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    boq_item = models.ForeignKey("accounting.BoqItem", on_delete=models.PROTECT, null=True, blank=True)
    regular_hours = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("8.00"))
    overtime_hours = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))
    hourly_rate = models.DecimalField(max_digits=10, decimal_places=2)
    overtime_rate = models.DecimalField(max_digits=10, decimal_places=2)
    labor_cost = models.DecimalField(max_digits=14, decimal_places=2)

    class Meta:
        db_table = "timesheet_lines"


class PayrollStatutoryRuleSet(models.Model):
    """Versioned, effective-dated Nepal payroll statutory rates (no hardcoded brackets in engine)."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="payroll_rule_sets")
    rule_name = models.CharField(max_length=120)
    fiscal_year_label = models.CharField(max_length=24, blank=True)  # e.g. 2083/84
    effective_from = models.DateField()
    effective_to = models.DateField(null=True, blank=True)
    employee_pf_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    employer_pf_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    employee_ssf_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("11.00"))
    employer_ssf_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("20.00"))
    gratuity_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("8.33"))
    festival_eligible_months = models.PositiveSmallIntegerField(default=12)
    normal_daily_hours = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("8.00"))
    normal_weekly_hours = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("48.00"))
    ot_daily_cap_hours = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("4.00"))
    ot_weekly_cap_hours = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("24.00"))
    ot_multiplier = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("1.50"))
    hourly_divisor_hours = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("208.00"))  # 26d * 8h configurable
    tax_slabs_single = models.JSONField(default=list, encoder=DjangoJSONEncoder)  # [{"upto": 500000, "rate": 1}, ...]
    tax_slabs_couple = models.JSONField(default=list, encoder=DjangoJSONEncoder)
    tax_exemptions_json = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    legal_reference = models.CharField(max_length=180, blank=True)
    is_active = models.BooleanField(default=True)
    version = models.PositiveIntegerField(default=1)

    class Meta:
        db_table = "payroll_statutory_rules"
        ordering = ["-effective_from"]


class PayrollRun(models.Model):
    class PayrollType(models.TextChoices):
        MONTHLY = "MONTHLY", "Monthly Regular Payroll"
        DAILY_WAGE = "DAILY_WAGE", "Daily Wage Payroll"
        HOURLY = "HOURLY", "Hourly Payroll"
        PROJECT = "PROJECT", "Project Labour Payroll"
        OVERTIME = "OVERTIME", "Overtime Payroll"
        BONUS = "BONUS", "Bonus Payroll"
        FESTIVAL = "FESTIVAL", "Festival Expense Payroll"
        ARREARS = "ARREARS", "Arrears Payroll"
        OFF_CYCLE = "OFF_CYCLE", "Off-Cycle Payroll"
        FINAL_SETTLEMENT = "FINAL_SETTLEMENT", "Final Settlement Payroll"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        CALCULATED = "CALCULATED", "Calculated"
        VALIDATION_REQUIRED = "VALIDATION_REQUIRED", "Validation Required"
        SUBMITTED = "SUBMITTED", "Submitted for Approval"
        APPROVED = "APPROVED", "Finance Approved"
        POSTED = "POSTED", "Posted to General Ledger"
        PARTIALLY_PAID = "PARTIALLY_PAID", "Partially Paid"
        PAID = "PAID", "Paid via Bank"
        CLOSED = "CLOSED", "Closed"
        REVERSED = "REVERSED", "Reversed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="payroll_runs")
    run_no = models.CharField(max_length=40)
    payroll_type = models.CharField(max_length=24, choices=PayrollType.choices, default=PayrollType.MONTHLY)
    period_label = models.CharField(max_length=48)
    period_start = models.DateField()
    period_end = models.DateField()
    pay_date = models.DateField()
    bs_pay_date = models.CharField(max_length=16, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    statutory_rule_set = models.ForeignKey(PayrollStatutoryRuleSet, on_delete=models.PROTECT, null=True, blank=True)
    total_gross = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_deductions = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_net_pay = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    employer_contribution_total = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    validation_warnings_json = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    attendance_frozen_at = models.DateTimeField(null=True, blank=True)
    calculation_version = models.PositiveIntegerField(default=1)
    accrual_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    payment_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    project_wip_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.DRAFT, db_index=True)
    idempotency_key = models.CharField(max_length=96, null=True, blank=True)
    version = models.PositiveIntegerField(default=1)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "payroll_runs"
        unique_together = [("company", "run_no")]
        ordering = ["-pay_date"]

    def save(self, *args, **kwargs):
        if self.pay_date and not self.bs_pay_date:
            self.bs_pay_date = ad_to_bs(self.pay_date).isoformat()
        super().save(*args, **kwargs)


class PayrollLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    payroll_run = models.ForeignKey(PayrollRun, on_delete=models.CASCADE, related_name="lines")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    proration_basis = models.CharField(max_length=24, default="CALENDAR_DAYS")
    payable_days = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("30.00"))
    total_period_days = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("30.00"))
    basic_pay = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    allowances = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    overtime_pay = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    bonus_festival = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    reimbursements = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    gross_pay = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    pf_ssf_deduction = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    tds_tax = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    advance_recovery = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    loan_deduction = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    other_deductions = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    net_pay = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    employer_ssf = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    employer_pf = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    gratuity_accrual = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    employer_total_cost = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    ytd_taxable_income = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    ytd_tax_already_paid = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    line_breakdown_json = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    advance_record = models.ForeignKey("accounting.AdvanceRecord", on_delete=models.SET_NULL, null=True, blank=True)
    staff_loan = models.ForeignKey("accounting.StaffLoan", on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "payroll_lines"
        unique_together = [("payroll_run", "employee")]


class Payslip(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    payroll_line = models.OneToOneField(PayrollLine, on_delete=models.CASCADE, related_name="payslip")
    payslip_no = models.CharField(max_length=48)
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "payslips"
        unique_together = [("company", "payslip_no")]


class DepartmentAccessTemplate(models.Model):
    """Default RBAC role, module, dashboard & scope template linked 1:1 with a Department."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="department_templates")
    department = models.OneToOneField(
        "accounting.Department", on_delete=models.CASCADE, related_name="access_template"
    )
    default_role = models.ForeignKey("accounts_rbac.Role", on_delete=models.PROTECT)
    permitted_modules = models.JSONField(default=list, blank=True)
    action_overrides = models.JSONField(default=dict, blank=True)
    default_data_scope = models.CharField(max_length=16, default="COMPANY")
    allowed_branches = models.ManyToManyField("tenancy.Branch", blank=True)
    allowed_projects = models.ManyToManyField("projects.Project", blank=True)
    default_dashboard = models.CharField(max_length=40, default="DEFAULT")
    default_nav_items = models.JSONField(default=list, blank=True)
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "department_access_templates"


class StaffInvitation(models.Model):
    class ActivationStatus(models.TextChoices):
        PENDING = "PENDING", "Pending"
        SENT = "SENT", "Sent"
        ACCEPTED = "ACCEPTED", "Accepted"
        EXPIRED = "EXPIRED", "Expired"
        REVOKED = "REVOKED", "Revoked"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="invitations")
    employee_detail = models.ForeignKey(EmployeeDetail, on_delete=models.CASCADE, related_name="invitations")
    invitation_token_hash = models.CharField(max_length=64, unique=True)
    activation_status = models.CharField(
        max_length=16, choices=ActivationStatus.choices, default=ActivationStatus.PENDING
    )
    expires_at = models.DateTimeField()
    accepted_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "staff_invitations"
        ordering = ["-created_at"]


class StaffProfileChangeRequest(models.Model):
    class ApprovalStatus(models.TextChoices):
        PENDING = "PENDING", "Pending HR Review"
        APPROVED = "APPROVED", "Approved"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile_change_requests")
    employee_detail = models.ForeignKey(EmployeeDetail, on_delete=models.CASCADE, related_name="change_requests")
    field_name = models.CharField(max_length=64)
    old_value = models.TextField(blank=True)
    requested_value = models.TextField()
    reason = models.TextField(blank=True)
    approval_status = models.CharField(
        max_length=16, choices=ApprovalStatus.choices, default=ApprovalStatus.PENDING
    )
    reviewed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    reviewed_at = models.DateTimeField(null=True, blank=True)
    review_note = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "staff_profile_change_requests"
        ordering = ["-created_at"]



class EmployeeGrade(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="hr_grades")
    code = models.CharField(max_length=24)
    title = models.CharField(max_length=120)
    min_basic = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    max_basic = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))

    class Meta:
        db_table = "hr_employee_grades"
        unique_together = [("company", "code")]


class EmploymentContract(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="hr_contracts")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.CASCADE, related_name="contracts")
    contract_no = models.CharField(max_length=48)
    employment_category = models.CharField(max_length=24, default="PERMANENT")
    start_date = models.DateField()
    end_date = models.DateField(null=True, blank=True)
    probation_months = models.PositiveSmallIntegerField(default=6)
    notice_period_days = models.PositiveSmallIntegerField(default=30)
    working_hours_per_day = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("8.00"))
    overtime_eligible = models.BooleanField(default=True)
    terms_notes = models.TextField(blank=True)
    status = models.CharField(max_length=20, default="ACTIVE")  # DRAFT|ACTIVE|EXTENDED|EXPIRED|TERMINATED
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_employment_contracts"
        unique_together = [("company", "contract_no")]
        ordering = ["-start_date"]


class EmployeeDocument(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.CASCADE, related_name="hr_documents")
    doc_type = models.CharField(max_length=32)  # CONTRACT|CITIZENSHIP|PAN|SSF_CARD|PERMIT|INSURANCE|CERTIFICATE
    title = models.CharField(max_length=160)
    document_no = models.CharField(max_length=80, blank=True)
    expiry_date = models.DateField(null=True, blank=True)
    file_ref = models.CharField(max_length=255, blank=True)
    uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_employee_documents"


class EmployeeLifecycleChange(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="hr_lifecycle_changes")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.CASCADE, related_name="lifecycle_changes")
    change_type = models.CharField(max_length=32)  # PROMOTION|TRANSFER|INCREMENT|PROBATION_CONFIRM|RESIGNATION|TERMINATION
    effective_date = models.DateField()
    previous_value = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    new_value = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    reason = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=20, default="APPROVED")  # PENDING|APPROVED|REJECTED
    prepared_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_lifecycle_changes"
        ordering = ["-effective_date", "-created_at"]


class SalaryComponent(models.Model):
    class ComponentType(models.TextChoices):
        EARNING = "EARNING", "Earning"
        REIMBURSEMENT = "REIMBURSEMENT", "Reimbursement (Non-Remuneration)"
        DEDUCTION = "DEDUCTION", "Employee Deduction"
        EMPLOYER_CONTRIBUTION = "EMPLOYER_CONTRIBUTION", "Employer Contribution"

    class CalcMethod(models.TextChoices):
        FIXED = "FIXED", "Fixed Amount"
        PCT_BASIC = "PCT_BASIC", "% of Basic Salary"
        PCT_GROSS = "PCT_GROSS", "% of Gross Salary"
        PER_DAY = "PER_DAY", "Per Working Day"
        PER_HOUR = "PER_HOUR", "Per Working Hour"
        PER_OT_HOUR = "PER_OT_HOUR", "Per Overtime Hour"
        PER_TRIP = "PER_TRIP", "Per Completed Trip"
        PER_UNIT = "PER_UNIT", "Per Production Unit"
        FORMULA = "FORMULA", "Restricted Safe Formula"
        MANUAL = "MANUAL", "Manual Approved Amount"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="salary_components")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=120)
    component_type = models.CharField(max_length=24, choices=ComponentType.choices)
    calc_method = models.CharField(max_length=20, choices=CalcMethod.choices, default=CalcMethod.FIXED)
    default_amount_or_pct = models.DecimalField(max_digits=14, decimal_places=4, default=Decimal("0.0000"))
    formula_expression = models.CharField(max_length=255, blank=True)
    is_taxable = models.BooleanField(default=True)
    is_statutory = models.BooleanField(default=False)
    max_deduction_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("100.00"))
    gl_account = models.ForeignKey("accounting.Account", on_delete=models.SET_NULL, null=True, blank=True)
    effective_from = models.DateField(null=True, blank=True)
    version = models.PositiveIntegerField(default=1)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = "hr_salary_components"
        unique_together = [("company", "code")]
        ordering = ["component_type", "code"]


class SalaryRevision(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="salary_revisions")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.CASCADE, related_name="salary_revisions")
    effective_from = models.DateField()
    previous_basic = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    new_basic = models.DecimalField(max_digits=14, decimal_places=2)
    revision_type = models.CharField(max_length=24, default="ANNUAL_INCREMENT")  # ANNUAL_INCREMENT|MERIT|PROMOTION|GRADE|ADJUSTMENT
    new_structure = models.ForeignKey(SalaryStructure, on_delete=models.SET_NULL, null=True, blank=True)
    status = models.CharField(max_length=16, default="APPROVED")  # PENDING|APPROVED|REJECTED
    reason = models.CharField(max_length=255, blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_salary_revisions"
        ordering = ["-effective_from"]


class HolidayCalendar(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="holidays")
    holiday_date = models.DateField()
    name = models.CharField(max_length=120)
    is_paid = models.BooleanField(default=True)

    class Meta:
        db_table = "hr_holidays"
        unique_together = [("company", "holiday_date")]
        ordering = ["holiday_date"]


class AttendanceCorrection(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="attendance_corrections")
    attendance = models.ForeignKey(AttendanceRecord, on_delete=models.CASCADE, related_name="corrections")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.CASCADE)
    requested_check_in = models.TimeField(null=True, blank=True)
    requested_check_out = models.TimeField(null=True, blank=True)
    requested_status = models.CharField(max_length=24, blank=True)
    reason = models.CharField(max_length=255)
    status = models.CharField(max_length=20, default="PENDING")  # PENDING|VERIFIED|APPROVED|REJECTED
    verified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_attendance_corrections"
        ordering = ["-created_at"]


class BiometricImportBatch(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    source_name = models.CharField(max_length=120)
    total_rows = models.PositiveIntegerField(default=0)
    imported_rows = models.PositiveIntegerField(default=0)
    duplicate_rows = models.PositiveIntegerField(default=0)
    imported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_biometric_imports"
        ordering = ["-created_at"]


class OvertimeRecord(models.Model):
    class Category(models.TextChoices):
        WORKDAY = "WORKDAY", "Normal Workday OT"
        WEEKLY_REST = "WEEKLY_REST", "Weekly Rest Day Work"
        PUBLIC_HOLIDAY = "PUBLIC_HOLIDAY", "Public Holiday Work"
        NIGHT = "NIGHT", "Night Overtime"
        EMERGENCY = "EMERGENCY", "Emergency Project OT"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="overtime_records")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT, related_name="overtime_records")
    attendance = models.ForeignKey(AttendanceRecord, on_delete=models.SET_NULL, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    ot_date = models.DateField(db_index=True)
    ot_category = models.CharField(max_length=20, choices=Category.choices, default=Category.WORKDAY)
    actual_ot_hours = models.DecimalField(max_digits=5, decimal_places=2)
    approved_ot_hours = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    basic_hourly_rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    multiplier = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("1.50"))
    calculated_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    exceeds_statutory_cap = models.BooleanField(default=False)
    status = models.CharField(max_length=24, default="PENDING")  # PENDING|SUPERVISOR_APPROVED|HR_APPROVED|REJECTED
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_overtime_records"
        unique_together = [("company", "employee", "ot_date", "ot_category")]
        ordering = ["-ot_date"]


class LeavePolicy(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="leave_policies")
    leave_type_code = models.CharField(max_length=24)  # ANNUAL|SICK|MATERNITY|PATERNITY|MOURNING|SUBSTITUTE|UNPAID|SPECIAL
    name = models.CharField(max_length=80)
    annual_entitlement_days = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("18.00"))
    accrual_frequency = models.CharField(max_length=16, default="MONTHLY")  # MONTHLY|ANNUAL|DAILY
    max_carry_forward = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("30.00"))
    is_encashable = models.BooleanField(default=False)
    is_paid = models.BooleanField(default=True)
    prorate_on_join = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = "hr_leave_policies"
        unique_together = [("company", "leave_type_code")]


class LeaveBalance(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="leave_balances")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.CASCADE, related_name="leave_balances")
    leave_type_code = models.CharField(max_length=24)
    fiscal_year_label = models.CharField(max_length=24, default="2083/84")
    opening_balance = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))
    accrued_days = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))
    taken_days = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))
    encashed_days = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))
    adjusted_days = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0.00"))

    class Meta:
        db_table = "hr_leave_balances"
        unique_together = [("company", "employee", "leave_type_code", "fiscal_year_label")]


class DailyWageEntry(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="daily_wages")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT)
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.SET_NULL, null=True, blank=True)
    work_date = models.DateField(db_index=True)
    work_category = models.CharField(max_length=80)
    workdays = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("1.00"))
    daily_rate = models.DecimalField(max_digits=12, decimal_places=2)
    overtime_amount = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    allowance_amount = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    net_payable = models.DecimalField(max_digits=14, decimal_places=2)
    status = models.CharField(max_length=20, default="SUBMITTED")  # SUBMITTED|APPROVED|POSTED
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "hr_daily_wages"
        ordering = ["-work_date"]


class PieceRateWorkRecord(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="piece_rate_records")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.SET_NULL, null=True, blank=True)
    work_date = models.DateField()
    work_description = models.CharField(max_length=160)
    unit = models.CharField(max_length=24, default="SQM")
    quantity = models.DecimalField(max_digits=12, decimal_places=3)
    unit_rate = models.DecimalField(max_digits=12, decimal_places=2)
    total_amount = models.DecimalField(max_digits=14, decimal_places=2)
    quality_approved = models.BooleanField(default=False)
    status = models.CharField(max_length=20, default="SUBMITTED")  # SUBMITTED|APPROVED|POSTED
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "hr_piece_rate_records"
        ordering = ["-work_date"]


class PayrollPaymentBatch(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="payroll_payment_batches")
    payroll_run = models.ForeignKey(PayrollRun, on_delete=models.PROTECT, related_name="payment_batches")
    batch_no = models.CharField(max_length=48)
    payment_method = models.CharField(max_length=20, default="BANK_TRANSFER")
    bank_account = models.ForeignKey("banking.BankAccount", on_delete=models.PROTECT, null=True, blank=True)
    total_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=20, default="EXPORTED")  # EXPORTED|CONFIRMED|FAILED
    confirmed_at = models.DateTimeField(null=True, blank=True)
    confirmed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_payroll_payment_batches"
        unique_together = [("company", "batch_no")]


class PayrollCostAllocation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    payroll_run = models.ForeignKey(PayrollRun, on_delete=models.CASCADE, related_name="cost_allocations")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    cost_center = models.ForeignKey("accounting.CostCenter", on_delete=models.SET_NULL, null=True, blank=True)
    allocation_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("100.00"))
    allocated_amount = models.DecimalField(max_digits=16, decimal_places=2)
    is_wip = models.BooleanField(default=True)

    class Meta:
        db_table = "hr_payroll_cost_allocations"


class FestivalExpenseRecord(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="festival_expenses")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT)
    festival_name = models.CharField(max_length=80, default="Dashain Festival Allowance")
    fiscal_year_label = models.CharField(max_length=24, default="2083/84")
    service_months = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("12.00"))
    entitled_amount = models.DecimalField(max_digits=14, decimal_places=2)
    status = models.CharField(max_length=20, default="APPROVED")  # DRAFT|APPROVED|PAID
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_festival_expenses"


class EmployeeReimbursement(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="hr_reimbursements")
    employee = models.ForeignKey("accounting.EmployeeProfile", on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    expense_type = models.CharField(max_length=32, default="TRAVEL")  # TRAVEL|HOTEL|FOOD|FUEL|MEDICAL|SITE|MISC
    claim_date = models.DateField()
    claim_amount = models.DecimalField(max_digits=14, decimal_places=2)
    approved_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    is_taxable = models.BooleanField(default=False)
    description = models.CharField(max_length=255)
    status = models.CharField(max_length=20, default="SUBMITTED")  # SUBMITTED|VERIFIED|APPROVED|PAID|REJECTED
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_reimbursements"
        ordering = ["-claim_date"]


class FinalSettlement(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="final_settlements")
    employee = models.OneToOneField("accounting.EmployeeProfile", on_delete=models.PROTECT, related_name="final_settlement")
    exit_type = models.CharField(max_length=24, default="RESIGNATION")  # RESIGNATION|TERMINATION|RETIREMENT
    last_working_date = models.DateField()
    unpaid_salary = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    pending_overtime = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    leave_encashment = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    gratuity_settlement = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    festival_prorata = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    advance_recovery = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    loan_recovery = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    tax_adjustment = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    net_payable = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    clearance_json = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    status = models.CharField(max_length=20, default="CALCULATED")  # CALCULATED|APPROVED|POSTED|PAID
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "hr_final_settlements"


class HrConfiguration(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField("tenancy.Company", on_delete=models.CASCADE, related_name="hr_config")
    payroll_day_of_month = models.PositiveSmallIntegerField(default=28)
    default_proration_method = models.CharField(max_length=24, default="CALENDAR_DAYS")
    salary_rounding_mode = models.CharField(max_length=16, default="NEAREST_1")
    allow_negative_net_pay = models.BooleanField(default=False)
    require_ot_pre_approval = models.BooleanField(default=True)
    capitalize_direct_labour_to_wip = models.BooleanField(default=True)
    payslip_template_default = models.CharField(max_length=24, default="STANDARD")
    gl_mappings = models.JSONField(default=dict, blank=True)
    audit_log_json = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "hr_configurations"
