import os
import platform
import datetime
import nepali_datetime

from django import get_version as django_version
from django.shortcuts import render, redirect
from django.utils import timezone
from .models import Employee, Department, Shift, DailyAttendance, LeaveRequest, AttendanceLog

def get_nepali_date(ad_date):
    """Convert AD date to Nepali BS date string."""
    bs_date = nepali_datetime.date.from_datetime_date(ad_date)
    return bs_date.strftime("%B %d, %Y BS")

def home(request):
    """Render the landing screen with modern HRMS dashboard."""
    now = timezone.now()
    today = now.date()
    
    # Stats
    total_employees = Employee.objects.count()
    daily_stats = DailyAttendance.objects.filter(date=today)
    
    present_today = daily_stats.filter(status__in=['present', 'late', 'half_day']).count()
    late_today = daily_stats.filter(status='late').count()
    on_leave_today = daily_stats.filter(status='on_leave').count()
    
    # Recent Attendance Summary
    recent_attendance = DailyAttendance.objects.all().order_by('-date', '-check_in')[:5]
    
    # Pending Leaves
    pending_leaves = LeaveRequest.objects.filter(status='pending').order_by('-applied_on')[:5]
    
    nepali_date = get_nepali_date(today)

    context = {
        "project_name": "MediHR",
        "total_employees": total_employees,
        "present_today": present_today,
        "late_today": late_today,
        "on_leave_today": on_leave_today,
        "recent_attendance": recent_attendance,
        "pending_leaves": pending_leaves,
        "current_time": now,
        "nepali_date": nepali_date,
    }
    return render(request, "core/index.html", context)

def attendance_list(request):
    """View to list all daily attendance summaries."""
    attendances = DailyAttendance.objects.all().order_by('-date', '-check_in')
    return render(request, "core/attendance_list.html", {"attendances": attendances})

def leave_list(request):
    """View to list all leave requests."""
    leaves = LeaveRequest.objects.all().order_by('-applied_on')
    return render(request, "core/leave_list.html", {"leaves": leaves})

def employee_list(request):
    """View to list all employees."""
    employees = Employee.objects.all().order_by('employee_id')
    return render(request, "core/employee_list.html", {"employees": employees})
