from django.contrib import messages
from django.contrib.auth import authenticate, login as auth_login, logout
from django.shortcuts import render, redirect, get_object_or_404
from .models import skyonnAdmin, ClientDetails, SubcompanyDetails, Contact, Locations, AddContact, SublocationDetails,InternalTeam
from django.contrib.auth.hashers import make_password
from django.http import HttpResponse
import random
import string
from django.http import JsonResponse
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.exceptions import ObjectDoesNotExist
from .serializers import DetailsSerializer
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
import re
from django.http import JsonResponse
from django.db.models import Q
from django.core.mail import send_mail
import threading
import pandas as pd

def home(request):
    return render(request, 'skyonnadmin/home.html')


def create_admin(request):
    if request.method == 'POST':
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        phone_number = request.POST['phone']
        phone_number_2 = request.POST.get('phone_2')
        company_email = request.POST['company_email']
        personal_email = request.POST.get('personal_email')
        address = request.POST['address']
        work_location = request.POST['work_location']
        role = 'admin'
        password = request.POST['password']  # Assuming there's a password field in the form
        hashed_password = make_password(password)

        picture = request.FILES.get('picture')

        # Generate admin ID based on the last ID in the database
        last_admin = skyonnAdmin.objects.order_by('-id').first()
        if last_admin:
            last_id = int(last_admin.admin_id[4:])  # Extract the serial number part and convert to int
            new_id = last_id + 1
        else:
            new_id = 1
        admin_id = f'SKYA{new_id:03d}'  # Construct the new admin ID

        # Create the admin user
        admin = skyonnAdmin.objects.create(
            first_name=first_name,
            last_name=last_name,
            phone=phone_number,
            phone_number_2=phone_number_2,
            company_email=company_email,
            personal_email=personal_email,
            address=address,
            work_location=work_location,
            role=role,
            admin_id=admin_id,
            password=hashed_password,
            picture= picture
        )
        print((admin.first_name, admin.last_name))
        admin.backend = 'user.backend.PhoneAuthenticationBackend'
        auth_login(request, admin)

        return JsonResponse(
            {'success': 'Login successful', 'redirect_url': f'/skyonnadmin/admin/dashboard/{admin.admin_id}'})
    else:
        return render(request, 'skyonnadmin/home.html')

def validate_admin(request):
        if request.method == 'GET':
            email1 = request.GET.get('company_email')
            email2 = request.GET.get('personal_email')
            phone_number1 = request.GET.get('phone')
            phone_number2 = request.GET.get('phone_2')
            response = {
                'exists': False
            }
            if email1 and (skyonnAdmin.objects.filter(company_email=email1).exists() or
                           skyonnAdmin.objects.filter(personal_email=email1).exists()):
                response['exists'] = True

            if email2 and (skyonnAdmin.objects.filter(company_email=email2).exists() or
                           skyonnAdmin.objects.filter(personal_email=email2).exists()):
                response['exists'] = True

            if phone_number1 and (skyonnAdmin.objects.filter(phone=phone_number1).exists() or
                                  skyonnAdmin.objects.filter(phone_number_2=phone_number1).exists()):
                response['exists'] = True

            if phone_number2 and (skyonnAdmin.objects.filter(phone=phone_number2).exists() or
                                  skyonnAdmin.objects.filter(phone_number_2=phone_number2).exists()):
                response['exists'] = True

            return JsonResponse(response)


def admin_login(request):
    if request.method == 'POST':
        phone = request.POST.get('phone')
        password = request.POST.get('password')

        if not phone  and 'phone' in request.POST:
            return JsonResponse({'error': 'Please fill the phone number field.'}, status=400)
        if not password and 'password' in request.POST:  # Validate password if it's present
            return JsonResponse({'error': 'Please fill the password field.'}, status=400)

        admin = skyonnAdmin.objects.filter(phone=phone).first()
        if admin is None:
            return JsonResponse({'error': 'Incorrect phone number.'}, status=404)

        if password:
            if not admin.check_password(password):
                return JsonResponse({'error': 'Incorrect password.'}, status=401)

            return JsonResponse(
                {'success': 'Login successful', 'redirect_url': f'/skyonnadmin/admin/dashboard/{admin.admin_id}'})

        return JsonResponse({'success': 'Phone number is valid.'}, status=200)

    return JsonResponse({'error': 'Invalid request method.'}, status=405)


def admin_dashboard(request, admin_id):
    admin = get_object_or_404(skyonnAdmin, admin_id=admin_id)

    # Get the manager's first name
    first_name = admin.first_name.capitalize()
    full_name = f"{first_name}"
    print(full_name)

    return render(request, 'skyonnadmin/admin_dashboard.html', {'first_name': full_name, 'admin_id': admin_id,'picture': admin.picture})
    # Admin dashboard logic goes here


def logout_view(request):
    logout(request)
    return redirect('admin_home')

def get_admin_details(request):
        admin_id = request.GET.get('admin_id', None)
        print(admin_id)
        admin = get_object_or_404(skyonnAdmin, admin_id=admin_id)
        print('admin:', admin)

        admin_picture = admin.picture.url

        admin_data = {
            'first_name': admin.first_name,
            'last_name': admin.last_name,
            'phone': admin.phone,
            'phone_number_2': admin.phone_number_2,
            'company_email': admin.company_email,
            'personal_email': admin.personal_email,
            'address': admin.address,
            'work_location': admin.work_location,
            'admin_picture': admin_picture
        }
        return JsonResponse({'admin_data': admin_data})


def client_details(request):
    return render(request, 'skyonnadmin/client_details.html')


