# ============================================================
# ADDITIVE: Payroll Inputs & Compensation Coordination
#   Payroll Dashboard | Salary Structure | Payroll Inputs | Variable Pay | Deductions | Loans / Advances |
#   Processing Status | Payslip Management | Statutory Components
#
# DUPLICATE CHECK (every existing models.py was reviewed first) - nothing existing is modified:
#   Employee.Payroll              REUSED (read + existing generator): the monthly salary row produced by
#                                 Company.payroll_engine (/api/payroll/generate/). It stays the base of every payslip.
#   Employee.EmployeeDT / CandidateCompensation / BankAccount   REUSED (read only): CTC, salary, bank details.
#   Timesheet.OvertimeClaim       REUSED (read only): the "Overtime Payout" lines are the claims already handed to payroll.
#   People.ExitFnF                REUSED (FK link): "Notice Period Shortfall - Pending F&F" deductions point at the F&F statement.
#   Performance.PerfAppraisal     REUSED (optional FK): variable pay can reference the appraisal it came from.
#   People.Compliance* (+ Form16) REUSED: the "Statutory Components" tab is /api/compliance/dashboard/ - not rebuilt.
#   Insurance premium / PF / ESI / TDS are already computed by the payroll engine - not recomputed.
#   Payslip PDF (existing /api/payroll/<emp>/<m>/<y>/slip/) stays; the hub adds the adjusted payslip.
#
# What did NOT exist and is added here:
#   PayrollSetting            company rules (no hard-coded policy)
#   SalaryComponent           the "Corporate Salary Component Architecture" (Basic / HRA / Special / EPF / PT / TDS ...)
#   PayrollCycle              Inputs Freeze -> Verification Run -> Bank Transfer File -> Release Payslips
#   PayrollInput              monthly variances & inputs (bonus, incentive, reimbursement, arrears, LOP verification ...)
#   VariablePay               performance bonus register (target x achievement)
#   PayrollDeduction          non-statutory deductions
#   Loan / LoanRepayment      loans & salary advances with EMI schedule
#   Payslip                   immutable snapshot created when payslips are released
# Nothing is pre-seeded. Every table carries `company` (B2B isolation) and soft delete via is_active.
# ============================================================
from decimal import Decimal

from django.db import models

from Company.models import company_details
from Employee.models import EmployeeDT
from People.models import Audit

Z = Decimal("0.00")


class PayrollSetting(Audit):
    """One row per company (created on first read)."""
    company = models.OneToOneField(company_details, on_delete=models.CASCADE, related_name="payroll_hub_setting")
    include_timesheet_overtime = models.BooleanField(default=True)   # add OvertimeClaim 'Passed to Payroll' to payslips
    allow_employee_claims = models.BooleanField(default=True)        # employees may raise reimbursement claims
    allow_employee_loan_requests = models.BooleanField(default=True)
    loan_max_emi_percent = models.PositiveSmallIntegerField(default=50)      # EMI cap as % of monthly gross
    loan_max_tenure_months = models.PositiveSmallIntegerField(default=60)
    loan_max_principal = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0"))  # 0 = no cap
    payslip_release_day = models.PositiveSmallIntegerField(default=0)        # day of the wage month; 0 = month end
    bank_portal_name = models.CharField(max_length=60, blank=True, null=True)  # label only, e.g. "HDFC Portal"
    require_verification_before_bank_file = models.BooleanField(default=True)


class SalaryComponent(Audit):
    TYPES = [("EARNING", "Earning"), ("DEDUCTION", "Deduction")]
    METHODS = [("PERCENT_OF_GROSS", "% of monthly gross"), ("PERCENT_OF_BASIC", "% of basic"),
               ("PERCENT_OF_COMPONENT", "% of another component"), ("FIXED_AMOUNT", "Fixed amount per month"),
               ("BALANCING", "Balancing figure (gross minus other earnings)")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="salary_components")
    code = models.CharField(max_length=20)                       # BASIC, HRA, SPECIAL, EPF, PT, TDS ...
    name = models.CharField(max_length=100)                      # "House Rent Allowance (HRA)"
    component_type = models.CharField(max_length=9, choices=TYPES, default="EARNING", db_index=True)
    calc_method = models.CharField(max_length=20, choices=METHODS, default="FIXED_AMOUNT")
    calc_value = models.DecimalField(max_digits=12, decimal_places=2, default=Z)    # percent or amount
    base_component = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True,
                                       related_name="dependents")
    cap_amount = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)   # EPF capped at 1800
    is_taxable = models.BooleanField(default=True)
    tax_treatment = models.CharField(max_length=200, blank=True, null=True)   # "Exemption under Sec 10(13A)"
    description = models.CharField(max_length=250, blank=True, null=True)
    sort_order = models.PositiveIntegerField(default=1)

    class Meta:
        ordering = ["sort_order", "id"]
        unique_together = (("company", "code"),)


