# ============================================================
# ADDITIVE: Project Timesheets & Overtime Coordination
#
# Nothing existing is modified or duplicated:
#   * employees       -> Employee.EmployeeDT          (FK)
#   * departments     -> Employee.Department          (optional FK on project)
#   * manager / HOD   -> Employee.ReportingHierarchy  (read only, approver resolution)
#   * hourly OT rate  -> Employee.EmployeeDT.Overtime_Rate (read only, default for claims)
#   * audit fields    -> People.models.Audit          (abstract, same convention)
# Every table carries `company` (B2B isolation) and soft-delete via is_active.
# Screens covered: Timesheets / Project Allocation / Overtime Claims / Timesheet Approval
# ============================================================
from decimal import Decimal

from django.db import models
from django.utils import timezone

from Company.models import company_details
from Employee.models import Department, EmployeeDT
from People.models import Audit


class TimesheetSetting(Audit):
    """One row per company - the rules the whole module follows."""
    company = models.OneToOneField(company_details, on_delete=models.CASCADE, related_name="timesheet_setting")
    standard_daily_hours = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("8"))
    max_daily_hours = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("24"))
    auto_overtime = models.BooleanField(default=True)            # hours above standard_daily_hours = OT
    overtime_multiplier = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal("1.00"))
    week_start_day = models.PositiveSmallIntegerField(default=0)  # 0 = Monday
    backdate_limit_days = models.PositiveIntegerField(default=31)  # employee can log this far back (0 = unlimited)
    enforce_allocation = models.BooleanField(default=True)       # employee may log only on projects they are allocated to


class TimesheetProject(Audit):
    STATUS = [("Planning", "Planning"), ("Active", "Active"), ("On Hold", "On Hold"),
              ("Completed", "Completed"), ("Cancelled", "Cancelled")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="timesheet_projects")
    code = models.CharField(max_length=30)                                  # PRJ-ZEN-01
    title = models.CharField(max_length=250)                                # Zenith Cloud Migration Platform
    client_department = models.CharField(max_length=200, blank=True, null=True)   # "Technology & Engineering"
    department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    description = models.TextField(blank=True, null=True)
    manager = models.ForeignKey(EmployeeDT, on_delete=models.SET_NULL, null=True, blank=True, related_name="managed_timesheet_projects")
    status = models.CharField(max_length=10, choices=STATUS, default="Active", db_index=True)
    budget_hours = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True)
    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    is_billable = models.BooleanField(default=True)

    class Meta:
        ordering = ["code"]
        unique_together = ((("company", "code")),)


class ProjectAllocation(Audit):
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="timesheet_allocations")
    project = models.ForeignKey(TimesheetProject, on_delete=models.CASCADE, related_name="allocations")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="timesheet_allocations")
    role = models.CharField(max_length=100, blank=True, null=True)          # "Backend Engineer"
    allocation_percent = models.PositiveSmallIntegerField(default=100)      # 100 = 1 FTE
    start_date = models.DateField(default=timezone.localdate)
    end_date = models.DateField(null=True, blank=True)
    is_billable = models.BooleanField(default=True)

    class Meta:
        ordering = ["project__code", "employee__name"]
        indexes = [models.Index(fields=["company", "employee"])]


class TimesheetEntry(Audit):
    STATUS = [("Draft", "Draft"), ("Submitted", "Submitted"), ("Approved", "Approved"), ("Rejected", "Rejected")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="timesheet_entries")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="timesheet_entries")
    project = models.ForeignKey(TimesheetProject, on_delete=models.PROTECT, related_name="entries")
    work_date = models.DateField(db_index=True)
    week_start = models.DateField(db_index=True)
    task_summary = models.CharField(max_length=500)
    hours = models.DecimalField(max_digits=4, decimal_places=2)             # total hours incl. overtime
    overtime_hours = models.DecimalField(max_digits=4, decimal_places=2, default=Decimal("0"))
    ot_manual = models.BooleanField(default=False)                          # True = overtime typed by a person, never auto-recalculated
    is_billable = models.BooleanField(default=True)
    status = models.CharField(max_length=10, choices=STATUS, default="Submitted", db_index=True)
    submitted_at = models.DateTimeField(null=True, blank=True)
    approver_code = models.CharField(max_length=100, blank=True, null=True, db_index=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 = ["-work_date", "-id"]
        indexes = [models.Index(fields=["company", "status"]), models.Index(fields=["company", "employee", "work_date"]),
                   models.Index(fields=["company", "approver_code", "status"])]


class OvertimeClaim(Audit):
    STATUS = [("Pending", "Pending Approval"), ("Approved", "Approved"), ("Rejected", "Rejected"),
              ("Passed to Payroll", "Passed to Payroll"), ("Cancelled", "Cancelled")]
    SOURCE = [("Auto", "Generated from approved timesheets"), ("Manual", "Entered by HR"), ("Employee", "Requested by employee")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="overtime_claims")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="overtime_claims")
    month = models.PositiveSmallIntegerField()
    year = models.PositiveSmallIntegerField()
    approved_hours = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal("0"))
    hourly_rate = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal("0"))
    multiplier = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal("1.00"))
    calculated_pay = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0"))
    approver_code = models.CharField(max_length=100, blank=True, null=True, db_index=True)   # approving manager
    status = models.CharField(max_length=17, choices=STATUS, default="Pending", db_index=True)
    source = models.CharField(max_length=8, choices=SOURCE, default="Auto")
    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)
    decision_remarks = models.TextField(blank=True, null=True)
    passed_to_payroll_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-year", "-month", "employee__name"]
        indexes = [models.Index(fields=["company", "year", "month"]), models.Index(fields=["company", "approver_code", "status"])]