def add_subclient(request):
    admin_id = request.GET.get('admin_id', None)
    clients = ClientDetails.objects.all()
    return render(request, 'skyonnadmin/add_subclient.html', {'clients': clients, 'admin_id': admin_id})


def add_client(request):
    admin_id = request.GET.get('admin_id', None)
    print(admin_id)
    clients = ClientDetails.objects.all()
    return render(request, 'skyonnadmin/add_client.html', {'clients': clients, 'admin_id': admin_id})


def existing_client(request):
    clients = ClientDetails.objects.all()
    return render(request, 'skyonnadmin/existing_client.html', {'clients': clients})

def new_job_posting(request):
    admin_id = request.GET.get('admin_id', None)
    return render(request, 'skyonnadmin/new_job_posting.html', {'admin_id': admin_id})

def add_new_contact(request):
    clients = ClientDetails.objects.all()
    sub_clients = SubcompanyDetails.objects.all()
    return render(request, 'skyonnadmin/add_new_contact.html',{'clients': clients,'sub_clients': sub_clients})


@csrf_exempt
def save_details(request):
    if request.method == 'POST':

        # Extract data from the first form
        parent_company = request.POST.get('ParentCompany', '')
        locationId = request.POST.get('Location_Id', '')
        GST_No = request.POST.get('GSTNo', '')
        address_1 = request.POST.get('Address_1', '')
        state = request.POST.get('State', '')
        # Street = request.POST.get('Street', '')
        City  = request.POST.get('City', '')
        country = request.POST.get('country', '')
        address_2 = request.POST.get('Address_2', '')
        Pincode = request.POST.get('Pincode', '')

        client_id = generate_client_id(parent_company)
        print(client_id)
        if not parent_company or not locationId or not GST_No or not address_1 or not state or not City or not country or not Pincode:
            return JsonResponse({'status': 'error','message': 'Error while saving client.Please fill required fields'},
                                status=400)
        # if ClientDetails.objects.filter(parent_company=parent_company.upper()).exists():
        #     return JsonResponse({'status': 'error','field': 'ParentCompany', 'message': 'Parent Company already exists'}, status=400)
        # # Save data into the database
        parent_company_proper = parent_company.title()

        # Check for duplicate ParentCompany
        if ClientDetails.objects.filter(parent_company=parent_company_proper).exists():
            return JsonResponse(
                {'status': 'error', 'field': 'ParentCompany', 'message': 'Parent Company already exists'}, status=400)

        job_details = ClientDetails(
            parent_company=parent_company_proper,
            location_Id=locationId,
            GST_No=GST_No,
            address_1=address_1,
            state=state,
            # Street= Street,
            City=City,
            country=country,
            address_2=address_2,
            Pincode=Pincode,
            client_id=client_id,
        )
        job_details.save()
        admin_id = request.GET.get('admin_id', None)
        print(admin_id)
        return JsonResponse({'status': 'success', 'message': 'Client saved successfully.'})
    else:
        return HttpResponse('Invalid request method')


def check_parent_company(request):
    if request.method == 'GET':
        parent_company = request.GET.get('ParentCompany', '').strip().upper()
        print(parent_company)
        exists = ClientDetails.objects.filter(parent_company=parent_company).exists()
        return JsonResponse({'exists': exists})
    return JsonResponse({'error': 'Invalid request method'}, status=400)

def get_parentCompany(request):
    clients = ClientDetails.objects.values('parent_company')
    print(clients)
    return JsonResponse(list(clients), safe=False)

def save_sublocation(request):
  if request.method == 'POST':
    parent_company = request.POST.get('ParentCompany', '')
    department = request.POST.get('Department', '')
    Location = request.POST.get('Location', '')
    GST_No = request.POST.get('GSTNo', '')
    address_1 = request.POST.get('Address_1', '')
    address_2 = request.POST.get('Address_2', '')
    # Street = request.POST.get('Street', '')
    City = request.POST.get('City', '')
    State = request.POST.get('State', '')
    Pincode = request.POST.get('Pincode', '')
    country = request.POST.get('country', '')

    if not parent_company or not department or not Location or not GST_No or not address_1 or not State or not City or not country or not Pincode:
        return JsonResponse({'status': 'error', 'message': 'Error while saving Sub_Location.Please fill required fields'},
                            status=400)

    # Save data into the database
    job_details = SublocationDetails(
        parent_company=parent_company,
        department= department,
        Location=Location,
        GST_No=GST_No,
        address_1=address_1,
        address_2=address_2,
        # Street = Street,
        City=City,
        State=State,
        Pincode=Pincode,
        country=country, )
    job_details.save()
    admin_id = request.GET.get('admin_id', None)
    print(admin_id)
    return JsonResponse({'status': 'success', 'message': 'sublocation saved successfully.'})
  else:
      return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

def get_GSTNo(request):
    if request.method == 'GET':
        parent_company = request.GET.get('ParentCompany')
        gst_no = ClientDetails.objects.filter(parent_company=parent_company).values('GST_No')
        gst = list(gst_no)
        print(gst)
        return JsonResponse(gst[0],safe=False)
    else:
        return JsonResponse({'error': 'Invalid request'})