class PayrollCycle(Audit):
    STATUS = [("OPEN", "Open"), ("INPUTS_FROZEN", "Inputs Frozen"), ("VERIFIED", "Verified"),
              ("BANK_FILE_READY", "Bank File Ready"), ("RELEASED", "Payslips Released")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="payroll_cycles")
    month = models.PositiveSmallIntegerField()
    year = models.PositiveSmallIntegerField()
    status = models.CharField(max_length=16, choices=STATUS, default="OPEN", db_index=True)
    inputs_frozen_at = models.DateTimeField(null=True, blank=True)
    inputs_frozen_by = models.CharField(max_length=150, blank=True, null=True)
    verified_at = models.DateTimeField(null=True, blank=True)
    verified_by = models.CharField(max_length=150, blank=True, null=True)
    verification_result = models.JSONField(default=dict, blank=True)
    bank_file_at = models.DateTimeField(null=True, blank=True)
    bank_file_by = models.CharField(max_length=150, blank=True, null=True)
    bank_file = models.FileField(upload_to="payroll_hub/bank_files/", null=True, blank=True)
    bank_file_total = models.DecimalField(max_digits=14, decimal_places=2, default=Z)
    bank_file_count = models.PositiveIntegerField(default=0)
    release_on = models.DateField(null=True, blank=True)         # scheduled release date
    released_at = models.DateTimeField(null=True, blank=True)
    released_by = models.CharField(max_length=150, blank=True, null=True)
    remarks = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["-year", "-month"]
        unique_together = (("company", "month", "year"),)


class PayrollInput(Audit):
    TYPES = [("BONUS", "Bonus"), ("INCENTIVE", "Incentive"), ("REIMBURSEMENT", "Reimbursement"),
             ("ARREAR", "Arrears"), ("OTHER_EARNING", "Other earning"), ("OTHER_DEDUCTION", "Other deduction"),
             ("LOP", "Loss of Pay (LOP) verification")]
    EARNING_TYPES = {"BONUS", "INCENTIVE", "REIMBURSEMENT", "ARREAR", "OTHER_EARNING"}
    STATUS = [("PENDING_REVIEW", "Pending Review"), ("APPROVED", "Approved"), ("VERIFIED", "Verified"),
              ("REJECTED", "Rejected"), ("PROCESSED", "Processed")]
    SOURCE = [("MANUAL", "Entered by HR"), ("EMPLOYEE", "Claimed by employee")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="payroll_inputs")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="payroll_inputs")
    month = models.PositiveSmallIntegerField()
    year = models.PositiveSmallIntegerField()
    input_type = models.CharField(max_length=16, choices=TYPES, db_index=True)
    label = models.CharField(max_length=100, blank=True, null=True)       # "Referral Incentive Bonus"
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    days = models.DecimalField(max_digits=5, decimal_places=2, default=Z)   # LOP days
    remarks = models.TextField(blank=True, null=True)
    status = models.CharField(max_length=14, choices=STATUS, default="PENDING_REVIEW", db_index=True)
    source = models.CharField(max_length=8, choices=SOURCE, default="MANUAL")
    attachment = models.FileField(upload_to="payroll_hub/inputs/", null=True, blank=True)
    decided_by = models.CharField(max_length=150, blank=True, null=True)
    decided_at = models.DateTimeField(null=True, blank=True)
    decision_remarks = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["-year", "-month", "-id"]
        indexes = [models.Index(fields=["company", "year", "month"])]


class VariablePay(Audit):
    PERIODS = [("MONTHLY", "Monthly"), ("QUARTERLY", "Quarterly"), ("HALF_YEARLY", "Half-yearly"),
               ("ANNUAL", "Annual")]
    STATUS = [("DRAFT", "Draft"), ("PENDING_APPROVAL", "Pending Approval"), ("APPROVED", "Approved"),
              ("PAID", "Paid"), ("REJECTED", "Rejected")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="variable_pay")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="variable_pay")
    period_type = models.CharField(max_length=12, choices=PERIODS, default="QUARTERLY")
    period_label = models.CharField(max_length=40)                 # "Q2 2026"
    target_amount = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    achievement_percent = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("100.00"))
    payable_amount = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    status = models.CharField(max_length=16, choices=STATUS, default="DRAFT", db_index=True)
    payout_month = models.PositiveSmallIntegerField(null=True, blank=True)   # cycle in which it is paid
    payout_year = models.PositiveSmallIntegerField(null=True, blank=True)
    appraisal_id = models.PositiveIntegerField(null=True, blank=True)        # Employee.PerfAppraisal id (soft link)
    remarks = models.TextField(blank=True, null=True)
    decided_by = models.CharField(max_length=150, blank=True, null=True)
    decided_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-id"]
        unique_together = (("company", "employee", "period_label"),)


