from email.mime.image import MIMEImage

from django.contrib import messages
from datetime import  datetime
from django.shortcuts import  redirect
from visitors_app.models import user,appointment,roles,location,company,department,website_setting,appointment_reject
from django.contrib.auth.hashers import check_password, make_password
from django.http import JsonResponse
from django.db import connection
from visitors_app.views import date_time,generate_vms_string,generate_unique_request_id
# from gate_keeper_app.whatsapps_send_notification import whatsapps_send_notifications
from django.shortcuts import get_object_or_404
from visitors_app.context_processors import my_constants
from django.shortcuts import render
from django.template.loader import render_to_string
from visitor_management import settings
from django.utils.html import strip_tags
from django.core.mail import  EmailMultiAlternatives
from django.core import signing
import base64
import os
from PIL import Image
import io
import requests
from django.db.models import Q
import requests
from visitor_management import settings
from gate_keeper_app.visitor_reject_whatsapp_notification import visitor_reject_whatsapp_notification
from gate_keeper_app.visitor_invite_url_whatsapp_notification import whatsapps_send_notifications
from gate_keeper_app.visitor_request_accepted_whatsapp_notification import visitor_accepted_whatsapp_notification
database_name = settings.DATABASE_NAME
# Create your views here.


def update_appointment_status(decrypted_appointment_id, status, user_check, from_email,request):
    """
    Update the appointment status to either 'accepted' or 'rejected'.

    Parameters:
    - decrypted_appointment_id: The ID of the appointment to be updated.
    - status: The new status to set (either 'accepted' or 'rejected').
    - user_check: The currently logged-in user object.
    - request: The HTTP request object.
    """
    appointment_instance = get_object_or_404(appointment, id=decrypted_appointment_id)

    # Check if the appointment belongs to the logged-in employee
    if appointment_instance.employee_id != user_check.id:
        messages.error(request, "You are not authorized to modify this appointment.")
        return

    # Check if the appointment is already in the desired state
    if appointment_instance.status == status:
        messages.error(request, f"Appointment is already {status}.")
        return

    # If the appointment is being rejected, save the reason
    if status == 'rejected':
        # Create a new record in the AppointmentReject table
        appointment_reject.objects.create(
            appointment_id=decrypted_appointment_id,
            reason='',
            date='',
            time='',
            created_at=date_time()
        )

    # Update the appointment status
    appointment_instance.status = status
    appointment_instance.employee_approval = status
    appointment_instance.save()
    # ---------------- EMAIL PART ---------------- #
    visitors_get_id =user.objects.filter(id=appointment_instance.visitors_id).first()
    employee_get_id =user.objects.filter(id=appointment_instance.employee_id).first()
    recipient_email = visitors_get_id.email
    visitors_first_name = visitors_get_id.first_name
    visitors_last_name = visitors_get_id.last_name
    employee_first_name = employee_get_id.first_name
    employee_last_name = employee_get_id.last_name

    visit_schedule = f"{appointment_instance.date} {appointment_instance.time}"

    # employee_obj = user.objects.filter(email=appointment_instance.employee_email).first()
    employee_obj = employee_get_id
    dept_obj = department.objects.filter(id=employee_obj.department_id).first() if employee_obj else None
    department_name = dept_obj.department_name if dept_obj else ""

    company_obj = company.objects.filter(id=employee_obj.company_id).first() if employee_obj else None
    company_name = company_obj.company_name if company_obj else ""

    context = {
        'company_name': company_name,
        'visitor_name': f"{visitors_first_name} {visitors_last_name}",
        'person_name': f"{employee_first_name} {employee_last_name}",
        'person_departments': department_name,
        'visit_schedule': visit_schedule,
        'request_id':appointment_instance.request_id
    }

    if status == 'accepted':
        template_name = 'dashboard/email_templates/visitor_request_approved.html'
        subject = f'Visitor Request Approved – {company_name}'
    else:
        template_name = 'dashboard/email_templates/visitor_request_rejection.html'
        subject = f'Visitor Request Update – {company_name}'

    if recipient_email:
        message = render_to_string(template_name, context)
        plain_message = strip_tags(message)

        mail = EmailMultiAlternatives(subject, plain_message, from_email, [recipient_email])
        mail.attach_alternative(message, "text/html")
        mail.send()
        # ==========================
        # WhatsApp Rejection Message
        # ==========================

        if status == 'rejected' and visitors_get_id.mobile:
            visitor_reject_whatsapp_notification(
                request=request,
                visitor_mobile=f"91{visitors_get_id.mobile}",
                visitor_name=f"{visitors_first_name} {visitors_last_name}",
                employee_name=f"{employee_first_name} {employee_last_name}",
                company_name=company_name
            )
        if status == 'accepted' and visitors_get_id.mobile:
            company_website = website_setting.objects.first()
            visitor_accepted_whatsapp_notification(
                request=request,
                visitor_mobile=f"91{visitors_get_id.mobile}",
                visitor_name=f"{visitors_first_name} {visitors_last_name}",
                employee_name=f"{employee_first_name} {employee_last_name}",
                company_name=company_name,
                qr_code=request.build_absolute_uri(f'/gate_keeper/qr_code_visitor_details/{signing.dumps(appointment_instance.id)}'),
                company_website=company_website.company_domain
            )
    messages.success(request, "Status updated and email sent successfully.")