@csrf_exempt
def save_details_subcompany(request):
    print("00came")
    if request.method == 'POST':
        # Extract data from the first form
        parent_company = request.POST.get('ParentCompany', '')
        sub_company = request.POST.get('SubCompany', '')
        location_id = request.POST.get('Location_Id', '')
        GST_No = request.POST.get('GSTNo', '')
        address_1 = request.POST.get('Address_1', '')
        address_2 = request.POST.get('Address_2', '')
        # Street = request.POST.get('Street', '')
        City = request.POST.get('City', '')
        State = request.POST.get('State', '')
        Pincode = request.POST.get('Pincode', '')
        country = request.POST.get('country', '')

        sub_client_id = generate_client_id(parent_company)
        print(sub_client_id)
        if not parent_company or not sub_company or not location_id or not address_1 or not State or not City or not country or not Pincode:
            return JsonResponse({'status': 'error', 'message': 'Error while saving Sub_client.Please fill required fields'},
                                status=400)
        if SubcompanyDetails.objects.filter(sub_company=sub_company.title()).exists():
            return JsonResponse({'status': 'error','field': 'SubCompany', 'message': 'Sub_Company already exists'}, status=400)
        # Save data into the database
        job_details = SubcompanyDetails(
            parent_company=parent_company,
            sub_company=sub_company.title(),
            location_id=location_id,
            GST_No=GST_No ,
            address_1=address_1,
            address_2=address_2,
            # Street = Street,
            City = City,
            State = State,
            Pincode = Pincode,
            country= country,
            sub_client_id=sub_client_id,

        )
        job_details.save()
        admin_id = request.GET.get('admin_id', None)
        print(admin_id)
        return JsonResponse({'status': 'success', 'message': 'subclient saved successfully.'})

    else:
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

def check_sub_company(request):
    if request.method == 'GET':
        sub_company = request.GET.get('SubCompany', '').strip().upper()
        print(sub_company)
        exists = SubcompanyDetails.objects.filter(sub_company=sub_company).exists()
        return JsonResponse({'exists': exists})
    return JsonResponse({'error': 'Invalid request method'}, status=400)

def get_combined_details(request):
    parent_company = request.GET.get('parent_company')
    location = request.GET.get('location')

    # Fetch data from ClientDetails and SubcompanyDetails tables based on filters
    client_details = ClientDetails.objects.filter(parent_company=parent_company, location=location)
    subcompany_details = SubcompanyDetails.objects.filter(parent_company=parent_company, location=location)

    # Combine data from both tables
    combined_data = []

    # Add client details to combined_data
    for detail in client_details:
        combined_data.append({
            'parent_company': detail.parent_company,
            'location': detail.location,
            'department': detail.department,
            'gst_no': detail.gst_no,
            'address': detail.address,
            'client_id': detail.client_id,

        })

    # Add subcompany details to combined_data
    for detail in subcompany_details:
        combined_data.append({
            'parent_company': detail.parent_company,
            'sub_company': detail.sub_company,
            'location': detail.location,
            # 'department': detail.department,
            'gst_no': detail.gst_no,
            'address': detail.address,
            'client_id': detail.client_id,

        })
    print(combined_data)
    return JsonResponse(combined_data, safe=False)


def get_locations(request):
    print(0)
    if request.method == 'GET' and 'parent_company' in request.GET:
        print(1)
        parent_company = request.GET.get('parent_company')
        locations = SubcompanyDetails.objects.filter(parent_company=parent_company).values_list('location', flat=True)
        serialized_data = json.dumps(list(locations), cls=DjangoJSONEncoder)
        return JsonResponse(serialized_data, safe=False)
    else:
        return JsonResponse({'error': 'Invalid request'})


def generate_client_id(parent_company):
    # Extract first 4 letters from parent_company and convert to uppercase
    prefix = parent_company[:4].upper()
    # Generate 4 random integers
    suffix = ''.join(random.choices(string.digits, k=4))
    # Concatenate prefix and suffix to form the client_id
    client_id = prefix + suffix
    return client_id


# def get_contacts(request):
#     if request.method == 'GET':
#         client = request.GET.get('Client')
#         print(client)
#         SPOC_Details = AddContact.objects.filter(Company=client).values('FirstName','Department')
#
#         SPOC_Details_list = list(SPOC_Details)
#         return JsonResponse(SPOC_Details_list, safe=False)
#     else:
#         return JsonResponse({'error': 'Invalid request'})


def add_locations(request):
    locations_list = ['Hyderabad', 'Pune', 'Chennai', 'Mumbai', 'Cochin', 'Ahmedabad', 'Bangalore']
    for location in locations_list:
        try:
            Locations.objects.get(location=location)
            print(f"Location '{location}' already exists.")
        except ObjectDoesNotExist:
            Locations.objects.create(location=location)
            print(f"Added location '{location}' to the database.")


def get_subclients(request):
    if request.method == 'GET' and 'parent_company' in request.GET:
        parent_company = request.GET['parent_company']
                                                    # Query SubcompanyDetails table to filter sub-clients by parent company
        sub_clients = SubcompanyDetails.objects.filter(parent_company=parent_company).values_list('sub_company',
                                                                                                  flat=True)
        # Convert queryset to list
        sub_clients_list = list(sub_clients)
        return JsonResponse(sub_clients_list, safe=False)
    else:
        return JsonResponse({'error': 'Invalid request'})


def get_filtered_data(request):
    if request.method == 'GET':
        client = request.GET.get('client')
        sub_client = request.GET.get('subClient')

        client_details = ClientDetails.objects.filter(parent_company=client)
        client_id = [data.client_id for data in client_details]
        print(client_id)
                                                                        # Filter SubcompanyDetails based on client and sub-client
        if sub_client == 'All Sub Clients':
            sub_company_details = SubcompanyDetails.objects.filter(parent_company=client)
        else:
            sub_company_details = SubcompanyDetails.objects.filter(parent_company=client, sub_company=sub_client)
        sub_client_id=[data.sub_client_id for data in sub_company_details]
        print(sub_client_id)

        filtered_data = {
            'client_details':list(client_details.values()),
            'sub_company_details': list(sub_company_details.values())
        }

        # # Serialize the filtered data
        serializer = DetailsSerializer(filtered_data)
        print(serializer.data)

        return JsonResponse(serializer.data, safe=False)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)