class PayrollDeduction(Audit):
    STATUS = [("PENDING_APPROVAL", "Pending Approval"), ("APPROVED", "Approved"), ("PENDING_FNF", "Pending F&F"),
              ("RECOVERED", "Recovered"), ("WAIVED", "Waived")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="payroll_deductions")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="payroll_deductions")
    head = models.CharField(max_length=100)                       # "Notice Period Shortfall"
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    reason = models.CharField(max_length=300, blank=True, null=True)
    month = models.PositiveSmallIntegerField(null=True, blank=True)    # recovery cycle (null while pending F&F)
    year = models.PositiveSmallIntegerField(null=True, blank=True)
    status = models.CharField(max_length=16, choices=STATUS, default="PENDING_APPROVAL", db_index=True)
    exit_fnf_id = models.PositiveIntegerField(null=True, blank=True)    # People.ExitFnF id (soft link)
    decided_by = models.CharField(max_length=150, blank=True, null=True)
    decided_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-id"]


class Loan(Audit):
    TYPES = [("LOAN", "Employee Loan"), ("SALARY_ADVANCE", "Salary Advance")]
    STATUS = [("PENDING", "Pending Approval"), ("ACTIVE", "Active"), ("CLOSED", "Closed"),
              ("FORECLOSED", "Foreclosed"), ("REJECTED", "Rejected"), ("CANCELLED", "Cancelled")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="payroll_loans")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="payroll_loans")
    loan_no = models.CharField(max_length=30)                      # LN-2026-04
    loan_type = models.CharField(max_length=14, choices=TYPES, default="LOAN")
    principal = models.DecimalField(max_digits=12, decimal_places=2)
    interest_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Z)   # % p.a. reducing balance
    tenure_months = models.PositiveSmallIntegerField()
    emi_amount = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    start_month = models.PositiveSmallIntegerField(null=True, blank=True)       # first EMI cycle
    start_year = models.PositiveSmallIntegerField(null=True, blank=True)
    purpose = models.CharField(max_length=300, blank=True, null=True)
    status = models.CharField(max_length=10, choices=STATUS, default="PENDING", db_index=True)
    sanctioned_on = models.DateField(null=True, blank=True)
    decided_by = models.CharField(max_length=150, blank=True, null=True)
    decision_remarks = models.CharField(max_length=300, blank=True, null=True)
    requested_by_employee = models.BooleanField(default=False)

    class Meta:
        ordering = ["-id"]
        unique_together = (("company", "loan_no"),)


class LoanRepayment(Audit):
    STATUS = [("SCHEDULED", "Scheduled"), ("DEDUCTED", "Deducted"), ("SKIPPED", "Skipped"), ("WAIVED", "Waived")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="payroll_loan_repayments")
    loan = models.ForeignKey(Loan, on_delete=models.CASCADE, related_name="repayments")
    installment_no = models.PositiveSmallIntegerField()
    month = models.PositiveSmallIntegerField()
    year = models.PositiveSmallIntegerField()
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    principal_part = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    interest_part = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    status = models.CharField(max_length=10, choices=STATUS, default="SCHEDULED", db_index=True)
    deducted_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["loan_id", "installment_no"]
        unique_together = (("loan", "installment_no"),)


class Payslip(Audit):
    STATUS = [("RELEASED", "Released"), ("REVOKED", "Revoked")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="hub_payslips")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="hub_payslips")
    cycle = models.ForeignKey(PayrollCycle, on_delete=models.CASCADE, related_name="payslips")
    payslip_no = models.CharField(max_length=40)                   # PSL-2026-09-EMP0248
    month = models.PositiveSmallIntegerField()
    year = models.PositiveSmallIntegerField()
    gross_salary = models.DecimalField(max_digits=14, decimal_places=2, default=Z)
    total_deductions = models.DecimalField(max_digits=14, decimal_places=2, default=Z)
    net_payable = models.DecimalField(max_digits=14, decimal_places=2, default=Z)
    breakup = models.JSONField(default=dict, blank=True)          # frozen earnings / deductions lines
    status = models.CharField(max_length=9, choices=STATUS, default="RELEASED", db_index=True)
    released_at = models.DateTimeField(null=True, blank=True)
    released_by = models.CharField(max_length=150, blank=True, null=True)

    class Meta:
        ordering = ["-year", "-month", "employee_id"]
        unique_together = (("company", "employee", "month", "year"), ("company", "payslip_no"))