def employee(request):

    context = {'function_name': 'Employee'}
    setting = website_setting.objects.first()
    context['setting'] = setting
    from_email = setting.from_email
    # 🔹 1. Call subscription API before login process
    url = f"{settings.SUBSCRIPTION_DOMAIN}{settings.SUBSCRIPTION_ENDPOINT}"
    payload = {"company_id": f"{settings.SUBSCRIPTION_PAYLOAD}"}
    headers = {
        "User-Agent": "Mozilla/5.0",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        api_response = requests.post(url, json=payload,headers=headers, timeout=5)
        response_data = api_response.json()
        # print("✅ Request successful!")
        # print("Response data:", response_data)

        if response_data.get("status") and "data" in response_data:
            sub_data = response_data["data"]
            sub_status = sub_data.get("sub_status", 0)  # 0 = expired/inactive, 1 = active
            expired_flag = response_data.get("expired", False)
            message_text = response_data.get("message", "")

            # ❌ Case 1: Subscription expired or inactive → block login
            if sub_status == 0 or expired_flag:
                messages.error(request, message_text or "Your subscription has expired!", extra_tags="danger")
                return render(request, "registration/login.html", context)

            # ⚠️ Case 2: Subscription active but expiring soon → show warning but allow login
            elif sub_status == 1 and not expired_flag:
                # days_left = response_data.get("daysLeft", 0)
                # if days_left <= 7:
                if message_text and message_text != "Your subscription is active!":
                    messages.warning(request, message_text, extra_tags="warning")

            # ✅ Case 3: Subscription active → no message, continue
            else:
                pass
        else:
            messages.error(request, "Unable to verify subscription.", extra_tags="danger")
            return render(request, "registration/login.html", context)

    except Exception as e:
        # messages.error(request, f"Error checking subscription: {str(e)}", extra_tags="danger")
        messages.error(request, f"Unable to check your subscription at the moment. Please try again later.", extra_tags="danger")
        return render(request, "registration/login.html", context)
    if request.method == 'POST':
        employee_code = request.POST.get('employee_code', '')
        password = request.POST.get('password', '')

        if not employee_code or not password:
            messages.error(request, 'All fields are required.')
            return render(request, 'registration/login.html', context)

        user_check = user.objects.filter(Q(type__icontains='employee'), employee_code=employee_code,
                                         is_active=True).first()
        if user_check:
            if check_password(password, user_check.password):
                user_name = user_check.first_name
                employee_data = {
                    'user_email': user_check.email,
                    'user_password': password,
                    'user_name': user_name,
                    'id': user_check.id
                }
                request.session['employee'] = employee_data
                encrypted_appointment_id = request.session.get('pending_appointment')
                pending_action = request.session.get('pending_action')  # Get pending action (accepted or rejected)

                if encrypted_appointment_id and pending_action:
                    try:
                        decrypted_appointment_id = signing.loads(encrypted_appointment_id)
                        update_appointment_status(decrypted_appointment_id, pending_action, user_check,from_email, request)

                        del request.session['pending_appointment']
                        del request.session['pending_action']  # Clear pending action after processing

                        messages.success(request, f"Appointment {pending_action} successfully after login.",extra_tags="success")
                        return redirect('employee_dashboard')

                    except signing.BadSignature:
                        messages.error(request, "Invalid appointment link, cannot save after login.",extra_tags='danger')
                        return redirect('employee_dashboard')
                return redirect('employee_dashboard')
            else:
                messages.error(request, 'Invalid Email or Password.',extra_tags='danger')

        else:
            messages.error(request, 'Invalid Login. No matching account found.',extra_tags='danger')

        return render(request, 'registration/login.html', context)

    return render(request, 'registration/login.html', context)


def employee_dashboard(request):


    constants = my_constants(request)

    username = request.session.get('employee')

    if not username:
        return redirect('employee')
    user_data = constants.get('employee_data', {})
    user_id = user_data.get('id')
    database_name = constants['database_name']

    today_date = date_time().split(' ')[0]
    total_visitors_date = f'20{today_date}'
    # Query for check-out details
    try:
        user_email = username.get('id')
        useres = user.objects.get(id=user_email)
        user_location = useres.location_id
        print('user_location:-',user_location)
    except user.DoesNotExist:
        user_location = None

    sql_query_check_out = f"""
        SELECT 
            appointment.*, 
            visitors.first_name AS visitors_name, 
            visitors.last_name AS visitors_last_name, 
            visitors.uni_id AS visitors_uni_id,
            visitors.image AS visitors_image,
            visitors.email AS visitors_email,
            visitors.mobile AS visitors_mobile,
            employees.first_name AS employee_name,
            employees.last_name AS employee_last_name,
            employees.uni_id AS employee_uni_id,
            appointment.check_in_time AS start_time,
            appointment.check_out_time AS stop_time,
            created_by.first_name AS created_by_first_name,
            created_by.last_name AS created_by_last_name
        FROM 
            {database_name}.appointment
        INNER JOIN 
            {database_name}.users AS visitors ON visitors.id = appointment.visitors_id
        INNER JOIN 
            {database_name}.users AS employees ON employees.id = appointment.employee_id
        LEFT JOIN 
            {database_name}.users AS created_by ON created_by.id = appointment.created_by
        WHERE
            date = %s AND check_out_time IS NOT NULL AND check_out_time != '' AND employee_id = %s AND visitors.location_id = %s
        ORDER BY 
            visitors.id DESC;
    """

    with connection.cursor() as cursor:
        cursor.execute(sql_query_check_out, [total_visitors_date, user_id] + [user_location])
        database_all_data = cursor.fetchall()
        columns = [col[0] for col in cursor.description]
        all_check_out_dtl = [dict(zip(columns, row)) for row in database_all_data]

    # Query for check-in details (corrected)
    sql_query_check_in = f"""
        SELECT 
            appointment.*, 
            visitors.first_name AS visitors_name, 
            visitors.last_name AS visitors_last_name, 
            visitors.uni_id AS visitors_uni_id,
            visitors.image AS visitors_image,
            visitors.email AS visitors_email,
            visitors.mobile AS visitors_mobile,
            employees.first_name AS employee_name,
            employees.last_name AS employee_last_name,
            employees.uni_id AS employee_uni_id,
            appointment.check_in_time AS start_time,
            appointment.check_out_time AS stop_time,
            created_by.first_name AS created_by_first_name,
            created_by.last_name AS created_by_last_name
        FROM 
            {database_name}.appointment
        INNER JOIN 
            {database_name}.users AS visitors ON visitors.id = appointment.visitors_id
        INNER JOIN 
            {database_name}.users AS employees ON employees.id = appointment.employee_id
        LEFT JOIN 
            {database_name}.users AS created_by ON created_by.id = appointment.created_by
        WHERE
            date = %s AND check_in_time IS NOT NULL AND check_in_time != '' AND check_out_time = '' AND employee_id = %s AND visitors.location_id = %s
        ORDER BY 
            visitors.id DESC;
    """
    with connection.cursor() as cursor:
        cursor.execute(sql_query_check_in, [total_visitors_date, user_id] + [user_location])
        database_all_data = cursor.fetchall()
        columns = [col[0] for col in cursor.description]
        all_check_in_dtl = [dict(zip(columns, row)) for row in database_all_data]

    sql_query_pending_list = f"""
       SELECT 
        appointment.*, 
        visitors.first_name AS visitors_name, 
        visitors.last_name AS visitors_last_name, 
        visitors.uni_id AS visitors_uni_id,
        visitors.image AS visitors_image,
        visitors.email AS visitors_email,
        visitors.mobile AS visitors_mobile,
        employees.first_name AS employee_name,
        employees.last_name AS employee_last_name,
        employees.uni_id AS employee_uni_id,
        appointment.check_in_time AS start_time,
        appointment.check_out_time AS stop_time,
        created_by.first_name AS created_by_first_name,
        created_by.last_name AS created_by_last_name
    FROM 
        {database_name}.appointment
    INNER JOIN 
        {database_name}.users AS visitors ON visitors.id = appointment.visitors_id
    INNER JOIN 
        {database_name}.users AS employees ON employees.id = appointment.employee_id
    LEFT JOIN 
        {database_name}.users AS created_by ON created_by.id = appointment.created_by
    WHERE
        date = %s AND check_in_time = '' AND check_out_time = '' AND employee_id = %s AND visitors.location_id = %s
    ORDER BY 
        visitors.id DESC;
"""
    with connection.cursor() as cursor:
        cursor.execute(sql_query_pending_list, [total_visitors_date, user_id] + [user_location])
        database_all_data = cursor.fetchall()
        columns = [col[0] for col in cursor.description]
        all_pending_list = [dict(zip(columns, row)) for row in database_all_data]

    # Count queries
    sql_query_check_in_count = f"""
        SELECT 
            COUNT(*) AS total_count
        FROM 
            {database_name}.appointment
        INNER JOIN 
            {database_name}.users AS visitors ON visitors.id = appointment.visitors_id
        INNER JOIN 
            {database_name}.users AS employees ON employees.id = appointment.employee_id
        LEFT JOIN 
            {database_name}.users AS created_by ON created_by.id = appointment.created_by

        WHERE date = %s AND check_in_time IS NOT NULL AND check_in_time != '' AND check_out_time = '' AND employee_id = %s AND visitors.location_id = %s; 
    """

    sql_query_check_out_count = f"""
       SELECT 
            COUNT(*) AS total_count
        FROM 
            {database_name}.appointment
        INNER JOIN 
            {database_name}.users AS visitors ON visitors.id = appointment.visitors_id
        INNER JOIN 
            {database_name}.users AS employees ON employees.id = appointment.employee_id
        LEFT JOIN 
            {database_name}.users AS created_by ON created_by.id = appointment.created_by
        WHERE date = %s AND check_out_time IS NOT NULL AND check_out_time != '' AND employee_id = %s AND visitors.location_id = %s;
    """

    sql_query_total_visitors = f"""
        SELECT 
            COUNT(*) AS total_count
        FROM 
            {database_name}.appointment
        INNER JOIN 
            {database_name}.users AS visitors ON visitors.id = appointment.visitors_id
        INNER JOIN 
            {database_name}.users AS employees ON employees.id = appointment.employee_id
        LEFT JOIN 
            {database_name}.users AS created_by ON created_by.id = appointment.created_by
        WHERE date = %s AND employee_id = %s AND visitors.location_id = %s;
    """

    # sql_query_pending = f"""
    #     SELECT COUNT(*) FROM {database_name}.appointment
    #     WHERE date = %s AND check_in_time = '' AND check_out_time = '';
    # """

    sql_query_pending = f"""
        SELECT 
            COUNT(*) AS total_count
        FROM 
            {database_name}.appointment
        INNER JOIN 
            {database_name}.users AS visitors ON visitors.id = appointment.visitors_id
        INNER JOIN 
            {database_name}.users AS employees ON employees.id = appointment.employee_id
        LEFT JOIN 
            {database_name}.users AS created_by ON created_by.id = appointment.created_by
        WHERE
            date = %s AND check_in_time = '' AND check_out_time = '' AND employee_id = %s AND visitors.location_id = %s;

    """

    with connection.cursor() as cursor:
        cursor.execute(sql_query_check_in_count, [total_visitors_date, user_id] + [user_location])
        check_in_data = cursor.fetchone()
        check_in_count = check_in_data[0] if check_in_data else 0

        cursor.execute(sql_query_check_out_count, [total_visitors_date, user_id] + [user_location])
        check_out_data = cursor.fetchone()
        check_out_count = check_out_data[0] if check_out_data else 0

        cursor.execute(sql_query_total_visitors, [total_visitors_date, user_id] + [user_location])
        total_visitors_data = cursor.fetchone()
        total_visitors_count = total_visitors_data[0] if total_visitors_data else 0

        cursor.execute(sql_query_pending, [total_visitors_date, user_id] + [user_location])
        pending_data = cursor.fetchone()
        pending_count = pending_data[0] if pending_data else 0

    context = {
        'username': username,
        'DOMAIN_NAME': constants['DOMAIN_NAME'],
        'DOMAIN_ICON': constants['DOMAIN_ICON'],
        'employee_data': constants['employee_data'],
        'check_in_count': check_in_count,
        'check_out_count': check_out_count,
        'total_visitors_count': total_visitors_count,
        'pending_count': pending_count,
        'all_check_out_dtl': all_check_out_dtl,
        'all_check_in_dtl': all_check_in_dtl,
        'all_pending_list': all_pending_list,
        'function_name': 'Employee'
    }

    return render(request, 'dashboard/employee_dashboard/dashboard.html', context)



def employee_logout(request):
    if request.session.get('employee'):
        del request.session['employee']
    return redirect('employee')



def employee_visitore_all_page(request):
    constants = my_constants(request)
    username = request.session.get('employee')
    if not username:
        return redirect('employee')

    return render(request, 'dashboard/employee_dashboard/employee_visitor/employee_visitore_all_page.html', {
        'username': username,
        'user_data': constants['employee_data'],
        'function_name': 'Employee'})


def employee_visitore_ajax_page_ajax(request):
    constants = my_constants(request)
    username = request.session.get('employee')
    if not username:
        return redirect('employee')

    try:
        user_email = username.get('id')
        useres = user.objects.get(id=user_email)
        user_location = useres.location_id
    except user.DoesNotExist:
        user_location = None
    user_data = constants.get('employee_data', {})
    user_id = user_data.get('id')
    start = int(request.POST.get('start', 0))
    length = int(request.POST.get('length', 10))
    search_value = request.POST.get('search[value]', '')

    search = ''
    search_args = []
    if search_value:
        search = '''
            AND (
                u.first_name LIKE %s OR 
                u.email LIKE %s OR 
                a.id LIKE %s OR 
                a.date LIKE %s OR 
                a.time LIKE %s OR 
                a.purpose LIKE %s
            )
        '''
        search_args = [f'%{search_value}%'] * 6

    # First SQL query to get the count of appointments
    sql_query_count = f"""
        SELECT
            COUNT(*)
        FROM
            {database_name}.appointment AS a
        INNER JOIN
            {database_name}.users AS u
        ON
            u.id = a.visitors_id
        WHERE
            a.employee_id = %s
            AND a.status = 'pending' AND u.location_id = %s
            {search}
    """
    with connection.cursor() as cursor:
        cursor.execute(sql_query_count, [user_id] + [user_location] + search_args)
        database_all_data = cursor.fetchall()
    recordsTotal = database_all_data[0][0] if database_all_data else 0

    # Second SQL query to get detailed appointment data
    sql_query_data = f"""
        SELECT 
            a.*, 
            u.first_name AS visitors_first_name,
            u.email AS visitors_email,
            u.mobile AS visitors_mobile,
            u.image AS visitors_image
        FROM 
            {database_name}.appointment AS a
        INNER JOIN 
            {database_name}.users AS u
        ON 
            u.id = a.visitors_id
        WHERE 
            a.employee_id = %s
            AND a.status = 'pending' AND u.location_id = %s
            {search}
        ORDER BY
            a.id DESC
        LIMIT %s OFFSET %s
    """

    args_data = [user_id] + [user_location] + search_args + [length, start]

    with connection.cursor() as cursor:
        cursor.execute(sql_query_data, args_data)
        database_all_data = cursor.fetchall()
        columns = [col[0] for col in cursor.description]
        all_coupon_dtl = [dict(zip(columns, row)) for row in database_all_data]

    return JsonResponse({"recordsTotal": recordsTotal, "recordsFiltered": recordsTotal, 'data': all_coupon_dtl})


def employee_user(request):
    constants = my_constants(request)
    username = request.session.get('employee')
    if not username:
        return redirect('employee')

    employee_data = constants.get('employee_data', {})
    employee_id = employee_data.get('id')

    return render(request, 'dashboard/employee_dashboard/employee_user/employee_user.html', {'username': username,'function_name': 'Employee'})


def employee_page_ajax(request):
    constants = my_constants(request)
    database_name = constants['database_name']
    username = request.session.get('employee')
    if not username:
        return redirect('employee')

    user_data = constants.get('employee_data', {})
    user_id = user_data.get('id')
    try:
        user_email = username.get('id')
        useres = user.objects.get(id=user_email)
        user_location = useres.location_id
    except user.DoesNotExist:
        user_location = None
    start = int(request.POST.get('start', 0))
    length = int(request.POST.get('length', 10))
    search_value = request.POST.get('search[value]', '')

    search = ''
    if search_value:
        search = (
            "AND (users.email LIKE %s OR "
            "users.mobile LIKE %s OR "
            "users.created_at LIKE %s OR "
            "users.updated_at LIKE %s OR "
            "users.first_name LIKE %s OR "
            "users.last_name LIKE %s OR "
            "users.uni_id LIKE %s)"
        )
        search_params = ['%' + search_value + '%'] * 7
    else:
        search_params = []

    # First SQL query to get the count of appointments
    sql_query = f"""
       SELECT
            COUNT(*) AS users
        FROM
            {database_name}.users AS users
        LEFT  JOIN  
            {database_name}.users AS created_by ON created_by.id = users.created_by
        WHERE
            users.type = 'visitors' AND users.location_id = %s
            {search}
    """
    with connection.cursor() as cursor:
        cursor.execute(sql_query, [user_location] + search_params)
        database_all_data = cursor.fetchall()

    recordsTotal = database_all_data[0][0] if database_all_data else 0

    # Second SQL query to get detailed appointment data
    sql_query = f"""
       SELECT 
            users.*, 
            created_by.first_name AS created_by_first_name,
            created_by.last_name AS created_by_last_name 
        FROM 
            {database_name}.users
        LEFT JOIN  
            {database_name}.users AS created_by ON created_by.id = users.created_by
        WHERE
            users.type = 'visitors' AND users.location_id = %s
            {search}
        ORDER BY 
            users.id DESC
        LIMIT %s OFFSET %s;
    """

    with connection.cursor() as cursor:
        cursor.execute(sql_query, [user_location] + search_params + [length, start])
        database_all_data = cursor.fetchall()
        columns = [col[0] for col in cursor.description]
        all_coupon_dtl = [dict(zip(columns, row)) for row in database_all_data]

    return JsonResponse({"recordsTotal": recordsTotal, "recordsFiltered": recordsTotal, 'data': all_coupon_dtl})


def employee_new_appointment(request, id):
    constants = my_constants(request)

    username = request.session.get('employee')

    if not username:
        return redirect('employee')

    # Fetch the appointment based on id

    all_user = get_object_or_404(user, id=id)

    user_id_get = int(id)
    all_appointmentes = appointment.objects.filter(visitors_id=user_id_get).order_by('-id').first()

    all_employee = user.objects.filter(type='employee', is_active=1)

    user_data = constants.get('employee_data', {})

    user_id = user_data.get('id')

    user_data_gate = user.objects.get(id=user_id)

    user_first_name = user_data.get('first_name')

    employee_code = user_data.get('employee_code')

    user_last_name = user_data.get('last_name')

    from_email = constants['From_Email']
    try:
        user_data_gate = user.objects.get(id=user_id)
        employee_companyes = user_data_gate.company_id
    except user.DoesNotExist:
        employee_companyes= None

    email_add_for_companye = company.objects.filter(id=employee_companyes).first()
    website_settings = website_setting.objects.first()
    is_id_card_required = website_settings.is_id_card_required
    if request.method == "POST":

        visitors_id = user_id

        employee_id = request.POST['employee']

        date = request.POST['date']

        time = request.POST['time']

        purpose = request.POST['Purpose']

        visitors_type = request.POST['visitors_type']
        visitor_company_name = request.POST.get('visitor_company_name', '').strip()

        detail = request.POST['detail']

        visitors_timing = request.POST['visitors_timing']

        device = request.POST['devices']
        vehicle_number =  request.POST['vehicle_number']
        id_card = request.POST['base_id_card']
        if employee_id == '' or employee_id == 'Choose employee' or date == '' or time == '' or purpose == '' or visitors_type == 'Choose visitors type' or visitors_type == '':
            messages.error(request, "All fields are required.", extra_tags="danger")

            return render(request, 'dashboard/employee_dashboard/employee_user/employee_user_appointment_add.html',
                          {'username': username, 'all_employee': all_employee, 'user_first_name': user_first_name,
                           'user_last_name': user_last_name, 'user_id': user_id, 'all_user': all_user,
                           'employee_code': employee_code, 'function_name': 'Employee','is_id_card_required':is_id_card_required})

        try:
            id_cards_filename = ''
            if id_card:

                if 'id_cards/' in id_card:
                    id_cards_filename = os.path.basename(id_card)
                else:
                    try:
                        if ',' in id_card:
                            base64_data = id_card.split(',')[1]
                        else:
                            raise ValueError("Invalid ID card format")

                        binary_data = base64.b64decode(base64_data)

                        img = Image.open(io.BytesIO(binary_data))

                        if img.mode in ('RGBA', 'LA'):
                            background = Image.new('RGB', img.size, (255, 255, 255))
                            background.paste(img, mask=img.split()[3])
                            img = background
                        else:
                            img = img.convert('RGB')

                        save_directory = os.path.join(settings.MEDIA_ROOT, 'id_cards')
                        os.makedirs(save_directory, exist_ok=True)

                        unique_name = generate_vms_string().replace('VMS', '')
                        clean_name = all_user.first_name.strip().replace(' ', '_')

                        id_cards_filename = f"idcard_{clean_name}_{unique_name}.jpg"
                        id_card_path = os.path.join(save_directory, id_cards_filename)

                        img.save(id_card_path, 'JPEG', quality=95)

                    except Exception as e:
                        messages.error(
                            request,
                            f"Error processing ID Card: {str(e)}",
                            extra_tags='danger'
                        )
                        return redirect('employee_user')
            appointment_obj = appointment.objects.create(

                visitors_id=id,

                employee_id=employee_id,

                date=date,

                time=time,

                status='pending',  # Assuming 'scheduled' is the default status

                created_at=date_time(),

                purpose=purpose,

                visitors_type=visitors_type,

                detail=detail,

                created_by=user_id,

                visitors_timing=visitors_timing,

                employee_approval=None,
                visitor_company_name=visitor_company_name,
                devices = device,
                # access_card_id=employees_API
                request_id = generate_unique_request_id(),
                vehicle_number=vehicle_number,
                id_card=id_cards_filename,

            )
            all_user.id_card = id_cards_filename
            all_user.save(update_fields=['id_card'])
            # appointment_obj.request_id = f"{datetime.now().strftime('VMS%d%m%Y%H%M')}{appointment_obj.id}"
            # appointment_obj.save(update_fields=['request_id'])
            # appointment_obj.save()

            visitor = user.objects.filter(id=id).first()

            employee = user.objects.filter(id=employee_id).first()

            encrypted_appointment_id = signing.dumps(appointment_obj.id)

            base_url = request.build_absolute_uri('/')[:-1]

            if employee != '':

                try:
                    company_name = email_add_for_companye.company_name
                    visitor_name = f"{visitor.first_name} {visitor.last_name}"
                    purpose = appointment_obj.purpose
                    person_name = f"{employee.first_name} {employee.last_name}"
                    person_departments = department.objects.filter(id=employee.department_id).first()
                    person_departments = person_departments.department_name
                    # visit_schedule = f"{appointment_obj.date} {appointment_obj.time}"
                    new_appointment_created_at = appointment_obj.created_at
                    dt = datetime.strptime(new_appointment_created_at, "%y-%m-%d %H:%M:%S")
                    check_in_date = dt.strftime("%d-%m-%Y")
                    check_in_time = dt.strftime("%H:%M:%S")
                    visit_schedule = f"{check_in_date} {check_in_time}"
                    appointment_id = appointment_obj.id
                    encrypted_appointment_id = signing.dumps(appointment_id)
                    base_url = request.build_absolute_uri('/')[:-1]
                    subject_employee = f'New Visitor Request – Approval Required | {company_name}'
                    context_employee = {
                        'company_name': company_name,
                        'visitor_name': visitor_name,
                        'purpose': purpose,
                        'person_name': person_name,
                        'person_departments': person_departments,
                        'visit_schedule': visit_schedule,
                        'accept_url': f"{base_url}/accept/{encrypted_appointment_id}",
                        'reject_url': f"{base_url}/reject/{encrypted_appointment_id}",
                        'request_id':appointment_obj.request_id,
                        'vehicle_number': appointment_obj.vehicle_number,
                        # 'visitor_photo': f"{base_url}/user/{all_user.image}"
                        'visitor_photo': 'cid:visitor_image' if (all_user.image and all_user.image.name) else '',
                        'other_guests_detail': detail
                    }

                    template_name_employee = 'dashboard/email_templates/email_to_concerned_person_(approval_required).html'
                    message_employee = render_to_string(template_name_employee, context_employee)

                    plain_message_employee = strip_tags(message_employee)

                    recipient_list_employee = [employee]

                    mail_employee = EmailMultiAlternatives(subject_employee, plain_message_employee, from_email,
                                                           recipient_list_employee)

                    mail_employee.attach_alternative(message_employee, "text/html")

                    if all_user.image:
                        image_filename = os.path.basename(all_user.image.name)
                        image_path = os.path.join(settings.MEDIA_ROOT, 'user', image_filename)

                        with open(image_path, "rb") as img:
                            mime_img = MIMEImage(img.read())
                            mime_img.add_header('Content-ID', '<visitor_image>')
                            mime_img.add_header('Content-Disposition', 'inline', filename="user.png")
                            mail_employee.attach(mime_img)
                    mail_employee.send()

                except Exception as e:
                    messages.error(request, f"Error: {e}", extra_tags="danger")

            try:

                if employee.mobile != '' or visitor.mobile != '':

                    visitor_name = f"{visitor.first_name} {visitor.last_name}"

                    if visitor_name == '':

                        visitor_name = '(visitor name)'

                    else:

                        visitor_name = visitor_name

                    visitor_mobile = visitor.mobile

                    if visitor_mobile == '':

                        visitor_mobile = '(visitor Mobile)'

                    else:

                        visitor_mobile = visitor_mobile

                    invitation_link = f"{base_url}/register/{encrypted_appointment_id}"
                    employee_mobile = employee.mobile

                    employee_name = f"{employee.first_name} {employee.last_name}"

                    visitor_name = visitor_name

                    visitor_image = f"{base_url}/user/{visitor.image}"

                    accept_url = f"{base_url}/accept/{encrypted_appointment_id}"

                    reject_url = f"{base_url}/reject/{encrypted_appointment_id}"

                    purpose_of_visit = appointment_obj.purpose

                    company_id = user_data_gate.company_id

                    check_company = company.objects.get(id=company_id)

                    company_name = check_company.company_name

                    location_id = user_data_gate.location_id

                    check_location = location.objects.get(id=location_id)

                    company_location = check_location.location_name

                    if visitor_company_name.lower() in ['', 'null', 'none']:
                        visitor_company_name = 'N/A'

                    new_appointment_created_at = appointment_obj.created_at
                    dt = datetime.strptime(new_appointment_created_at, "%y-%m-%d %H:%M:%S")
                    check_in_date = dt.strftime("%d-%m-%Y")
                    check_in_time = dt.strftime("%H:%M:%S")
                    request_id = appointment_obj.request_id
                    qr_code = request.build_absolute_uri(f'/gate_keeper/qr_code_visitor_details/{signing.dumps(appointment_obj.id)}'),
                    is_new_visitor = False
                    website_settings = website_setting.objects.first()

                    if website_settings.whatsapp_notification == 1:
                        company_website = website_settings.company_domain

                        whatsapps_send_notifications(request, employee_mobile, employee_name, visitor_name, accept_url,
                                                     reject_url, purpose_of_visit, company_name, company_location,
                                                     check_in_date, check_in_time, company_website, visitor_mobile,
                                                     invitation_link,visitor_image,request_id,qr_code[0],visitor_company_name,is_new_visitor)
            except requests.exceptions.RequestException as e:

                messages.error(request, f"Error: {e}", extra_tags="danger")

                pass

            if visitor.email != '' and visitor.email != None:

                try:
                    company_name = email_add_for_companye.company_name
                    visitor_name = f"{visitor.first_name} {visitor.last_name}"
                    person_name = f"{employee.first_name} {employee.last_name}"
                    person_departments = department.objects.filter(id=employee.department_id).first()
                    person_departments = person_departments.department_name
                    subject_visitor = f'Visitor Request Received – {company_name}'
                    context_visitor = {
                        'company_name': company_name,
                        'visitor_name': visitor_name,
                        'person_name': person_name,
                        'person_departments': person_departments,
                        'request_id':appointment_obj.request_id

                    }
                    template_name_visitor = 'dashboard/email_templates/visitor_request_submitted.html'

                    message_visitor = render_to_string(template_name_visitor, context_visitor)

                    plain_message_visitor = strip_tags(message_visitor)

                    recipient_list_visitor = [visitor.email]

                    mail_visitor = EmailMultiAlternatives(subject_visitor, plain_message_visitor, from_email,
                                                          recipient_list_visitor)

                    mail_visitor.attach_alternative(message_visitor, "text/html")

                    mail_visitor.send()

                    messages.success(request, "Appointment successfully created.", extra_tags="success")

                    return redirect('employee_user')

                except requests.RequestException as e:

                    print(f"API request error: {e}")

                    messages.error(request, f"API request error: {e}", extra_tags="danger")

                    return redirect('employee_user')

            else:

                messages.success(request, "Appointment successfully created.", extra_tags="success")

                return redirect('employee_user')

            messages.success(request, "Appointment successfully created.", extra_tags="success")

            return redirect('employee_user')

        except Exception as e:

            messages.error(request, f"An error occurred: {e}", extra_tags="danger")

    return render(request, 'dashboard/employee_dashboard/employee_user/employee_user_appointment_add.html',
                  {'username': username, 'all_employee': all_employee, 'user_first_name': user_first_name,
                   'user_last_name': user_last_name, 'user_id': user_id, 'all_user': all_user,
                   'employee_code': employee_code, 'all_appointmentes': all_appointmentes, 'function_name': 'Employee','is_id_card_required':is_id_card_required})


def employee_visitore_send_invitations(request):
    constants = my_constants(request)

    username = request.session.get('employee')
    if not username:
        return redirect('employee')
    user_data = constants.get('employee_data', {})
    user_id = user_data.get('id')
    user_data_gate = user.objects.get(id=user_id)
    from_email = constants['From_Email']
    try:
        user_data_gate = user.objects.get(id=user_id)
        gatekeeper_location = user_data_gate.location_id  # Get gatekeeper's location
        gatekeeper_companyes = user_data_gate.company_id
    except user.DoesNotExist:
        gatekeeper_location = None
        gatekeeper_companyes = None

    email_add_for_companye = company.objects.filter(id=gatekeeper_companyes).first()
    all_employee = user.objects.filter(id=user_id, is_active=1)
    locationes = location.objects.filter(status=1, id=gatekeeper_location)
    companyes = company.objects.filter(status=1)
    departmentes = department.objects.filter(location_id=gatekeeper_location)
    role = roles.objects.filter(name='Visitors')
    website_settings = website_setting.objects.first()
    is_id_card_required = website_settings.is_id_card_required

    select_employee = user_data_gate.id
    select_locationes = user_data_gate.location_id
    select_companyes = user_data_gate.company_id
    select_departmentes = user_data_gate.department_id

    if request.method == "POST":

        user_ides = request.POST['user_id']

        if user_ides:
            user_ides_chane = int(user_ides)
            visitor_user = user.objects.filter(id=user_ides_chane).first()
            all_users = user.objects.get(id=user_ides_chane)

        employee_id = request.POST['employee_id']
        date = request.POST['date']
        time = request.POST['time']
        purpose = request.POST['Purpose']
        visitors_type = request.POST['visitors_type']
        detail = request.POST['detail']
        firstname = request.POST['Firstname']
        lastname = request.POST['Lastname']
        email = request.POST['Email']
        visitor_company_name = request.POST['visitor_company_name']
        address = request.POST['Address']
        mobile = request.POST['mobile']
        gender = request.POST['gender']
        company_id = request.POST['company_id']
        department_id = request.POST['department_id']
        status = request.POST['status']
        image = request.POST['user_image']
        id_card = request.POST['base_id_card']
        location_id = request.POST['location_id']
        visitors_timing = request.POST['visitors_timing']
        device = request.POST['devices']
        vehicle_number =  request.POST['vehicle_number']
        if user_ides in '':
            if email != '':
                if user.objects.filter(email=email).exists():
                    messages.error(request, 'User Email already exists.', extra_tags='danger')
                    return redirect('employee_visitore_send_invitations')
            else:
                email = None
        else:
            email = email
            pass

        if 'user' in image:
            filename = image
        else:
            if image != '':
                try:
                    base64_data = image.split(",")[1]
                    binary_data = base64.b64decode(base64_data)
                    image = Image.open(io.BytesIO(binary_data))

                    # Convert RGBA to RGB before saving as JPEG
                    if image.mode in ('RGBA', 'LA') or (image.mode == 'P' and 'transparency' in image.info):
                        # Create a new white background image
                        background = Image.new('RGB', image.size, (255, 255, 255))
                        # Paste the image on the background if it has alpha
                        if image.mode == 'RGBA':
                            background.paste(image, mask=image.split()[3])
                        else:
                            background.paste(image)
                        image = background
                    elif image.mode != 'RGB':
                        image = image.convert('RGB')

                    save_directory = 'user/'
                    if not os.path.exists(save_directory):
                        os.makedirs(save_directory)
                    filename = firstname.replace(' ', '_')
                    file_date = generate_vms_string()
                    new_file_name = file_date.replace('VMS', '')
                    filename = f"{filename}_{new_file_name}.jpg"

                    face_image_path = os.path.join(save_directory, filename)
                    image.save(face_image_path, 'JPEG', quality=95)
                except Exception as e:
                    messages.error(request, f"Error processing image: {str(e)}", extra_tags='danger')
                    return redirect('employee_visitore_send_invitations')
            else:
                filename = ''

        id_cards_filename = ''
        if id_card:
            if 'id_cards/' in id_card:
                id_cards_filename = os.path.basename(id_card)
            else:
                try:
                    if ',' in id_card:
                        base64_data = id_card.split(',')[1]
                    else:
                        raise ValueError("Invalid ID card format")

                    binary_data = base64.b64decode(base64_data)

                    img = Image.open(io.BytesIO(binary_data))

                    if img.mode in ('RGBA', 'LA'):
                        background = Image.new('RGB', img.size, (255, 255, 255))
                        background.paste(img, mask=img.split()[3])
                        img = background
                    else:
                        img = img.convert('RGB')

                    save_directory = os.path.join(settings.MEDIA_ROOT, 'id_cards')
                    os.makedirs(save_directory, exist_ok=True)

                    unique_name = generate_vms_string().replace('VMS', '')
                    clean_name = firstname.strip().replace(' ', '_')

                    id_cards_filename = f"idcard_{clean_name}_{unique_name}.jpg"

                    id_card_path = os.path.join(save_directory, id_cards_filename)

                    img.save(id_card_path, 'JPEG', quality=95)

                except Exception as e:
                    messages.error(
                        request,
                        f"Error processing ID Card: {str(e)}",
                        extra_tags='danger'
                    )
                    return redirect('employee_visitore_send_invitations')
        created_at = date_time()
        updated_at = date_time()

        if employee_id == '' or employee_id == 'Choose employee' or date == '' or time == '' or purpose == '' or company_id == '' or company_id == '-- Select Company  --' or department_id == '' or department_id == '-- Select Department --' or location_id == '' or location_id == '-- Select Location --' or status == '' or mobile == '':
            messages.error(request, "All fields are required.", extra_tags="danger")
            return render(request, 'dashboard/employee_dashboard/employee_visitor/employee__visitor_add.html', {
                'username': username, 'all_employee': all_employee, 'locationes': locationes, 'companyes': companyes,
                'departmentes': departmentes, 'roles': role,'function_name': 'Employee','select_locationes':select_locationes,'select_companyes':select_companyes,'select_departmentes':select_departmentes,'select_employee':select_employee,'is_id_card_required':is_id_card_required
            })
        try:
            if user_ides == '':
                is_new_visitor = True
                new_user = user.objects.create(
                    first_name=firstname,
                    last_name=lastname,
                    email=email,
                    password='',
                    address=address,
                    mobile=mobile,
                    gender=gender,
                    image=filename,
                    id_card =id_cards_filename,
                    type='visitors',
                    company_id=company_id,
                    department_id=department_id,
                    location_id=location_id,
                    is_active=status,
                    created_at=created_at,
                    uni_id=generate_vms_string(),
                    created_by=user_id,
                    employee_code=0,
                    designation_id=0

                )

                new_user.save()
                new_user.save()
                if visitors_type == '':
                    visitors_type = 'other'

                new_appointment = appointment.objects.create(
                    employee_id=employee_id,
                    date=date,
                    time=time,
                    status='pending',
                    purpose=purpose,
                    visitors_type=visitors_type,
                    detail=detail,
                    visitors_id=new_user.id,
                    created_at=date_time(),
                    created_by=user_id,
                    visitors_timing=visitors_timing,
                    employee_approval=None,
                    visitor_company_name=visitor_company_name,
                    devices = device,
                    request_id=generate_unique_request_id(),
                    vehicle_number =vehicle_number,
                    id_card=id_cards_filename,

                )
                # new_appointment.request_id = f"{datetime.now().strftime('VMS%d%m%Y%H%M')}{new_appointment.id}"
                # new_appointment.save(update_fields=['request_id'])
                # new_appointment.save()
                employee_email = user.objects.filter(id=employee_id).first()

                if employee_email != '':
                    try:
                        new_appointment_created_at = new_appointment.created_at
                        dt = datetime.strptime(new_appointment_created_at, "%y-%m-%d %H:%M:%S")
                        check_in_date = dt.strftime("%d-%m-%Y")
                        check_in_time = dt.strftime("%H:%M:%S")
                        company_name = email_add_for_companye.company_name
                        visitor_name = f"{new_user.first_name} {new_user.last_name}"
                        purpose = new_appointment.purpose
                        person_name = f"{employee_email.first_name} {employee_email.last_name}"
                        person_departments = department.objects.filter(id=employee_email.department_id).first()
                        person_departments = person_departments.department_name
                        visit_schedule = f"{check_in_date} {check_in_time}"
                        appointment_id = new_appointment.id
                        encrypted_appointment_id = signing.dumps(appointment_id)
                        base_url = request.build_absolute_uri('/')[:-1]
                        subject_employee = f'New Visitor Request – Approval Required | {company_name}'
                        context_employee = {
                            'company_name': company_name,
                            'visitor_name': visitor_name,
                            'purpose': purpose,
                            'person_name': person_name,
                            'person_departments': person_departments,
                            'visit_schedule': visit_schedule,
                            'request_id':new_appointment.request_id,
                            'accept_url': f"{base_url}/accept/{encrypted_appointment_id}",
                            'reject_url': f"{base_url}/reject/{encrypted_appointment_id}",
                            'vehicle_number':new_appointment.vehicle_number,
                            'visitor_photo': 'cid:visitor_image' if (new_user.image) else '',
                            'other_guests_detail': detail
                        }
                        template_name_employee = 'dashboard/email_templates/email_to_concerned_person_(approval_required).html'
                        message_employee = render_to_string(template_name_employee, context_employee)
                        plain_message_employee = strip_tags(message_employee)
                        recipient_list_employee = [employee_email]

                        mail_employee = EmailMultiAlternatives(subject_employee, plain_message_employee, from_email,
                                                               recipient_list_employee)
                        mail_employee.attach_alternative(message_employee, "text/html")

                        if new_user.image:
                            image_filename = os.path.basename(new_user.image.name)
                            image_path = os.path.join(settings.MEDIA_ROOT, 'user', image_filename)

                            with open(image_path, "rb") as img:
                                mime_img = MIMEImage(img.read())
                                mime_img.add_header('Content-ID', '<visitor_image>')
                                mime_img.add_header('Content-Disposition', 'inline', filename="user.png")
                                mail_employee.attach(mime_img)
                        mail_employee.send()
                    except Exception as e:
                        messages.error(request, f"Error: {e}", extra_tags="danger")
                try:
                    if employee_email.mobile != '' or new_user.mobile != '':
                        # visitor_name = new_user.first_name
                        visitor_name = f"{new_user.first_name} {new_user.last_name}".strip()
                        if visitor_name == '':
                            visitor_name = '(visitor name)'
                        else:
                            visitor_name = visitor_name

                        visitor_mobile = new_user.mobile
                        if visitor_mobile == '':
                            visitor_mobile = None
                        else:
                            visitor_mobile = visitor_mobile

                        visitor_image = f"{base_url}/user/{new_user.image}"
                        invitation_link = f"{base_url}/register/{encrypted_appointment_id}"
                        employee_mobile = employee_email.mobile
                        employee_name = f"{employee_email.first_name} {employee_email.last_name}"
                        visitor_name = visitor_name if visitor_name else 'Default Visitor Name'
                        accept_url = f"{base_url}/accept/{encrypted_appointment_id}"
                        reject_url = f"{base_url}/reject/{encrypted_appointment_id}"
                        purpose_of_visit = new_appointment.purpose

                        company_id = user_data_gate.company_id
                        check_company = company.objects.get(id=company_id)
                        company_name = check_company.company_name

                        location_id = user_data_gate.location_id
                        check_location = location.objects.get(id=location_id)
                        company_location = check_location.location_name

                        new_appointment_created_at = new_appointment.created_at
                        dt = datetime.strptime(new_appointment_created_at, "%y-%m-%d %H:%M:%S")
                        check_in_date = dt.strftime("%d-%m-%Y")
                        check_in_time = dt.strftime("%H:%M:%S")
                        # check_in_date = datetime.today().strftime("%d-%m-%Y")
                        # check_in_time = datetime.now().strftime("%H:%M")
                        request_id = new_appointment.request_id
                        visitor_company_name = new_appointment.visitor_company_name
                        if visitor_company_name in [None, '', 'NULL', 'null']:
                            visitor_company_name = 'N/A'
                        qr_code = request.build_absolute_uri(f'/gate_keeper/qr_code_visitor_details/{signing.dumps(new_appointment.id)}'),
                        website_settings = website_setting.objects.first()
                        if website_settings.whatsapp_notification == 1:
                            company_website = website_settings.company_domain
                            whatsapps_send_notifications(request, employee_mobile, employee_name, visitor_name,
                                                         accept_url, reject_url, purpose_of_visit, company_name,
                                                         company_location, check_in_date, check_in_time,
                                                         company_website, visitor_mobile, invitation_link,visitor_image,request_id,qr_code[0],visitor_company_name,is_new_visitor)

                except requests.exceptions.RequestException as e:
                    messages.error(request, f"Error: {e}", extra_tags="danger")
                if email != '' and email != None:
                    try:

                        company_name = email_add_for_companye.company_name
                        visitor_name = f"{new_user.first_name} {new_user.last_name}"
                        person_name = f"{employee_email.first_name} {employee_email.last_name}"
                        person_departments = department.objects.filter(id=employee_email.department_id).first()
                        person_departments = person_departments.department_name
                        subject_visitor = f'Visitor Request Received – {company_name}'
                        context_visitor = {
                            'company_name': company_name,
                            'visitor_name': visitor_name,
                            'person_name': person_name,
                            'person_departments': person_departments,
                            'request_id': new_appointment.request_id

                        }
                        template_name_visitor = 'dashboard/email_templates/visitor_request_submitted.html'
                        message_visitor = render_to_string(template_name_visitor, context_visitor)
                        plain_message_visitor = strip_tags(message_visitor)
                        recipient_list_visitor = [email]

                        mail_visitor = EmailMultiAlternatives(subject_visitor, plain_message_visitor, from_email,
                                                              recipient_list_visitor)
                        mail_visitor.attach_alternative(message_visitor, "text/html")

                        mail_visitor.send()

                        messages.success(request, "Appointment successfully created.", extra_tags="success")
                        return redirect('employee_visitore_send_invitations')
                    except requests.RequestException as e:
                        print(f"API request error: {e}")
                        messages.error(request, f"API request error: {e}", extra_tags="danger")
                        return redirect('employee_visitore_send_invitations')
                else:
                    messages.success(request, "Appointment successfully created.", extra_tags="success")
                    return redirect('employee_visitore_send_invitations')
            else:
                if email == '':
                    email = None
                is_new_visitor = False
                all_users.first_name = firstname
                all_users.last_name = lastname
                all_users.email = email
                all_users.address = address
                all_users.mobile = mobile
                all_users.gender = gender
                all_users.image = filename
                all_users.id_card = id_cards_filename
                all_users.type = 'visitors'
                all_users.company_id = company_id
                all_users.department_id = department_id
                all_users.location_id = location_id
                all_users.is_active = status
                all_users.created_at = created_at
                # all_users.uni_id = generate_vms_string()
                all_users.created_by = user_id
                all_users.employee_code = 0
                all_users.designation_id = 0
                all_users.save()

                new_appointment = appointment.objects.create(
                    employee_id=employee_id,
                    date=date,
                    time=time,
                    status='pending',
                    purpose=purpose,
                    visitors_type=visitors_type,
                    detail=detail,
                    visitors_id=user_ides,
                    created_at=date_time(),
                    created_by=user_id,
                    visitors_timing=visitors_timing,
                    employee_approval=None,
                    visitor_company_name=visitor_company_name,
                    devices=device,
                    request_id=generate_unique_request_id(),
                    vehicle_number=vehicle_number,
                    id_card=id_cards_filename,

                )
                # new_appointment.request_id = f"{datetime.now().strftime('VMS%d%m%Y%H%M')}{new_appointment.id}"
                # new_appointment.save(update_fields=['request_id'])
                # new_appointment.save()
                employee_email = user.objects.filter(id=employee_id).first()

                if employee_email != '':
                    try:
                        company_name = email_add_for_companye.company_name
                        visitor_name = f"{all_users.first_name} {all_users.last_name}"
                        purpose = new_appointment.purpose
                        person_name = f"{employee_email.first_name} {employee_email.last_name}"
                        person_departments = department.objects.filter(id=employee_email.department_id).first()
                        person_departments = person_departments.department_name
                        # visit_schedule = f"{new_appointment.date} {new_appointment.time}"
                        new_appointment_created_at = new_appointment.created_at
                        dt = datetime.strptime(new_appointment_created_at, "%y-%m-%d %H:%M:%S")
                        check_in_date = dt.strftime("%d-%m-%Y")
                        check_in_time = dt.strftime("%H:%M:%S")
                        visit_schedule = f"{check_in_date} {check_in_time}"
                        appointment_id = new_appointment.id
                        encrypted_appointment_id = signing.dumps(appointment_id)
                        base_url = request.build_absolute_uri('/')[:-1]
                        subject_employee = f'New Visitor Request – Approval Required | {company_name}'
                        context_employee = {
                            'company_name': company_name,
                            'visitor_name': visitor_name,
                            'purpose': purpose,
                            'person_name': person_name,
                            'person_departments': person_departments,
                            'visit_schedule': visit_schedule,
                            'request_id': new_appointment.request_id,
                            'accept_url': f"{base_url}/accept/{encrypted_appointment_id}",
                            'reject_url': f"{base_url}/reject/{encrypted_appointment_id}",
                            'vehicle_number': new_appointment.vehicle_number,
                            # 'visitor_photo': f"{base_url}/user/{all_users.image}"
                            'visitor_photo': 'cid:visitor_image' if (all_users.image) else '',
                            'other_guests_detail': detail
                        }
                        template_name_employee = 'dashboard/email_templates/email_to_concerned_person_(approval_required).html'


                        message_employee = render_to_string(template_name_employee, context_employee)
                        plain_message_employee = strip_tags(message_employee)
                        recipient_list_employee = [employee_email]

                        mail_employee = EmailMultiAlternatives(subject_employee, plain_message_employee, from_email,
                                                               recipient_list_employee)
                        mail_employee.attach_alternative(message_employee, "text/html")
                        if all_users.image:
                            image_filename = os.path.basename(all_users.image.name)
                            image_path = os.path.join(settings.MEDIA_ROOT, 'user', image_filename)

                            with open(image_path, "rb") as img:
                                mime_img = MIMEImage(img.read())
                                mime_img.add_header('Content-ID', '<visitor_image>')
                                mime_img.add_header('Content-Disposition', 'inline', filename="user.png")
                                mail_employee.attach(mime_img)
                        mail_employee.send()
                    except Exception as e:
                        messages.error(request, f"Error: {e}", extra_tags="danger")
                try:
                    if employee_email.mobile != '' or all_users.mobile != '':
                        # visitor_name = all_users.first_name
                        visitor_name =f"{all_users.first_name} {all_users.last_name}".strip()
                        if visitor_name == '':
                            visitor_name = '(visitor name)'
                        else:
                            visitor_name = visitor_name

                        visitor_mobile = all_users.mobile

                        if visitor_mobile == '':

                            visitor_mobile = None

                        else:

                            visitor_mobile = visitor_mobile

                        invitation_link = f"{base_url}/register/{encrypted_appointment_id}"
                        employee_mobile = employee_email.mobile
                        employee_name = f"{employee_email.first_name} {employee_email.last_name}"
                        visitor_name = visitor_name
                        accept_url = f"{base_url}/accept/{encrypted_appointment_id}"
                        reject_url = f"{base_url}/reject/{encrypted_appointment_id}"
                        purpose_of_visit = new_appointment.purpose

                        visitor_image = f"{base_url}/user/{all_users.image}"
                        # print('visitor_image:-',visitor_image)
                        company_id = user_data_gate.company_id
                        check_company = company.objects.get(id=company_id)
                        company_name =  check_company.company_name

                        location_id = user_data_gate.location_id
                        check_location = location.objects.get(id=location_id)
                        company_location = check_location.location_name

                        new_appointment_created_at = new_appointment.created_at
                        dt = datetime.strptime(new_appointment_created_at, "%y-%m-%d %H:%M:%S")
                        check_in_date = dt.strftime("%d-%m-%Y")
                        check_in_time = dt.strftime("%H:%M:%S")
                        # check_in_date = datetime.today().strftime("%d-%m-%Y")
                        # check_in_time = datetime.now().strftime("%H:%M")
                        request_id = new_appointment.request_id
                        qr_code = request.build_absolute_uri(f'/gate_keeper/qr_code_visitor_details/{signing.dumps(new_appointment.id)}'),
                        visitor_company_name = new_appointment.visitor_company_name
                        if visitor_company_name in [None, '', 'NULL', 'null']:
                            visitor_company_name = 'N/A'
                        website_settings = website_setting.objects.first()
                        if website_settings.whatsapp_notification == 1:
                            company_website = website_settings.company_domain
                            whatsapps_send_notifications(request, employee_mobile, employee_name, visitor_name,
                                                         accept_url, reject_url, purpose_of_visit, company_name,
                                                         company_location, check_in_date, check_in_time,
                                                         company_website, visitor_mobile, invitation_link,visitor_image,request_id,qr_code[0],visitor_company_name,is_new_visitor)

                except requests.exceptions.RequestException as e:
                    messages.error(request, f"Error: {e}", extra_tags="danger")
                if email != '' and email != None:
                    try:
                        company_name = email_add_for_companye.company_name
                        visitor_name = f"{all_users.first_name} {all_users.last_name}"
                        person_name = f"{employee_email.first_name} {employee_email.last_name}"
                        person_departments = department.objects.filter(id=employee_email.department_id).first()
                        person_departments = person_departments.department_name
                        subject_visitor = f'Visitor Request Received – {company_name}'
                        context_visitor = {
                            'company_name': company_name,
                            'visitor_name': visitor_name,
                            'person_name': person_name,
                            'person_departments': person_departments,
                            'request_id': new_appointment.request_id,

                        }
                        template_name_visitor = 'dashboard/email_templates/visitor_request_submitted.html'
                        message_visitor = render_to_string(template_name_visitor, context_visitor)
                        plain_message_visitor = strip_tags(message_visitor)
                        recipient_list_visitor = [email]

                        mail_visitor = EmailMultiAlternatives(subject_visitor, plain_message_visitor, from_email,
                                                              recipient_list_visitor)
                        mail_visitor.attach_alternative(message_visitor, "text/html")
                        mail_visitor.send()

                        messages.success(request, "Appointment successfully created.", extra_tags="success")
                        return redirect('employee_visitore_send_invitations')
                    except requests.RequestException as e:
                        print(f"API request error: {e}")
                        messages.error(request, f"API request error: {e}", extra_tags="danger")
                        return redirect('employee_visitore_send_invitations')
                else:
                    messages.success(request, "Appointment successfully created.", extra_tags="success")
                    return redirect('employee_visitore_send_invitations')
        except Exception as e:
            messages.error(request, f"Error: {e}", extra_tags="danger")
            return redirect('employee_visitore_send_invitations')

    return render(request, 'dashboard/employee_dashboard/employee_visitor/employee__visitor_add.html', {
        'username': username, 'all_employee': all_employee, 'locationes': locationes, 'companyes': companyes,
        'departmentes': departmentes,'function_name': 'Employee','select_locationes':select_locationes,'select_companyes':select_companyes,'select_departmentes':select_departmentes,'select_employee':select_employee,'is_id_card_required':is_id_card_required
    })


def employee_visitore_approve_reject(request):
    constants = my_constants(request)
    username = request.session.get('employee')
    if not username:
        return redirect('employee')

    employee_data = constants.get('employee_data', {})
    employee_id = employee_data.get('id')
    print(employee_id)
    if not employee_id:
        return JsonResponse({"status": "false", "message": "Employee ID is required."})

    DOMIN_PATH = constants.get('ADMIN_PATH')
    if not DOMIN_PATH:
        return JsonResponse({"status": "false", "message": "Invalid configuration: ADMIN_PATH missing."})

    types = 'all'
    try:
        page = max(int(request.GET.get('page', 1)), 1)
    except (ValueError, TypeError):
        page = 1

    api_url = f"{DOMIN_PATH}api/visitore_listing"
    payload = {
        "employee_id": employee_id,
        "page": page,
        "type": types
    }

    try:
        response = requests.post(api_url, json=payload, verify=False, timeout=10)
        response.raise_for_status()
        print('response:-',response)
        api_response = response.json()

        if api_response.get('status') == "true":
            results = api_response.get('data', [])
            pagination = api_response.get('pagination', {})
        else:
            message = api_response.get('message', 'No data found.')
            return render(request, 'dashboard/employee_dashboard/employee_visitor/employee_visitore_approve_reject.html', {
                'username': username,
                'user_data': employee_data,
                'message': message,
                'function_name': 'Employee'
            })
    except requests.exceptions.RequestException as e:
        return render(request, 'dashboard/employee_dashboard/employee_visitor/employee_visitore_approve_reject.html', {
            'username': username,
            'user_data': employee_data,
            'message': f"API request failed: {str(e)}",
            'function_name': 'Employee'
        })
    except ValueError:
        return render(request, 'dashboard/employee_dashboard/employee_visitor/employee_visitore_approve_reject.html', {
            'username': username,
            'user_data': employee_data,
            'message': "Invalid response format from the API.",
            'function_name': 'Employee'
        })

    per_page_count = pagination.get('per_page_count', 10)
    last_page = pagination.get('last_page', 1) or 1
    total_entries = pagination.get('total', 0) or 0
    start_index = max((page - 1) * per_page_count + 1, 1)
    end_index = min(page * per_page_count, total_entries)
    page_range = range(1, last_page + 1)

    return render(request, 'dashboard/employee_dashboard/employee_visitor/employee_visitore_approve_reject.html', {
        'username': username,
        'user_data': employee_data,
        'results': results,
        'pagination': pagination,
        'page_range': page_range,
        'start_index': start_index,
        'end_index': end_index,
        'total_entries': total_entries,
        'DOMIN_PATH': DOMIN_PATH,
        'function_name': 'Employee'

    })


def employee_edit(request):
    constants = my_constants(request)

    username = request.session.get('employee')
    if not username:
        return redirect('employee')

    user_data = constants.get('employee_data', {})
    email = username['user_email']
    user_name = username['user_name']

    try:
        employee_user = user.objects.get(email=email)
    except user.DoesNotExist:
        messages.error(request, "User not found.", extra_tags="danger")
        return redirect('employee')
    # employee_user = user.objects.filter(email=email).first()
    #
    # if not employee_user:
    #     messages.error(request, "User not found.", extra_tags="danger")
    #     return redirect('employee')
    mobile = employee_user.mobile
    # user_mobile = user.objects.filter(mobile=mobile).first()
    if request.method == "POST":
        employee_user.first_name = request.POST['Firstname']
        employee_user.last_name = request.POST['Lastname']

        new_email = request.POST['Email']
        if employee_user.email != new_email:
            employee_user.email = new_email
            username['user_email'] = new_email
            request.session['employee'] = username

        employee_user.address = request.POST['Address']
        employee_user.mobile = request.POST['mobile']
        employee_user.gender = request.POST['gender']

        password = request.POST['Password']
        confirm_password = request.POST['Confirm_Password']

        if employee_user.mobile != mobile:
            user_mobile_is_exist = user.objects.filter(mobile=employee_user.mobile).exists()
            if user_mobile_is_exist == True:
                messages.error(request, 'Mobile already exists.', extra_tags='danger')
                return redirect('employee_edit')

        if employee_user.email != email:
            user_email_is_exist = user.objects.filter(email=employee_user.email).exists()
            if user_email_is_exist == True:
                messages.error(request, 'Email already exists.', extra_tags='danger')
                return redirect('employee_edit')

        if 'gender' not in request.POST or request.POST['gender'] == '':
            messages.error(request, 'Please choose a gender.', extra_tags='danger')
            return redirect('employee_edit')

        if password == '' and confirm_password == '':
            pass  # No change in password
        elif password == confirm_password:
            employee_user.password = make_password(confirm_password)
        else:
            messages.error(request, 'Passwords do not match.', extra_tags='danger')
            return redirect('employee_edit')

        if 'image' in request.FILES:
            file = request.FILES['image']
            file_extension = file.name.split('.')[-1].lower()
            if file_extension in ['png', 'jpg', 'jpeg']:
                employee_user.image = file
                print('employee_user',employee_user.image)
            else:
                messages.error(request, 'Error: Invalid image format.', extra_tags='danger')
                return redirect('employee_edit')

        if 'document' in request.FILES:
            document = request.FILES['document']
            document_extension = document.name.split('.')[-1].lower()
            if document_extension in ['png', 'jpg', 'jpeg', 'pdf']:
                employee_user.document = document
            else:
                messages.error(request, 'Error: Invalid document format.', extra_tags='danger')
                return redirect('employee_edit')

        employee_user.save()
        messages.success(request, "Successfully Updated.", extra_tags="success")
        return redirect('employee_edit')

    return render(request, 'dashboard/employee_dashboard/employee_profile/profile_edit.html', {
        'employee_user': employee_user,
        'username': username,
        'user_data': constants['employee_data'],
        'function_name': 'Employee'
    })



def employee_meeting_over(request):
    if request.method == "POST":
        appointment_id = request.POST.get("appointment_id")

        try:
            appointments = appointment.objects.get(id=appointment_id)

            appointments.status = "meeting_completed"
            appointments.save()

            return JsonResponse({
                "status": "success"
            })

        except appointments.DoesNotExist:
            return JsonResponse({
                "status": "error",
                "message": "Appointment not found."
            })

    return JsonResponse({
        "status": "error",
        "message": "Invalid request."
    })