def save_new_entry(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        rowData = data.get('rowData')
        department = data.get('department')

        # Retrieve the SubcompanyDetails instance based on the department
        subcompany_instance = get_object_or_404(SubcompanyDetails, department=department)

        # Save the new contact data to the appropriate contact field
        if subcompany_instance:
            new_contact = Contact.objects.create(**rowData)
            getattr(subcompany_instance, 'admin_contacts').add(new_contact)
            return JsonResponse({'message': 'New entry saved successfully.'}, status=200)
        else:
            return JsonResponse({'message': f'No SubcompanyDetails instance found for department: {department}'}, status=404)
    else:
        return JsonResponse({'message': 'Invalid request method.'}, status=400)

def add_contact(request):
    print("00came")
    if request.method == 'POST':
        # Extract data from the form
        Company = request.POST.get('Company', '')
        Sub_company = request.POST.get('Sub_Company') or Company
        LastName = request.POST.get('LastName', '')
        FirstName = request.POST.get('FirstName', '')
        Department = request.POST.get('Department', '')
        Designation = request.POST.get('Designation', '')
        Phone_number = request.POST.get('Phone_number', '')
        Email = request.POST.get('Email', '')

        contact_id = generate_client_id(Company)
        print(contact_id)
        if not Company or not FirstName or not Department or not Designation or not Phone_number or not Email:
            return JsonResponse({'status': 'error', 'message': 'Error while saving Sub_client.Please fill required fields'},
                                status=400)

        # Save data into the database
        add_contact = AddContact(
            Company=Company,
            Sub_company=Sub_company,
            FirstName=FirstName,
            LastName=LastName,
            Department=Department,
            Designation=Designation,
            Phone_number=Phone_number,
            Email=Email,
            Contact_id=contact_id
        )
        add_contact.save()

        admin_id = request.GET.get('admin_id', None)
        print(admin_id)

        return JsonResponse({'status': 'success', 'message': 'Contact saved successfully.'})

    else:
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

def validate_field(request):
    if request.method == 'GET':
        email = request.GET.get('Email')
        phone_number = request.GET.get('Phone_number')
        response = {
            'exists': False
        }
        if email and AddContact.objects.filter(Email=email).exists():
            response['exists'] = True
        elif phone_number and AddContact.objects.filter(Phone_number=phone_number).exists():
            response['exists'] = True
        return JsonResponse(response)


def validate_cell_field(request):
    if request.method == 'GET':
        email = request.GET.get('Email')
        phone_number = request.GET.get('Phone_number')
        contact_id = request.GET.get('Contact_id')
        print('contact_id:',contact_id)

        response = {
            'email_exists': False,
            'phone_exists': False
        }
        if email:
            existing_email_contact = AddContact.objects.filter(Email=email).first()
            if existing_email_contact and existing_email_contact.Contact_id != contact_id:
                response['email_exists'] = True

        # Check for existing phone number but ignore if it's the same contact
        if phone_number:
            existing_phone_contact = AddContact.objects.filter(Phone_number=phone_number).first()
            if existing_phone_contact and existing_phone_contact.Contact_id != contact_id:
                response['phone_exists'] = True

        return JsonResponse(response)



# def save_job_posting(request):
#     if request.method == 'POST':
#         # Extract data from the form
#         Client = request.POST.get('Client', '')
#         JobID = request.POST.get('JobID', '')
#         Location = request.POST.get('Location', '')
#         SPOC = request.POST.get('SPOC', '')
#         SPOC2 = request.POST.get('SPOC2', '')
#         StartDate = request.POST.get('StartDate', '')
#         CloseDate = request.POST.get('CloseDate', '')
#         BudgetMin = request.POST.get('BudgetMin', '')
#         BudgetMax = request.POST.get('BudgetMax', '')
#         Header = request.POST.get('Header', '')
#         JobDescription = request.POST.get('JobDescription', '')
#         Experience_in_Yrs = request.POST.get('Experience_in_Yrs', '')
#         NoOfPosting = request.POST.get('NoOfPosting', '')
#         Type = request.POST.get('Type', '')
#         SpecialInstructions = request.POST.get('SpecialInstructions', '')
#         JD = request.POST.get('JD', '' )
#
#         jobposting = JobPosting(
#             Client=Client,
#             JobID=JobID,
#             Location=Location,
#             SPOC=SPOC,
#             SPOC2=SPOC2,
#             StartDate=StartDate,
#             CloseDate=CloseDate,
#             BudgetMin=BudgetMin,
#             BudgetMax=BudgetMax,
#             Header=Header,
#             JobDescription=JobDescription,
#             Experience_in_Yrs=Experience_in_Yrs,
#             NoOfPosting=NoOfPosting,
#             Type=Type,
#             SpecialInstructions=SpecialInstructions,
#             JD=JD,
#         )
#         jobposting.save()
#         print(jobposting)
#
#         admin_id = request.GET.get('admin_id', None)
#         print(admin_id)
#
#         return JsonResponse({'status': 'success', 'message': 'Job_posting saved successfully.'})
#
#     else:
#         return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

def get_team_details(request):
    if request.method == 'GET':
        client = request.GET.get('client')
        sub_client = request.GET.get('subClient')

        if not sub_client:
            contacts = AddContact.objects.filter(Company=client, Sub_company='')
        elif sub_client == 'All Sub Clients':
            contacts = AddContact.objects.filter(Company=client)
        else:
            contacts = AddContact.objects.filter(Company=client, Sub_company=sub_client)

        filtered_data = {
            'contacts': list(contacts.values()),
        }
        # Return serialized data as JSON response
        return JsonResponse(filtered_data, safe=False)
        # return JsonResponse({"success": True, "message": "Contact added successfully."})

    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)


