from django.shortcuts import render
import json
from django.conf import settings
from django.shortcuts import render
from common.models import *
from employee.models import *
from store.models import *
from employee.forms import *
from masters.forms import *
from privilege.models import *
import hashlib
import os
from django.conf import settings
from datetime import datetime
from django.utils import timezone
from django.db.models import Max, F, Q
import base64
from django.shortcuts import render
from io import BytesIO
from django.conf import settings
from django.template.loader import get_template
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.templatetags.static import static
from xhtml2pdf import pisa
from num2words import num2words
from django.contrib.staticfiles import finders
from common.utils import *
from django.db.models.functions import Cast



# Create your views here.

#```````````````````````````````````````````````````````````**EMPLOYEE**````````````````````````````````````````````````````````````````````````````````

def employee(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        if user_type == 'admin':
            cmpy = selectList(company_table, {'id':1})
            role = selectList(role_table, {'role_type': 'admin'},order_by='name')
            branch = selectList(branch_table, {'status': 1}, order_by='name')

            return render(request, 'employee/details.html', {'company': cmpy,'role':role, 'branch': branch})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
    




def employee_addpage(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        if user_type == 'admin':
            cmpy = selectList(company_table, {'id':1})
            role = selectList(role_table, {'role_type': 'admin'},order_by='name')
            branch = selectList(branch_table, {'status': 1}, order_by='name')

            return render(request, 'employee/add.html', {'company': cmpy,'role':role, 'branch': branch})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")



def employee_editpage(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        if user_type == 'admin':
            cmpy = selectList(company_table, {'id':1})
            role = selectList(role_table, {'role_type': 'admin'},order_by='name')
            branch = selectList(branch_table, {'status': 1}, order_by='name')
            encoded_id = request.GET.get('id')
            decoded_id = decode_base64_id(encoded_id)

            if not decoded_id:
                return HttpResponse("ID parameter is missing")
            
            employee = select_row(employee_table, {'id': decoded_id})

            return render(request, 'employee/edit.html', {'company': cmpy,'role':role, 'branch': branch, 'employee': employee})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/") 

def employee_add(request):
    if request.method == 'POST':
        try:
            user_id = request.session.get('user_id')           
            company_id = request.session.get('company_id')    
            date_time = datetime.now()       
            form = EmployeeForm(request.POST, request.FILES)

            role_id = request.session.get('role_id')
            has_access, error_message = check_user_access(role_id, 'master_employee', "create")

            if not has_access:
                return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to add employee details'})
            
            if form.is_valid():
                category = form.save(commit=False)
                company_id = request.POST.get('company_id') or 0
                user_role = request.POST.get('user_role') or 0
                name = request.POST.get('name')
                user_name = request.POST.get('user_name')
                email = request.POST.get('email')
                pwd = request.POST.get('pwd')
                address1 = request.POST.get('address1')
                address2 = request.POST.get('address2')
                mobile = request.POST.get('mobile')
                city = request.POST.get('city')
                state = request.POST.get('state')
                pincode = request.POST.get('pincode')
                photo = request.FILES.get('photo')
                is_wholesale = request.POST.get('is_wholesale') or 0
                store_type = request.POST.get('store_type') or 'store'

                employee_code= generate_company_code(company_id)

                if employee_table.objects.filter(email=email,status=1).exists():
                    return JsonResponse({
                        'message': 'email_exists',
                        'field': 'email',
                        'error': 'This email is already in use.'
                    })

                category.employee_code = employee_code
                category.num_series =  generate_num_series(employee_table)
                category.company_id = company_id
                category.is_wholesale = is_wholesale
                category.store_type = store_type
                category.role_id = user_role
                category.branch_id = request.POST.get('branch_id') or 0
                category.name = name
                category.nick_name = user_name
                category.email = email
                category.password = hashlib.md5(pwd.encode()).hexdigest()
                category.address_line1 = address1
                category.address_line2 = address2
                category.mobile = mobile
                category.city = city
                category.state = state
                category.pincode = int(pincode) if pincode else None
                category.photo = photo

                # Basic Details
                category.gender = request.POST.get('gender')
                category.parent_name = request.POST.get('parent_name')
                category.spouse_name = request.POST.get('spouse_name')
                category.aadhar_no = request.POST.get('aadhar_no')
                category.pan_no = request.POST.get('pan_no')
                category.alternative_no = request.POST.get('alternative_no')
                category.home_contact_no = request.POST.get('home_contact_no')
                category.blood_group = request.POST.get('blood_group')
                category.dob = request.POST.get('dob') or None
                category.marital_status = request.POST.get('marital_status')
                category.ot_applicable = request.POST.get('ot_applicable')

                # Accounting Details
                category.promoter_brand = request.POST.get('promoter_brand')
                category.esi_no = request.POST.get('esi_no')
                category.pf_no = request.POST.get('pf_no')
                category.salary_type = request.POST.get('salary_type')
                category.opening_balance = request.POST.get('opening_balance') or 0
                category.monthly_salary = request.POST.get('monthly_salary') or 0
                category.daily_salary = request.POST.get('daily_salary') or 0
                category.loan_amount = request.POST.get('loan_amount') or 0
                category.monthly_loan_deduction = request.POST.get('monthly_loan_deduction') or 0
                category.doj = request.POST.get('doj') or None
                category.enable_esi = request.POST.get('enable_esi')
                category.enable_pf = request.POST.get('enable_pf')
                category.esi_percentage = request.POST.get('esi_percentage') or 0
                category.pf_percentage = request.POST.get('pf_percentage') or 0
                category.allowed_leave = request.POST.get('allowed_leave') or 0

                # Bank Account
                category.bank_name = request.POST.get('bank_name')
                category.ifsc_code = request.POST.get('ifsc_code')
                category.account_no = request.POST.get('account_no')
                category.account_holder_name = request.POST.get('account_holder_name')
                category.bonus_percentage = request.POST.get('bonus_percentage') or 0
                category.work_time_from = request.POST.get('work_time_from') or None
                category.work_time_to = request.POST.get('work_time_to') or None

                # Other Details
                category.no_of_children = request.POST.get('no_of_children') or 0
                category.height = request.POST.get('height')
                category.weight = request.POST.get('weight')
                category.driving_license_no = request.POST.get('driving_license_no')
                category.quota = request.POST.get('quota')
                category.nature_of_employee = request.POST.get('nature_of_employee')
                category.ration_card_no = request.POST.get('ration_card_no')
                category.passport_no = request.POST.get('passport_no')
                category.nominees = request.POST.get('nominees')
                category.weekly_off = request.POST.get('weekly_off')
                category.rejoin_date = request.POST.get('rejoin_date') or None
                category.current_address = request.POST.get('current_address')
                category.medical_record = request.POST.get('medical_record')
                category.resignation_date = request.POST.get('resignation_date') or None

                category.is_admin = 1
                category.is_active = 1
                category.status = 1
                category.created_by = user_id
                category.updated_by = user_id
                category.created_on = format_datetime(date_time)
                category.updated_on = format_datetime(date_time)
                category.save()
                return JsonResponse({'message': 'success'})
            else:
                errors = form.errors.as_json()
                return JsonResponse({'message': 'form_error', 'errors': errors}, status=400)

        except Exception as e:
            return JsonResponse({'message': 'exception', 'error': str(e)}, status=500)



def employee_view(request):  
    role_id = request.session.get('role_id')
    has_access, error_message = check_user_access(role_id, 'master_employee', "read")

    if not has_access:
        return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to read employee details'})
            
    data = list(employee_table.objects.filter(status=1,company_id=1).order_by('-id').values())
    formatted = [
        {
            'id': index + 1,
            'action': '<button type="button" onclick="edit_data(\'{}\')" class="btn btn-outline-success btn-xs p-1"><i class="fas fa-edit"></i></button> \
                      <button type="button" onclick="delete_data(\'{}\')" class="btn btn-outline-danger btn-xs p-1"> <i class="fas fa-trash-alt"></i></button>'.format(item['id'], item['id']), 
            'cmpy': getItemNameById(company_table, item['company_id']) if item['company_id'] else '-', 
            'role': getItemNameById(role_table, item['role_id']) if item['role_id'] else '-', 
            'code': item['employee_code'] if item['employee_code'] else '-', 
            'name': item['name'] if item['name'] else '-', 
            'mail': item['email'] if item['email'] else '-', 
            'phone': item['mobile'] if item['mobile'] else '-', 
            'address': item['address_line1'] if item['address_line1'] else '-', 
            'status': '<span class="badge text-bg-success">Active</span>' if item['is_active'] else '<span class="badge text-bg-danger">Inactive</span>'  # Assuming is_active is a boolean field
        } 
        for index, item in enumerate(data)
    ]
    return JsonResponse({'data': formatted})


def employee_edit(request):
    if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == "POST":
         frm = request.POST
    data = employee_table.objects.filter(id=request.POST.get('id'))    
    return JsonResponse(data.values()[0])



def employee_update(request):
    if request.method == "POST":
        try:
            category_id = request.POST.get('id')
            category = employee_table.objects.get(id=category_id)
            form = EmployeeForm(request.POST, request.FILES, instance=category)
            role_id = request.session.get('role_id')
            has_access, error_message = check_user_access(role_id, 'master_employee', "update")

            if not has_access:
                return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to update employee details'})
            
            
            if form.is_valid():
                email = request.POST.get('email')

                if employee_table.objects.filter(email=email,status=1).exclude(id=category_id).exists():
                   return JsonResponse({
                        'message': 'email_exists',
                        'field': 'edit_email',  # <== This must match input ID
                        'error': 'This email is already in use.'
                    })

                
                updated_category = form.save(commit=False)
                company_id = request.POST.get('company_id')
                user_role = request.POST.get('user_role') or 0
                name = request.POST.get('name')
                user_name = request.POST.get('user_name')
                pwd = request.POST.get('pwd')
                address1 = request.POST.get('address1')
                address2 = request.POST.get('address2')
                mobile = request.POST.get('mobile')
                city = request.POST.get('city')
                state = request.POST.get('state')
                pincode = request.POST.get('pincode')
                photo = request.FILES.get('photo')
                is_active = request.POST.get('is_active')

                

                updated_category.company_id = company_id
                updated_category.role_id = user_role
                updated_category.branch_id = request.POST.get('branch_id') or 0
                updated_category.name = name
                updated_category.nick_name = user_name
                updated_category.email = email
                if pwd:
                    updated_category.password = hashlib.md5(pwd.encode()).hexdigest()

                updated_category.address_line1 = address1
                updated_category.address_line2 = address2
                updated_category.mobile = mobile
                updated_category.city = city
                updated_category.state = state
                updated_category.pincode = int(pincode) if pincode else None
               
                if photo:
                    updated_category.photo = photo
                
                # Basic Details
                updated_category.gender = request.POST.get('gender')
                updated_category.parent_name = request.POST.get('parent_name')
                updated_category.spouse_name = request.POST.get('spouse_name')
                updated_category.aadhar_no = request.POST.get('aadhar_no')
                updated_category.pan_no = request.POST.get('pan_no')
                updated_category.alternative_no = request.POST.get('alternative_no')
                updated_category.home_contact_no = request.POST.get('home_contact_no')
                updated_category.blood_group = request.POST.get('blood_group')
                updated_category.dob = request.POST.get('dob') or None
                updated_category.marital_status = request.POST.get('marital_status')
                updated_category.ot_applicable = request.POST.get('ot_applicable')

                # Accounting Details
                updated_category.promoter_brand = request.POST.get('promoter_brand')
                updated_category.esi_no = request.POST.get('esi_no')
                updated_category.pf_no = request.POST.get('pf_no')
                updated_category.salary_type = request.POST.get('salary_type')
                updated_category.opening_balance = request.POST.get('opening_balance') or 0
                updated_category.monthly_salary = request.POST.get('monthly_salary') or 0
                updated_category.daily_salary = request.POST.get('daily_salary') or 0
                updated_category.loan_amount = request.POST.get('loan_amount') or 0
                updated_category.monthly_loan_deduction = request.POST.get('monthly_loan_deduction') or 0
                updated_category.doj = request.POST.get('doj') or None
                updated_category.enable_esi = request.POST.get('enable_esi')
                updated_category.enable_pf = request.POST.get('enable_pf')
                updated_category.esi_percentage = request.POST.get('esi_percentage') or 0
                updated_category.pf_percentage = request.POST.get('pf_percentage') or 0
                updated_category.allowed_leave = request.POST.get('allowed_leave') or 0

                # Bank Account
                updated_category.bank_name = request.POST.get('bank_name')
                updated_category.ifsc_code = request.POST.get('ifsc_code')
                updated_category.account_no = request.POST.get('account_no')
                updated_category.account_holder_name = request.POST.get('account_holder_name')
                updated_category.bonus_percentage = request.POST.get('bonus_percentage') or 0
                updated_category.work_time_from = request.POST.get('work_time_from') or None
                updated_category.work_time_to = request.POST.get('work_time_to') or None

                # Other Details
                updated_category.no_of_children = request.POST.get('no_of_children') or 0
                updated_category.height = request.POST.get('height')
                updated_category.weight = request.POST.get('weight')
                updated_category.driving_license_no = request.POST.get('driving_license_no')
                updated_category.quota = request.POST.get('quota')
                updated_category.nature_of_employee = request.POST.get('nature_of_employee')
                updated_category.ration_card_no = request.POST.get('ration_card_no')
                updated_category.passport_no = request.POST.get('passport_no')
                updated_category.nominees = request.POST.get('nominees')
                updated_category.weekly_off = request.POST.get('weekly_off')
                updated_category.rejoin_date = request.POST.get('rejoin_date') or None
                updated_category.current_address = request.POST.get('current_address')
                updated_category.medical_record = request.POST.get('medical_record')
                updated_category.resignation_date = request.POST.get('resignation_date') or None

                updated_category.is_active = is_active      

                updated_category.updated_by = request.session.get('user_id')
                updated_category.updated_on = format_datetime(date_time)
                updated_category.save()
                return JsonResponse({'message': 'success'})
            else:
                errors = form.errors.as_json()
                return JsonResponse({'message': 'error', 'errors': errors})
        except Exception as e:
            return JsonResponse({'message': 'exception', 'error': str(e)})



def employee_delete(request):
    if request.method == 'POST':
        data_id = request.POST.get('id')     
        role_id = request.session.get('role_id')
        has_access, error_message = check_user_access(role_id, 'master_employee', "delete")

        if not has_access:
            return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to delete employee details'})
              
        try:
            updated = employee_table.objects.filter(id=data_id).update(status=0)
            if updated:
                return JsonResponse({'message': 'yes'})
            else:
                return JsonResponse({'message': 'no such data'})
        except Exception as e:
            return JsonResponse({'message': 'exception', 'error': str(e)})

    return JsonResponse({'message': 'Invalid request method'})