def get_department(request):
    if request.method == 'GET':
        department = request.GET.get('Department')
        client = request.GET.get('client')
        sub_client = request.GET.get('subClient')

        if not sub_client:
            departments = AddContact.objects.filter(Department=department, Company=client, Sub_company='').distinct()
        elif sub_client == 'All Sub Clients':
            departments = AddContact.objects.filter(Department=department, Company=client).distinct()
        else:
            departments = AddContact.objects.filter(Department=department, Company=client,
                                                    Sub_company=sub_client).distinct()
            # Convert queryset to list
        department_list = list(departments.values())

        return JsonResponse(department_list, safe=False)
        # return JsonResponse({"success": True, "message": "Contact added successfully."})
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)


def get_SearchData(request):
    if request.method == 'GET':
        client = request.GET.get('client')
        sub_client = request.GET.get('subClient')
        searchKeyword = request.GET.get('searchKeyword')

        query1 = Q()
        query2 = Q()
        query3 = Q()

        if client:
            query1 &= Q(Company__icontains=client)
            query2 &= Q(parent_company__icontains=client)
            query3 &= Q(parent_company__icontains=client)

        if sub_client and sub_client != 'All Sub Clients':
            query1 &= Q(Sub_company__icontains=sub_client)
            query2 &= Q(parent_company__icontains=sub_client)
            query3 &= Q(sub_company__icontains=sub_client)

        if searchKeyword:
            keywords = searchKeyword.split()
            search_query1 = Q()

            search_query1 |= (
                    Q(Sub_company__icontains=searchKeyword) |
                    Q(Company__icontains=searchKeyword) |
                    Q(FirstName__icontains=searchKeyword) |
                    Q(LastName__icontains=searchKeyword) |
                    Q(Designation__icontains=searchKeyword) |
                    Q(Department__icontains=searchKeyword) |
                    Q(Phone_number__icontains=searchKeyword) |
                    Q(Email__icontains=searchKeyword)
            )

            # Handle case for multiple words in keyword (e.g., "account department")
            for word in keywords:
                search_query1 |= (
                        Q(Sub_company__icontains=word) |
                        Q(Company__icontains=word) |
                        Q(FirstName__icontains=word) |
                        Q(LastName__icontains=word) |
                        Q(Designation__icontains=word) |
                        Q(Department__icontains=word) |
                        Q(Phone_number__icontains=word) |
                        Q(Email__icontains=word)
                )

            # Handle concatenated names (e.g., "JohnDoe")
            if len(keywords) == 1:  # Check for single-word input
                for i in range(1, len(searchKeyword)):
                    possible_first_name = searchKeyword[:i]
                    possible_last_name = searchKeyword[i:]
                    search_query1 |= (
                            Q(FirstName__icontains=possible_first_name) &
                            Q(LastName__icontains=possible_last_name)
                    )
            elif len(keywords) == 2:  # If two parts exist, treat as FirstName and LastName
                first_name, last_name = keywords
                search_query1 |= (
                        Q(FirstName__icontains=first_name) & Q(LastName__icontains=last_name)
                )

            query1 &= search_query1

            search_query2 = (
                    Q(parent_company__icontains=searchKeyword) | Q(GST_No__icontains=searchKeyword) |
                    Q(location_Id__icontains=searchKeyword))
            query2 &= search_query2

            search_query3 = (
                    Q(sub_company__icontains=searchKeyword) | Q(parent_company__icontains=searchKeyword) |
                    Q(GST_No__icontains=searchKeyword) | Q(location_id__icontains=searchKeyword))
            query3 &= search_query3

        contacts = AddContact.objects.filter(query1).values()
        client_details = ClientDetails.objects.filter(query2).values()
        sub_company_details = SubcompanyDetails.objects.filter(query3).values()

        filtered_data = {
            'contacts': list(contacts),
            'client_details': list(client_details),
            'sub_company_details': list(sub_company_details)
        }

        return JsonResponse(filtered_data, safe=False)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)


def edit_CompanyDetails(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            id = data.get('client_id') or data.get('sub_client_id')
            print(id)

            if not id:
                return JsonResponse({'error': 'ID parameter missing'}, status=400)

            if 'client_id' in data:
                client = ClientDetails.objects.filter(client_id=id).first()
                if client:
                    client.parent_company = data.get('parent_company', client.parent_company)
                    client.GST_No = data.get('GST_No', client.GST_No)
                    client.location_Id = data.get('location_Id', client.location_Id)
                    client.address_1 = data.get('address_1', client.address_1)
                    client.address_2 = data.get('address_2', client.address_2)
                    client.City = data.get('City', client.City)
                    client.state = data.get('state', client.state)
                    client.Pincode = data.get('Pincode', client.Pincode)
                    client.country = data.get('country', client.country)
                    client.save()
                    print(client)
                    return JsonResponse({'message': 'Client details updated successfully.'}, status=200)

            if 'sub_client_id' in data:
                sub_client = SubcompanyDetails.objects.filter(sub_client_id=id).first()
                if sub_client:
                    sub_client.parent_company = data.get('parent_company', sub_client.parent_company)
                    sub_client.sub_company = data.get('sub_company', sub_client.sub_company)
                    sub_client.GST_No = data.get('GST_No', sub_client.GST_No)
                    sub_client.location_id = data.get('location_id', sub_client.location_id)
                    sub_client.address_1 = data.get('address_1', sub_client.address_1)
                    sub_client.address_2 = data.get('address_2', sub_client.address_2)
                    sub_client.City = data.get('City', sub_client.City)
                    sub_client.State = data.get('State', sub_client.State)
                    sub_client.Pincode = data.get('Pincode', sub_client.Pincode)
                    sub_client.country = data.get('country', sub_client.country)
                    sub_client.save()
                    print(sub_client)
                    return JsonResponse({'message': 'Sub-client details updated successfully.'}, status=200)

            return JsonResponse({'error': 'Company details not found.'}, status=404)

        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON'}, status=400)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Invalid request method'}, status=405)


def delete_CompanyDetails(request):
    if request.method != 'DELETE':
        return JsonResponse({'error': 'Invalid HTTP method. Only DELETE is allowed.'}, status=405)

    try:
        data = json.loads(request.body)
        client_id = data.get('client_id')
        sub_client_id = data.get('sub_client_id')
        parent_company = data.get('parent_company')

        if sub_client_id:
            # Delete only the specific subclient
            sub_clients_deleted, _ = SubcompanyDetails.objects.filter(sub_client_id=sub_client_id).delete()
            response = {
                'message': 'Subclient deleted successfully.',
                'sub_clients_deleted': sub_clients_deleted
            }
            return JsonResponse(response, status=200)

        if client_id and parent_company:
            # Delete related sub-clients and contacts
            sub_clients_deleted, _ = SubcompanyDetails.objects.filter(parent_company=parent_company).delete()
            contacts_deleted, _ = AddContact.objects.filter(Company=parent_company).delete()

            # Delete the main client
            client = ClientDetails.objects.get(client_id=client_id, parent_company=parent_company)
            client.delete()

            response = {
                'message': 'Client and related data deleted successfully.',
                'client_deleted': 1,
                'sub_clients_deleted': sub_clients_deleted,
                'contacts_deleted': contacts_deleted
            }
            return JsonResponse(response, status=200)

        return JsonResponse({'error': 'Insufficient data provided to delete any record.'}, status=400)

    except ClientDetails.DoesNotExist:
        return JsonResponse({'error': 'Client with the given ID and Parent Company does not exist'}, status=404)
    except Exception as e:
        return JsonResponse({'error': f'An error occurred: {str(e)}'}, status=500)



@csrf_exempt
def edit_teamDetails(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        id = data.get('Contact_id', None)
        print(id)

        if id:
            try:
                contact = AddContact.objects.get(Contact_id=id)
                print(contact)

                contact.Company = data.get('Company', contact.Company)
                contact.Sub_company = data.get('Sub_company', contact.Sub_company)
                contact.FirstName = data.get('FirstName', contact.FirstName)
                contact.LastName = data.get('LastName', contact.LastName)
                contact.Department = data.get('Department', contact.Department)
                contact.Designation = data.get('Designation', contact.Designation)
                contact.Phone_number = data.get('Phone_number', contact.Phone_number)
                contact.Email = data.get('Email', contact.Email)
                contact.save()
                print(contact)
                return JsonResponse({'message': 'Contact updated successfully.'}, status=200)
            except AddContact.DoesNotExist:
                return JsonResponse({'error': 'Contact not found.'}, status=404)
            except Exception as e:
                return JsonResponse({'error': str(e)}, status=500)
        else:
            return JsonResponse({'error': 'Email not provided.'}, status=400)
    else:
        return JsonResponse({'error': 'Invalid request method.'}, status=405)


def delete_teamDetails(request):
    try:
        # Get the contact_id from the query parameters instead of the request body
        contact_id = request.GET.get('Contact_id')
        print('contact_id:', contact_id)

        if contact_id is None:
            return JsonResponse({'error': 'Contact ID not provided'}, status=400)

        # Try to get the contact and delete it
        contact = AddContact.objects.get(Contact_id=contact_id)
        contact.delete()

        return JsonResponse({'success': f'Contact with id {contact_id} deleted successfully'})

    except AddContact.DoesNotExist:
        return JsonResponse({'error': 'Contact does not exist'}, status=404)

    except Exception as e:
        # Log the error and return a 500 status
        print(f'Error deleting contact: {e}')
        return JsonResponse({'error': str(e)}, status=500)


def edit_internalTeam(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        email = data.get('Email1', None)
        print(email)

        if email:
            try:
                employee = InternalTeam.objects.get(Email1=email)

                employee.FirstName = data.get('FirstName', employee.FirstName)
                employee.LastName = data.get('LastName', employee.LastName)
                employee.Designation = data.get('Designation', employee.Designation)
                employee.Department = data.get('Department', employee.Department)
                employee.PhoneNo1 = data.get('PhoneNo1', employee.PhoneNo1)
                employee.LandNumber = data.get('LandNumber', employee.LandNumber)
                employee.Email2 = data.get('Email2', employee.Email2)
                employee.Level = data.get('Level', employee.Level)
                employee.save()
                print(employee)
                return JsonResponse({'message': 'Internal Team updated successfully.'}, status=200)
            except AddContact.DoesNotExist:
                return JsonResponse({'error': 'Contact not found.'}, status=404)
            except Exception as e:
                return JsonResponse({'error': str(e)}, status=500)
        else:
            return JsonResponse({'error': 'Email not provided.'}, status=400)
    else:
        return JsonResponse({'error': 'Invalid request method.'}, status=405)


def delete_internalTeam(request):
    try:
        email = request.GET.get('Email1')
        print(email)

        employee = InternalTeam.objects.get(Email1=email)
        print(employee)
        employee.delete()
        return JsonResponse({'success':f'Data with Email {email} deleted successfully'})
    except InternalTeam.DoesNotExist:
        return JsonResponse({'error': 'Employee does not exist'}, status=404)

    except Exception as e:
        # Log the error and return a 500 status
        print(f'Error deleting Internal Team Details: {e}')
        return JsonResponse({'error': str(e)}, status=500)


def print_internalTeam(request):
    email = request.GET.get('Email1')
    print(email)

    if email:
        try:
            employee = InternalTeam.objects.get(Email1=email)

            data = {
                'FirstName': employee.FirstName,
                'LastName': employee.LastName,
                'Designation': employee.Designation,
                'Department': employee.Department,
                'PhoneNo1': employee.PhoneNo1,
                'LandNumber': employee.LandNumber,
                'Email1': employee.Email1,
                'Email2': employee.Email2,
                'Level': employee.Level
            }
            print(employee)
            return JsonResponse(data, status=200)
        except AddContact.DoesNotExist:
            return JsonResponse({'error': 'Contact not found.'}, status=404)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    else:
        return JsonResponse({'error': 'Email not provided.'}, status=400)


def validate_existingEmployee(request):
    if request.method == 'GET':
        email1 = request.GET.get('Email1')
        email2 = request.GET.get('Email2')
        phone_number1 = request.GET.get('PhoneNo1')
        phone_number2 = request.GET.get('PhoneNo2')

        response = {
            'email_exists': False,
            'phone_exists': False,

        }
        if email2:
            existing_phone_contact1 = InternalTeam.objects.filter(Email1=email2).first()
            existing_phone_contact2 = InternalTeam.objects.filter(Email2=email2).first()
            if (existing_phone_contact1 and existing_phone_contact1.Email1 != email1) or \
                    (existing_phone_contact2 and existing_phone_contact2.Email1 != email1):
                response['email_exists'] = True

        # Check for existing phone number but ignore if it's the same contact
        if phone_number1:
            existing_phone_contact1 = InternalTeam.objects.filter(PhoneNo1=phone_number1).first()
            existing_phone_contact2 = InternalTeam.objects.filter(LandNumber=phone_number1).first()
            if (existing_phone_contact1 and existing_phone_contact1.Email1 != email1) or \
                    (existing_phone_contact2 and existing_phone_contact2.Email1 != email1):
                response['phone_exists'] = True

        if phone_number2:
            existing_phone_contact1 = InternalTeam.objects.filter(PhoneNo1=phone_number2).first()
            existing_phone_contact2 = InternalTeam.objects.filter(LandNumber=phone_number2).first()
            if (existing_phone_contact1 and existing_phone_contact1.Email1 != email1) or \
                    (existing_phone_contact2 and existing_phone_contact2.Email1 != email1):
                response['phone_exists'] = True

        return JsonResponse(response)



def Internal_team_details(request):
    admin_id = request.GET.get('admin_id', None)
    print(admin_id)
    return render(request, 'skyonnadmin/Internal_team_details.html',{'admin_id': admin_id})


def save_Internal_team_Details(request):
    if request.method == 'POST':
        FirstName = request.POST.get('FirstName').strip()
        LastName = request.POST.get('LastName')
        Designation = request.POST.get('Designation')
        Department = request.POST.get('Department')
        Address_1 = request.POST.get('Address_1')
        Address_2 = request.POST.get('Address_2')
        City = request.POST.get('City')
        State = request.POST.get('State')
        Country = request.POST.get('Country')
        Pincode = request.POST.get('Pincode')
        PhoneNo1 = request.POST.get('PhoneNo1')
        LandNumber = request.POST.get('LandNumber')
        Email1 = request.POST.get('Email1')
        Email2 = request.POST.get('Email2')
        Level = request.POST.get('Level')

        fullName = FirstName + '' + LastName

        Login = Email1
        Password = FirstName + '@123'
        user_id = FirstName.upper()[:3] + PhoneNo1[:4]

        internal_team = InternalTeam(
            FirstName=FirstName,
            LastName=LastName,
            Designation=Designation,
            Department=Department,
            Address_1=Address_1,
            Address_2=Address_2,
            City=City,
            State=State,
            Pincode=Pincode,
            Country=Country,
            PhoneNo1=PhoneNo1,
            LandNumber=LandNumber,
            Email1=Email1,
            Email2=Email2,
            Level=Level,
            Login=Login,
            Password=Password,
            user_id=user_id,
            FullName = fullName
        )
        internal_team.save()

        # email_thread= threading.Thread(target=send_login_credentials, args=(FirstName, Login, Password, Email1))
        # email_thread.start()

        # Return JSON response
        return JsonResponse({'status': 'success', 'message': 'Internal team details saved successfully.'})
    else:
        return HttpResponse('Invalid request method', status=405)

# def send_login_credentials(FirstName, Login, Password, Email1):
#     subject = 'Your Login Credentials'
#     message = f'Hi {FirstName}, \n\n Your Login Credentials are: \n Login_id : {Login} \n Password : {Password}'
#     from_email = 'subramanyajithendra@gmail.com'
#     recipient_list = [Email1]
#     send_mail(subject, message, from_email, recipient_list)


def validate_internal_team(request):
    if request.method == 'GET':
        email1 = request.GET.get('Email1')
        email2 = request.GET.get('Email2')
        phone_number1 = request.GET.get('PhoneNo1')
        phone_number2 = request.GET.get('LandNumber')
        response = {
            'exists': False
        }
        if email1 and (InternalTeam.objects.filter(Email1=email1).exists() or InternalTeam.objects.filter(Email2=email1).exists()):
            response['exists'] = True
        if email2 and (InternalTeam.objects.filter(Email1=email2).exists() or InternalTeam.objects.filter(Email2=email2).exists()):
            response['exists'] = True
        if phone_number1 and (InternalTeam.objects.filter(PhoneNo1=phone_number1).exists() or InternalTeam.objects.filter(LandNumber=phone_number1).exists()):
            response['exists'] = True
        elif phone_number2 and (InternalTeam.objects.filter(PhoneNo1=phone_number2).exists() or InternalTeam.objects.filter(LandNumber=phone_number2).exists()):
            response['exists'] = True
        return JsonResponse(response)


# def existing_employee(request):
#     employees = InternalTeam.objects.all()
#
#     employees_data = []
#     for employee in employees:
#         employees_data.append({
#             'FirstName': employee.FirstName,
#             'LastName': employee.LastName,
#             'Designation': employee.Designation,
#             'Department': employee.Department,
#             'Address_1': employee.Address_1,
#             'Address_2': employee.Address_2,
#             'City': employee.City,
#             'State': employee.State,
#             'Pincode': employee.Pincode,
#             'Country': employee.Country,
#             'PhoneNo1': employee.PhoneNo1,
#             'PhoneNo2': employee.PhoneNo2,
#             'Email1': employee.Email1,
#             'Email2': employee.Email2,
#             'Band': employee.Band
#         })
#
#     return JsonResponse({'employees': employees_data})


def get_row_count(request):
    if request.method == 'POST' and request.FILES['excelFile']:
        try:
            excel_file = request.FILES['excelFile']
            df = pd.read_excel(excel_file)  # Requires pandas and openpyxl
            row_count = len(df.index)  # Count the rows in the DataFrame
            return JsonResponse({'row_count': row_count})
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)
    return JsonResponse({'error': 'Invalid request'}, status=400)

def load_excel_data(request):
    if request.method == 'POST' and request.FILES.get('excelFile'):
        excel_file = request.FILES['excelFile']
        data = pd.read_excel(excel_file)

        required_columns = ['FirstName', 'LastName', 'Designation', 'Department', 'Address_1', 'City',
                            'State', 'Pincode', 'Country', 'PhoneNo1','LandNumber', 'Email1', 'Level']

        data[['PhoneNo1', 'LandNumber']] = data[['PhoneNo1', 'LandNumber']].fillna('')

        empty_fields = {}

        for column in required_columns:
            if column not in ['PhoneNo1','LandNumber'] and data[column].isnull().any():
                empty_fields[column] = data[data[column].isnull()].index.tolist()

        missing_contact = data[(data['PhoneNo1'] == '') & (data['LandNumber'] == '')].index.tolist()

        if missing_contact:
            empty_fields['Contact'] = missing_contact

        if empty_fields:
            return JsonResponse({'error': True,
                       'message': 'Some fields are empty in the provided Excel sheet.','empty_fields': empty_fields}, status=400)

        valid_data = data[(data['PhoneNo1'] != '') | (data['LandNumber'] != '')]
        print(valid_data)

        return JsonResponse({'error': False,'data': valid_data.to_dict(orient='records')}, safe=False)

    return JsonResponse({'error': True,'message': "No file uploaded"}, status=400)


def process_row(request):
    if request.method == 'POST':
        try:
            row_data = json.load(request.body)
            print(row_data)

            FirstName = row_data.get('FirstName')
            LastName = row_data.get('LastName')
            Designation = row_data.get('Designation')
            Department = row_data.get('Department')
            Address_1 = row_data.get('Address_1')
            Address_2 = row_data.get('Address_2')
            City = row_data.get('City')
            State = row_data.get('State')
            Pincode = row_data.get('Pincode')
            PhoneNo1 = row_data.get('PhoneNo1')
            LandNumber = row_data.get('LandNumber')
            Email1 = row_data.get('Email1')
            Email2 = row_data.get('Email2')
            Level = row_data.get('Level')

            return JsonResponse({"message": "Row processed successfully", "data": row_data}, status=200)

        except Exception as e:
            return JsonResponse({"error": f"Failed to process row: {str(e)}"}, status=400)

    return JsonResponse({"error": "Invalid request method"}, status=400)


def existing_employee(request):
    employees = InternalTeam.objects.all()

    employees_data = []
    for employee in employees:
        employees_data.append({
            'FirstName': employee.FirstName,
            'LastName': employee.LastName,
            'Designation': employee.Designation,
            'Department': employee.Department,
            'PhoneNo1': employee.PhoneNo1,
            'LandNumber': employee.LandNumber,
            'Email1': employee.Email1,
            'Email2': employee.Email2,
            'Level': employee.Level
        })

    return JsonResponse({'employees': employees_data})

def get_employee(request):
    if request.method == 'GET':
        firstName = request.GET.get('firstName')
        lastName = request.GET.get('lastName')
        email = request.GET.get('Email1')
        print('email:',email)
        try:

            emp_obj = InternalTeam.objects.filter((Q(FirstName=firstName) | Q(LastName=lastName)) & Q(Email1=email)).first()
            emp_data = {
                'FirstName': emp_obj.FirstName,
                'LastName': emp_obj.LastName,
                'Designation': emp_obj.Designation,
                'Department': emp_obj.Department,
                'Address_1': emp_obj.Address_1,
                'Address_2': emp_obj.Address_2,
                'City': emp_obj.City,
                'State': emp_obj.State,
                'Pincode': emp_obj.Pincode,
                'Country': emp_obj.Country,
                'PhoneNo1': emp_obj.PhoneNo1,
                'LandNumber': emp_obj.LandNumber,
                'Email1': emp_obj.Email1,
                'Email2': emp_obj.Email2,
                'Level': emp_obj.Level,
            }
            return JsonResponse(emp_data)
        except InternalTeam.DoesNotExist:
            return JsonResponse({'error': 'Client not found'}, status=404)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)
