import time
from django.http import JsonResponse
import requests
from django.http import HttpRequest
from django.db import transaction
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse, reverse_lazy
from django.core.paginator import Paginator
from django.db.models import Q
from userauth.models import User
from django.views import View
from .forms import UserRegisterForm, UserLoginForm
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
import secrets
import string
from doctor.models import Doctor, Technician
from patient.models import Patient
from core.models import Service
from reservation.models import Reservation
from .models import AccessLevel, MessageWhatsappTemplate, VerificationCode, PasswordResetCode
from .forms import EmployeeRegistrationForm, MessageWhatsappTemplateForm

from django.views.decorators.http import require_POST, require_GET
import json
from django.utils.decorators import method_decorator
from django.core.mail import send_mail
from django.conf import settings
import logging
# from core.management.utils import send_whatsapp, send_whatsapp_message
from waapi.utils import send_whatsapp


User = get_user_model()
logger = logging.getLogger(__name__)

from django.contrib.auth.views import PasswordResetConfirmView
from django.urls import reverse_lazy
from django.http import JsonResponse
import random
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def send_whatsapp_message_custom(request):
    if request.method == 'POST':
        print("request=", request)
        print("request=", request.POST)
        print("request=", request.POST.get('service_id'))

        service_id = int(request.POST.get('service_id'))
        content = request.POST.get('content')
        messageType = request.POST.get('messageType')
        patient_ids = request.POST.get('Patient_ids')
        patient_ids = patient_ids.split(',')
        print("service_id:", service_id)
        print("content:", content)
        print("messageType:", messageType)
        print("Patient_ids:", patient_ids)
        print("type Patient_ids:", type(patient_ids))

        try:
            if '999999' in patient_ids:
                reservations = Reservation.objects.exclude(status='canceled')
                try:
                    if service_id != 999:
                        service_obj = Service.objects.get(id=service_id)
                        reservations = reservations.filter(service=service_obj)

                except Exception as e:
                    print(f"❌ Error getting service: {e}")


                # بیمارانی که رزرویشن فعال دارند
                active_reservation_patient_ids = reservations.values_list(
                    'patient_id', flat=True
                ).distinct()

                # بیمارانی که رزرویشن فعال ندارند برای این سرویس خاص
                if messageType == 'patient_without_service':
                    patient_list = Patient.objects.exclude(
                        id__in=active_reservation_patient_ids
                    )
                else:
                    patient_list = Patient.objects.filter(
                        id__in=active_reservation_patient_ids
                    )
                print("patient_list ==", patient_list)
                print("patient_list ==", len(patient_list))
                for p in patient_list:
                    phone = p.country_code + p.phone_number
                    print("p=", p.id)
                    print("phone=", phone)
                    print("content=", content)

                    # استفاده از تابع ارسال واتساپ موجود
                    response = send_whatsapp(phone, content)



            else:
                for patient_id in patient_ids:
                    try:

                        if patient_id.isdigit():
                            patient_id = int(patient_id)
                        else:
                            continue

                        patient_id = int(patient_id)
                        patient = Patient.objects.get(id=patient_id)
                        phone = patient.country_code + patient.phone_number
                        print("p.id=", patient_id)
                        print("phone=", phone)
                        print("content=", content)

                        # استفاده از تابع ارسال واتساپ موجود
                        response = send_whatsapp(phone, content)

                    except Exception as e:
                        print(e)

            return JsonResponse({'success':True,'message': 'Sent'})

        except User.DoesNotExist:
            return JsonResponse({'success':False,'error': 'Error'}, status=404)

    return JsonResponse({'success':False,'error': 'Error'}, status=405)

@csrf_exempt
def request_password_reset(request):
    print("in request_password_reset")
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username')
        print("Received username:", username)

        try:

            print("in request_password_reset=", username)
            user = User.objects.get(username=username)
            phone = user.country_code + user.phone_number
            print("phone=", phone)
            # اگر کاربر شماره تلفن نداشته باشد
            if not user.phone_number:
                return JsonResponse({'error': 'No phone number is registered for this user.'}, status=400)

            # ایجاد کد بازیابی
            code = str(random.randint(100000, 999999))
            print("code=", code)

            # ذخیره کد در دیتابیس
            PasswordResetCode.objects.create(user=user, code=code)

            # ارسال پیام به واتساپ
            message = f"""
            Your password recovery code:{code}
            This code is valid for 15 minutes.
            """

            response = send_whatsapp(phone, message)

            if response.status_code == 200:
                return JsonResponse({'success': 'کد بازیابی به واتساپ شما ارسال شد'})
            else:
                return JsonResponse({'error': 'خطا در ارسال پیام به واتساپ'}, status=500)

        except User.DoesNotExist:
            return JsonResponse({'error': 'کاربری با این نام کاربری یافت نشد'}, status=404)

    return JsonResponse({'error': 'فقط درخواست POST پذیرفته می‌شود'}, status=405)


from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import SetPasswordForm


def verify_reset_code(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username')
        code = data.get('code')
        new_password = data.get('new_password')
        print("Received username:", username)
        try:
            user = User.objects.get(username=username)
            reset_code = PasswordResetCode.objects.filter(
                user=user,
                code=code,
                is_used=False
            ).order_by('-created_at').first()

            if not reset_code or not reset_code.is_valid():
                return JsonResponse({'error': 'کد نامعتبر یا منقضی شده است'}, status=400)

            # تغییر رمز عبور
            form = SetPasswordForm(user, {'new_password1': new_password, 'new_password2': new_password})
            if form.is_valid():
                form.save()
                reset_code.is_used = True
                reset_code.save()

                # به روزرسانی session برای کاربران لاگین کرده
                if request.user.is_authenticated:
                    update_session_auth_hash(request, user)

                return JsonResponse({'success': 'رمز عبور با موفقیت تغییر یافت'})
            else:
                return JsonResponse({'error': form.errors}, status=400)

        except User.DoesNotExist:
            return JsonResponse({'error': 'کاربری با این نام کاربری یافت نشد'}, status=404)

    return JsonResponse({'error': 'فقط درخواست POST پذیرفته می‌شود'}, status=405)


@login_required
def all_leaders(request):
    leader_list = User.objects.filter(access_level='Leader').order_by('id')
    leaders = []
    for leader in leader_list:
        leaders.append({
            'id': leader.id,
            'name': leader.get_full_name(),
        })
    results = {"leaders": leaders}
    return JsonResponse({'success': True, 'results': results})


def generate_secure_password(length=12):
    """Generate a secure random password"""
    alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
    password = ''.join(secrets.choice(alphabet) for i in range(length))
    return password


def generate_verification_code():
    """Generate a 6-digit verification code"""
    return ''.join(secrets.choice(string.digits) for i in range(6))


@require_POST
def save_message_template(request):
    try:
        data = json.loads(request.body)
        msg_type = data.get('message_type')
        content = data.get('content')

        # بررسی وجود فیلدهای ضروری
        if not msg_type or not content.strip():
            return JsonResponse({'success': False, 'error': 'Message type and content are required'}, status=400)

        # پیدا کردن یا ایجاد قالب پیام
        obj, created = MessageWhatsappTemplate.objects.update_or_create(
            message_type=msg_type,
            defaults={
                'content': content,
                'modified_by': request.user
            }
        )

        action = 'created' if created else 'updated'
        return JsonResponse({
            'success': True,
            'created': created,
            'message': f'Template {action} successfully!'
        })

    except json.JSONDecodeError:
        return JsonResponse({'success': False, 'error': 'Invalid JSON data'}, status=400)
    except Exception as e:
        logger.error(f"Error saving message template: {str(e)}")
        return JsonResponse({'success': False, 'error': str(e)}, status=500)


@require_GET
def get_message_template(request):
    try:
        message_type = request.GET.get('type')

        if not message_type:
            return JsonResponse({'success': False, 'error': 'Message type is required'}, status=400)

        try:
            template = MessageWhatsappTemplate.objects.get(message_type=message_type)
            return JsonResponse({
                'success': True,
                'template': {
                    'message_type': template.message_type,
                    'content': template.content,
                    'modified_at': template.modified_at.isoformat() if template.modified_at else None,
                    'modified_by': template.modified_by.get_full_name() if template.modified_by else None
                }
            })
        except MessageWhatsappTemplate.DoesNotExist:
            return JsonResponse({
                'success': True,
                'template': None,
                'message': 'No template found for this type'
            })

    except Exception as e:
        logger.error(f"Error getting message template: {str(e)}")
        return JsonResponse({'success': False, 'error': str(e)}, status=500)


@method_decorator(login_required, name='dispatch')
class SecurityView(View):
    """Handles viewing security settings and employee registration."""

    def get(self, request, *args, **kwargs):
        # Check if user is Administrator for employee registration features
        is_admin = request.user.access_level == AccessLevel.ADMINISTRATOR

        search_query = request.GET.get('searchQuery', '')
        filter_type = request.GET.get('filterType', 'first_name')

        user_list = User.objects.all()
        if search_query:
            if filter_type == 'first_name':
                user_list = User.objects.filter(
                    Q(first_name__icontains=search_query))
            elif filter_type == 'last_name':
                user_list = User.objects.filter(
                    Q(last_name__icontains=search_query))
            elif filter_type == 'username':
                user_list = User.objects.filter(
                    Q(username__icontains=search_query))
            elif filter_type == 'access_level':
                user_list = User.objects.filter(
                    Q(access_level__icontains=search_query))
            else:
                user_list = User.objects.none()

        user_list = user_list.order_by('first_name')

        # Paginate the results
        paginator = Paginator(user_list, 10)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)

        # Create employee form for admins
        employee_form = None
        if is_admin:
            employee_form = EmployeeRegistrationForm()

        context = {
            'page_obj': page_obj,
            'search_query': search_query,
            'filter_type': filter_type,
            'employee_form': employee_form,
            'is_admin': is_admin,
        }
        return render(request, 'security/setting-security.html', context)

    def post(self, request, *args, **kwargs):
        # Check if user is Administrator for most actions
        action = request.POST.get('action')

        # Handle AJAX requests
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return self.handle_ajax_request(request)

        # Handle regular form submissions
        if action == 'create_employee':
            return self.handle_employee_creation(request)

        # Non-AJAX POST request - redirect back to GET
        return redirect('userauth:security-setting')

    def handle_ajax_request(self, request):
        """Handle all AJAX requests"""
        action = request.POST.get('action')

        if action == 'delete_user':
            return self.handle_user_deletion(request)
        elif action == 'reset_password':
            return self.handle_password_reset(request)
        elif action == 'edit_user':
            return self.handle_user_edit(request)
        elif action == 'request_verification':
            return self.handle_verification_request(request)
        elif action == 'load_persons':
            return self.handle_load_persons(request)
        elif action == 'save_template':
            return self.handle_save_template(request)
        elif action == 'load_template':
            return self.handle_load_template(request)
        elif action == 'create_employee':
            return self.handle_employee_creation(request)
        else:
            return JsonResponse({'success': False, 'error': 'Invalid action'}, status=400)

    def handle_user_deletion(self, request):
        """Handle user deletion"""
        if request.user.access_level != AccessLevel.ADMINISTRATOR:
            return JsonResponse({
                'success': False,
                'error': "You don't have permission to delete users."
            }, status=403)
        print("request.POST Delete=", request.POST)
        verification = request.POST.get('verification')
        if not verification:
            return JsonResponse({
                'success': False,
                'error': 'Please Enter a correct verification code.'
            })
        vericode = VerificationCode.objects.all().order_by('id').last()
        print(vericode.code)
        print(verification)
        print(type(vericode.code))
        print(type(verification))
        if str(vericode.code) != str(verification) or not verification:
            return JsonResponse({
                'success': False,
                'error': 'Please Enter a correct verification code.'
            })
        user_id = request.POST.get('user_id') or request.POST.get('delete_user')
        if not user_id:
            return JsonResponse({
                'success': False,
                'error': 'User ID is required'
            }, status=400)

        try:
            with transaction.atomic():
                user = User.objects.get(id=user_id)

                # Prevent admin from deleting themselves
                if user.id == request.user.id:
                    return JsonResponse({
                        'success': False,
                        'error': 'You cannot delete your own account.'
                    })

                username = user.username

                # Set user field to null in related tables based on access level
                if user.access_level == AccessLevel.DOCTOR:
                    try:
                        doctor = Doctor.objects.get(user=user)
                        doctor.user = None
                        doctor.save()
                    except Doctor.DoesNotExist:
                        pass

                elif user.access_level == AccessLevel.TECHNICIAN:
                    try:
                        technician = Technician.objects.get(user=user)
                        technician.user = None
                        technician.save()
                    except Technician.DoesNotExist:
                        pass

                # elif user.access_level == AccessLevel.PATIENT:
                #     try:
                #         patient = Patient.objects.get(user=user)
                #         patient.user = None
                #         patient.save()
                #     except Patient.DoesNotExist:
                #         pass

                # Delete the user from User table
                user.delete()

                return JsonResponse({
                    'success': True,
                    'message': f'User "{username}" has been successfully deleted.'
                })

        except User.DoesNotExist:
            return JsonResponse({
                'success': False,
                'error': 'User not found.'
            })
        except Exception as e:
            logger.error(f"Error deleting user: {str(e)}")
            return JsonResponse({
                'success': False,
                'error': f'Error deleting user: {str(e)}'
            })

    def handle_password_reset(self, request):
        """Handle password reset"""
        if request.user.access_level != AccessLevel.ADMINISTRATOR:
            return JsonResponse({
                'success': False,
                'error': "You don't have permission to reset passwords."
            }, status=403)

        username = request.POST.get('username')

        if not username:
            return JsonResponse({
                'success': False,
                'error': 'Username is required'
            }, status=400)

        try:
            user = User.objects.get(username=username)
            new_password = generate_secure_password()
            user.set_password(new_password)
            user.save()

            return JsonResponse({
                'success': True,
                'message': f'Password reset successfully!',
                'new_password': new_password,
                'username': username
            })
        except User.DoesNotExist:
            return JsonResponse({
                'success': False,
                'error': 'There isn\'t any user with that username.'
            })
        except Exception as e:
            logger.error(f"Error resetting password: {str(e)}")
            return JsonResponse({
                'success': False,
                'error': f'Error resetting password: {str(e)}'
            })

    def handle_user_edit(self, request):
        if request.user.access_level != AccessLevel.ADMINISTRATOR:
            return JsonResponse({
                'success': False,
                'error': "You don't have permission to edit users."
            }, status=403)

        user_id = request.POST.get('user_id')
        if not user_id:
            return JsonResponse({'success': False, 'error': 'User ID is required'}, status=400)

        try:
            with transaction.atomic():
                user = User.objects.get(id=user_id)

                # Update basic info
                user.first_name = request.POST.get('first_name', '').strip()
                user.last_name = request.POST.get('last_name', '').strip()
                user.username = request.POST.get('username', '').strip()
                user.phone_number = request.POST.get('phone_number', '').strip()
                user.country_code = request.POST.get('country_code', user.country_code)
                user.access_level = request.POST.get('access_level', user.access_level)

                # Validate required fields
                if not user.first_name or not user.last_name or not user.username:
                    return JsonResponse({
                        'success': False,
                        'error': 'First name, last name, and username are required'
                    })

                # Check username uniqueness
                if User.objects.filter(username=user.username).exclude(id=user.id).exists():
                    return JsonResponse({
                        'success': False,
                        'error': 'Username already exists'
                    })

                # Handle password change
                if request.POST.get('password_change') == 'true':
                    current_password = request.POST.get('current_password')
                    new_password = request.POST.get('new_password')

                    if not user.check_password(current_password):
                        return JsonResponse({
                            'success': False,
                            'error': 'Current password is incorrect'
                        })

                    if not self.is_password_strong(new_password):
                        return JsonResponse({
                            'success': False,
                            'error': 'Password does not meet security requirements'
                        })

                    user.set_password(new_password)

                # Handle password reset
                elif request.POST.get('password_reset') == 'true':
                    verification_code = request.POST.get('verification_code')
                    new_password = request.POST.get('reset_new_password')
                    confirm_password = request.POST.get('reset_confirm_password')

                    # بررسی کد تایید
                    if not self.verify_verification_code(request.user, verification_code):
                        return JsonResponse({
                            'success': False,
                            'error': 'Invalid verification code'
                        })

                    # بررسی رمز جدید
                    if not new_password or not confirm_password:
                        return JsonResponse({
                            'success': False,
                            'error': 'Please enter and confirm new password'
                        })

                    if new_password != confirm_password:
                        return JsonResponse({
                            'success': False,
                            'error': 'Passwords do not match'
                        })

                    if not self.is_password_strong(new_password):
                        return JsonResponse({
                            'success': False,
                            'error': 'Password does not meet security requirements'
                        })

                    user.set_password(new_password)
                    user.save()

                user.save()

                return JsonResponse({
                    'success': True,
                    'message': f'User "{user.username}" updated successfully!'
                })

        except User.DoesNotExist:
            return JsonResponse({'success': False, 'error': 'User not found'})
        except Exception as e:
            logger.error(f"Error editing user: {str(e)}")
            return JsonResponse({'success': False, 'error': f'Error updating user: {str(e)}'})

    def verify_verification_code(self, admin_user, code):
        """Verify the verification code (implement your logic)"""
        try:
            vericode = VerificationCode.objects.filter(modified_by=admin_user).latest('id')
            return str(vericode.code) == str(code)
        except VerificationCode.DoesNotExist:
            return False

    def handle_verification_request(self, request):
        print("in handle_verification_request")
        """Handle verification code request"""
        if request.user.access_level != AccessLevel.ADMINISTRATOR:
            return JsonResponse({
                'success': False,
                'error': "You don't have permission to request verification codes."
            }, status=403)

        user_id = request.POST.get('user_id')
        print("user_id=", user_id)
        if not user_id:
            return JsonResponse({
                'success': False,
                'error': 'User ID is required'
            }, status=400)

        try:
            user = User.objects.get(id=user_id)
            verification_code = generate_verification_code()
            print("verification_code=", verification_code)

            # ذخیره کد تأیید در دیتابیس
            obj_ = VerificationCode.objects.filter(modified_by=request.user).delete()
            obj, created = VerificationCode.objects.update_or_create(
                code=verification_code,
                defaults={
                    'modified_by': request.user
                }
            )

            # ارسال به واتس‌اپ
            try:
                # اگر کاربر شماره تلفن دارد، به شماره خود کاربر ارسال شود
                if user.phone_number and user.country_code:
                    phone_number = f"{user.country_code}{user.phone_number.lstrip('0')}"
                    message = f"Your verification code is: {verification_code}"
                    send_whatsapp(phone_number, message)
                    send_whatsapp(settings.MANAGER_PHONE, message)
                else:
                    # در غیر این صورت به شماره پیش‌فرض (مثلاً شماره ادمین)
                    default_phone = settings.MANAGER_PHONE  # شماره پیش‌فرض
                    message = f"Verification code for user {user.username} is: {verification_code}"
                    send_whatsapp(default_phone, message)
            except Exception as e:
                print("Error sending WhatsApp:", e)

            # ارسال به ایمیل
            try:
                if user.email:
                    email = user.email
                    message = f"Your verification code is: {verification_code}"
                    send_mail(
                        subject='Your Verification Code',
                        message=message,
                        from_email=None,
                        recipient_list=[settings.EMAIL_HOST_USER],
                        fail_silently=False
                    )
                    send_mail(
                        subject='Your Verification Code',
                        message=message,
                        from_email=None,
                        recipient_list=[email],
                        fail_silently=False
                    )
                else:
                    # در غیر این صورت به ایمیل پیش‌فرض
                    default_email = settings.EMAIL_HOST_USER
                    message = f"Verification code for user {user.username} is: {verification_code}"
                    send_mail(
                        subject='Verification Code',
                        message=message,
                        from_email=None,
                        recipient_list=[default_email],
                        fail_silently=False
                    )
            except Exception as e:
                print("Error sending email:", e)

            return JsonResponse({
                'success': True,
                'message': 'Verification code sent to WhatsApp and email!',
                'verification_code': ''  # در محیط تولید این خط باید حذف شود
            })

        except User.DoesNotExist:
            return JsonResponse({
                'success': False,
                'error': 'User not found'
            })
        except Exception as e:
            logger.error(f"Error generating verification code: {str(e)}")
            return JsonResponse({
                'success': False,
                'error': f'Error generating verification code: {str(e)}'
            })

    def handle_load_persons(self, request):
        """Handle loading persons for employee registration"""
        if request.user.access_level != AccessLevel.ADMINISTRATOR:
            return JsonResponse({
                'success': False,
                'error': "You don't have permission to load persons."
            }, status=403)

        access_level = request.POST.get('access_level')

        if not access_level:
            return JsonResponse({
                'success': False,
                'error': 'Access level is required'
            }, status=400)

        try:
            persons = []

            if access_level == AccessLevel.DOCTOR:
                doctors = Doctor.objects.filter(user__isnull=True)
                persons = [
                    {'id': d.id, 'first_name': d.first_name, 'last_name': d.last_name, 'phone_number': d.phone_number}
                    for d in doctors]
            elif access_level == AccessLevel.TECHNICIAN:
                technicians = Technician.objects.filter(user__isnull=True)
                persons = [
                    {'id': t.id, 'first_name': t.first_name, 'last_name': t.last_name, 'phone_number': t.phone_number}
                    for t in technicians]
            elif access_level == AccessLevel.PATIENT:
                patients = Patient.objects.filter(user__isnull=True)
                persons = [
                    {'id': p.id, 'first_name': p.first_name, 'last_name': p.last_name, 'phone_number': p.phone_number}
                    for p in patients]

            return JsonResponse({
                'success': True,
                'persons': persons
            })

        except Exception as e:
            logger.error(f"Error loading persons: {str(e)}")
            return JsonResponse({
                'success': False,
                'error': f'Error loading persons: {str(e)}'
            })

    def handle_save_template(self, request):
        """Handle saving message templates"""
        if request.user.access_level != AccessLevel.ADMINISTRATOR:
            return JsonResponse({
                'success': False,
                'error': "You don't have permission to save templates."
            }, status=403)

        message_type = request.POST.get('message_type')
        content = request.POST.get('content')
        service_id = request.POST.get('service_id')

        if not message_type or not content:
            return JsonResponse({
                'success': False,
                'error': 'Message type and content are required'
            }, status=400)

        try:
            if service_id:
                print("service_id=", service_id, type(service_id))
                if service_id != 999 and service_id != '999':
                    service = Service.objects.get(id=int(service_id))
                    service_id = service.id
                    service_name = service.name
                else:
                    service_id = 999
                    service_name = "all"
                try:
                    obj = MessageWhatsappTemplate.objects.get(message_type=message_type, service_id=int(service_id))
                    obj.service_name = service_name
                    obj.content = content
                    obj.modified_by = request.user
                    obj.save()
                    action = 'updated'

                except Exception as e:
                    created = MessageWhatsappTemplate.objects.create(
                        message_type=message_type,
                        service_id=int(service_id),
                        service_name=service_name,
                        content=content,
                        modified_by=request.user
                    )
                    action = 'created'
                return JsonResponse({
                    'success': True,
                    'message': f'Template {action} successfully!'
                })
            else:
                obj, created = MessageWhatsappTemplate.objects.update_or_create(
                    message_type=message_type,
                    defaults={
                        'content': content,
                        'modified_by': request.user
                    }
                )

                action = 'created' if created else 'updated'
                return JsonResponse({
                    'success': True,
                    'message': f'Template {action} successfully!'
                })

        except Exception as e:
            logger.error(f"Error saving template: {str(e)}")
            return JsonResponse({
                'success': False,
                'error': f'Error saving template: {str(e)}'
            })

    def handle_load_template(self, request):
        """Handle loading message templates"""
        message_type = request.POST.get('message_type')
        service_id = request.POST.get('service_id')

        if not message_type:
            return JsonResponse({
                'success': False,
                'error': 'Message type is required'
            }, status=400)
        print("********************************!!!!!!!!!!!!!!!!!!!!!!!!!!!=")
        print("service_id=", service_id, type(service_id))
        try:
            if service_id == '':
                template = MessageWhatsappTemplate.objects.get(message_type=message_type)
                return JsonResponse({
                    'success': True,
                    'template': template.content
                })
            else:
                template = MessageWhatsappTemplate.objects.get(message_type=message_type, service_id=int(service_id))
                return JsonResponse({
                    'success': True,
                    'template': template.content
                })
        except MessageWhatsappTemplate.DoesNotExist:
            return JsonResponse({
                'success': True,
                'template': None
            })
        except Exception as e:
            logger.error(f"Error loading template: {str(e)}")
            return JsonResponse({
                'success': False,
                'error': f'Error loading template: {str(e)}'
            })

    def handle_employee_creation(self, request):
        print("in handle_employee_creation")
        """Handle employee registration"""
        if request.user.access_level != AccessLevel.ADMINISTRATOR:
            return JsonResponse({
                'success': False,
                'error': "You don't have permission to create employees."
            }, status=403)

        form = EmployeeRegistrationForm(request.POST)
        print("form=", form.is_valid())
        print("form.cleaned_data=", form)
        print("form.cleaned_data=", form.cleaned_data)
        print("form.cleaned_data['phone_number']=", form.cleaned_data['phone_number'])

        if form.is_valid():
            try:
                with transaction.atomic():
                    # Get form data
                    first_name = form.cleaned_data['first_name']
                    last_name = form.cleaned_data['last_name']
                    email = form.cleaned_data['email']
                    access_level = form.cleaned_data['access_level']
                    phone_number = form.cleaned_data['phone_number']
                    country_code = form.cleaned_data['country_code']
                    selected_person_id = form.cleaned_data.get('selected_person')

                    # Generate username and password
                    base_username = f"{first_name.lower()}-{last_name.lower()}"
                    generated_password = generate_secure_password()
                    username = base_username

                    # Check if username exists and handle accordingly
                    if User.objects.filter(username=username).exists():
                        existing_user = User.objects.get(username=username)
                        existing_user.phone_number = phone_number
                        existing_user.country_code = country_code
                        if email:
                            existing_user.email = email
                        # If user exists and is linked to a profile
                        if (Doctor.objects.filter(user=existing_user).exists() or
                                Technician.objects.filter(user=existing_user).exists() ):

                            # Just update password
                            existing_user.set_password(generated_password)
                            existing_user.save()
                            user = existing_user
                        else:
                            # Create new user with modified username
                            username = f"{base_username}-{User.objects.filter(username__startswith=base_username).count() + 1}"
                            user = User.objects.create_user(
                                username=username,
                                password=generated_password,
                                first_name=first_name,
                                last_name=last_name,
                                phone_number=phone_number,
                                country_code=country_code,
                                email=email,
                                access_level=access_level
                            )
                    else:
                        # Create new user
                        user = User.objects.create_user(
                            username=username,
                            password=generated_password,
                            first_name=first_name,
                            last_name=last_name,
                            phone_number=phone_number,
                            country_code=country_code,
                            email=email,
                            access_level=access_level
                        )

                    # Link to existing person if selected
                    if selected_person_id:
                        try:
                            if access_level == AccessLevel.DOCTOR:
                                person = Doctor.objects.get(id=selected_person_id, user__isnull=True)
                            elif access_level == AccessLevel.TECHNICIAN:
                                person = Technician.objects.get(id=selected_person_id, user__isnull=True)


                            person.user = user
                            person.save()
                            user.phone_number = person.phone_number
                            user.country_code = person.country_code
                            user.save()
                        except (Doctor.DoesNotExist, Technician.DoesNotExist, Patient.DoesNotExist):
                            return JsonResponse({
                                'success': False,
                                'error': 'The selected person is already linked to another user.'
                            })

                    # Create profile if not linked to existing person
                    if not selected_person_id:
                        if access_level == AccessLevel.DOCTOR:
                            Doctor.objects.create(user=user, first_name=first_name, last_name=last_name)
                        elif access_level == AccessLevel.TECHNICIAN:
                            Technician.objects.create(user=user, first_name=first_name, last_name=last_name)


                    return JsonResponse({
                        'success': True,
                        'message': f'Account created successfully:<br>Username: {username}<br>Password: {generated_password}'
                    })

            except ValidationError as e:
                return JsonResponse({
                    'success': False,
                    'error': f"Validation Error: {e}"
                })
            except Exception as e:
                logger.error(f"Error creating employee: {str(e)}")
                return JsonResponse({
                    'success': False,
                    'error': f"Unexpected Error: {str(e)}"
                })
        else:
            errors = form.errors.items()
            print(errors)
            # Form is invalid
            errors = []
            for field, error_list in form.errors.items():
                for error in error_list:
                    errors.append(f"{field}: {error}")
            return JsonResponse({
                'success': False,
                'error': '<br>'.join(errors)
            })

    def is_password_strong(self, password):
        """Check if password meets security requirements"""
        if len(password) < 8:
            return False

        has_upper = any(c.isupper() for c in password)
        has_lower = any(c.islower() for c in password)
        has_digit = any(c.isdigit() for c in password)
        has_special = any(c in "!@#$%^&*(),.?\":{}|<>" for c in password)

        return has_upper and has_lower and has_digit and has_special


@login_required
def register_employee(request):
    print("in register_employee=", request)
    # Check if user is Administrator
    if request.user.access_level != AccessLevel.ADMINISTRATOR:
        messages.error(request, "You can't do this action.")
        return redirect('dashboard')

    # Handle AJAX requests (both password reset and employee registration)
    if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        print("AJAX request detected")

        # Password reset request
        if 'username' in request.POST and 'reset_password' not in request.POST:
            username = request.POST.get('username')
            try:
                user = User.objects.get(username=username)
                new_password = generate_secure_password()
                user.set_password(new_password)
                user.save()

                return JsonResponse({
                    'success': True,
                    'message': f'Success:<br> Username: {username}<br>Password: {new_password}'
                })
            except User.DoesNotExist:
                return JsonResponse({
                    'success': False,
                    'error': 'There isn\'t any User with that username.'
                })

        # Employee registration request
        else:
            form = EmployeeRegistrationForm(request.POST)
            print("Form data:", request.POST)

            if form.is_valid():
                try:
                    # Get form data
                    first_name = form.cleaned_data['first_name']
                    last_name = form.cleaned_data['last_name']
                    access_level = form.cleaned_data['access_level']
                    selected_person_id = form.cleaned_data.get('selected_person')

                    # Generate username and password
                    base_username = f"{first_name.lower()}-{last_name.lower()}"
                    generated_password = generate_secure_password()
                    username = base_username

                    # Check if username exists and handle accordingly
                    if User.objects.filter(username=username).exists():
                        existing_user = User.objects.get(username=username)

                        # If user exists and is linked to a profile
                        if (Doctor.objects.filter(user=existing_user).exists() or
                                Technician.objects.filter(user=existing_user).exists() or
                                Patient.objects.filter(user=existing_user).exists()):

                            # Just update password
                            existing_user.set_password(generated_password)
                            existing_user.save()
                            user = existing_user
                        else:
                            # Create new user with modified username
                            username = f"{base_username}-{User.objects.filter(username__startswith=base_username).count() + 1}"
                            user = User.objects.create_user(
                                username=username,
                                password=generated_password,
                                first_name=first_name,
                                last_name=last_name,
                                access_level=access_level
                            )
                    else:
                        # Create new user
                        user = User.objects.create_user(
                            username=username,
                            password=generated_password,
                            first_name=first_name,
                            last_name=last_name,
                            access_level=access_level
                        )

                    # Link to existing person if selected
                    if selected_person_id:
                        try:
                            if access_level == AccessLevel.DOCTOR:
                                person = Doctor.objects.get(id=selected_person_id, user__isnull=True)
                            elif access_level == AccessLevel.TECHNICIAN:
                                person = Technician.objects.get(id=selected_person_id, user__isnull=True)
                            else:  # Patient
                                person = Patient.objects.get(id=selected_person_id, user__isnull=True)

                            person.user = user
                            person.save()
                        except (Doctor.DoesNotExist, Technician.DoesNotExist, Patient.DoesNotExist):
                            return JsonResponse({
                                'success': False,
                                'error': 'The selected person is already linked to another user.'
                            })

                    # Create profile if not linked to existing person
                    if not selected_person_id:
                        if access_level == AccessLevel.DOCTOR:
                            Doctor.objects.create(user=user, first_name=first_name, last_name=last_name)
                        elif access_level == AccessLevel.TECHNICIAN:
                            Technician.objects.create(user=user, first_name=first_name, last_name=last_name)
                        else:
                            Patient.objects.create(user=user, first_name=first_name, last_name=last_name)

                    return JsonResponse({
                        'success': True,
                        'message': f'Account created successfully:<br>Username: {username}<br>Password: {generated_password}'
                    })

                except ValidationError as e:
                    return JsonResponse({
                        'success': False,
                        'error': f"Validation Error: {e}"
                    })
                except Exception as e:
                    return JsonResponse({
                        'success': False,
                        'error': f"Unexpected Error: {str(e)}"
                    })
            else:
                # Form is invalid
                errors = []
                for field, error_list in form.errors.items():
                    for error in error_list:
                        errors.append(f"{field}: {error}")
                return JsonResponse({
                    'success': False,
                    'error': '<br>'.join(errors)
                })

    # Regular GET request
    form = EmployeeRegistrationForm()
    return render(request, 'security/register_employee.html', {'form': form})


@require_http_methods(["GET"])
def get_persons_by_type(request):
    person_type = request.GET.get('type')
    persons = []

    if person_type == AccessLevel.DOCTOR:
        doctors = Doctor.objects.filter(user__isnull=True).values('id', 'first_name', 'last_name')
        persons = [
            {
                'id': doc['id'],
                'name': f"{doc['first_name']} {doc['last_name']}"
            }
            for doc in doctors
        ]
    elif person_type == AccessLevel.TECHNICIAN:
        technicians = Technician.objects.filter(user__isnull=True).values('id', 'first_name', 'last_name')
        persons = [
            {
                'id': tech['id'],
                'name': f"{tech['first_name']} {tech['last_name']}"
            }
            for tech in technicians
        ]
    elif person_type in [AccessLevel.SUPERVISOR, AccessLevel.ACCOUNTANT]:
        # For these roles, we might want to show patients or create new entries
        patients = Patient.objects.filter(user__isnull=True).values('id', 'first_name', 'last_name')
        persons = [
            {
                'id': patient['id'],
                'name': f"{patient['first_name']} {patient['last_name']}"
            }
            for patient in patients
        ]

    return JsonResponse({'persons': persons})


SETTING_SECURTITY_CREATE = 'security/setting-security-create.html'
SECURITY_SETTING = 'userauth:security-setting'
SECURITY_EDIT = 'security/setting-security-edit.html'


def unauthorized_view(request, exception):
    return render(request, 'unauthorized.html', status=403)


class UserLoginView(View):
    template_name = 'userauth/index.html'

    def get(self, request: HttpRequest):
        if request.user.is_authenticated:
            return redirect('core:dashboard')

        form = UserLoginForm()
        return render(request, self.template_name, {'form': form, 'page_messages': []})

    def post(self, request: HttpRequest):
        form = UserLoginForm(request, data=request.POST)  # تغییر این خط
        page_messages = []

        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            remember_me = form.cleaned_data.get('remember_me', False)
            user = authenticate(request, username=username, password=password)

            if user is not None:
                login(request, user)  # تغییر از login به login

                if remember_me:
                    request.session.set_expiry(60 * 60 * 24 * 30)  # 30 روز
                else:
                    request.session.set_expiry(0)  # پایان با بستن مرورگر

                return redirect('core:dashboard')
            else:
                page_messages.append({'level': 'error', 'text': 'Invalid username or password.'})
        else:
            for field, errors in form.errors.items():
                for error in errors:
                    if field == '__all__':
                        page_messages.append({'level': 'error', 'text': error})
                    else:
                        page_messages.append({'level': 'error', 'text': f"{field}: {error}"})

        return render(request, self.template_name, {'form': form, 'page_messages': page_messages})


class UserLogoutView(View):
    def post(self, request: HttpRequest):
        messages.get_messages(request)  # clear all messages
        logout(request)
        messages.info(request, 'You have been logged out successfully.')
        return redirect(reverse_lazy('userauth:login'))

    def get(self, request):
        # Handle GET requests (e.g., if someone tries to access the logout URL directly)
        return self.post(request)


####  SECURITY ####


class SecurityCreateUserView(View):

    def get(self, request, *args, **kwargs):
        form = UserRegisterForm()
        return render(request, SETTING_SECURTITY_CREATE, {'form': form})

    def post(self, request: HttpRequest):
        form = UserRegisterForm(request.POST)

        # Make sure the password is required during user creation
        if not form.instance.pk:  # Only when creating a new user
            form.fields['password'].required = True
            form.fields['confirm_password'].required = True

        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']

            username = f"{first_name.lower()}-{last_name.lower()}"

            # Check if the username already exists
            if User.objects.filter(username=username).exists():
                messages.error(request, f"The username '{username}' already exists.")
                return render(request, SETTING_SECURTITY_CREATE, {'form': form})

            user = form.save(commit=False)
            user.username = username
            user.save()

            messages.success(request, "User created successfully.")
            return redirect(SECURITY_SETTING)
        else:
            # Add this block to handle form errors
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f"{field.capitalize()}: {error}")

        return render(request, SETTING_SECURTITY_CREATE, {'form': form})


class SecurityEditView(View):
    """Handles the Edit of Access Level to Employee."""

    def get(self, request: HttpRequest, id):
        user = get_object_or_404(User, id=id)
        form = UserRegisterForm(instance=user)
        return render(request, SECURITY_EDIT, {'form': form, 'user': user})

    def post(self, request: HttpRequest, id):
        user = get_object_or_404(User, id=id)
        form = UserRegisterForm(request.POST, instance=user)

        # Make the password fields optional during edit
        if form.instance.pk:  # Only when editing an existing user
            form.fields['password'].required = False
            form.fields['confirm_password'].required = False

        if form.is_valid():
            password = form.cleaned_data.get('password')
            confirm_password = form.cleaned_data.get('confirm_password')
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']

            if password and password != confirm_password:
                messages.error(request, "Passwords do not match.")
                return render(request, SECURITY_EDIT, {'form': form, 'user': user})

            username = f"{first_name.lower()}-{last_name.lower()}"

            if User.objects.filter(username__iexact=username).exclude(id=id).exists():
                messages.error(request, f"A user '{username}' exists.")
                return render(request, SECURITY_EDIT, {'form': form, 'user': user})

            user = form.save(commit=False)
            user.username = username
            if password:
                user.set_password(password)
            user.save()

            messages.success(request, "User updated successfully.")
            return redirect(SECURITY_SETTING)

        return render(request, SECURITY_EDIT, {'form': form, 'user': user})


class SecurityDeleteView(View):
    def post(self, request: HttpRequest, id: int):
        user = get_object_or_404(User, id=id)

        try:
            with transaction.atomic():
                user_name = user.get_full_name()
                user.delete()
                messages.success(request, f"Employe '{user_name}' has been successfully deleted.")
        except Exception as e:
            messages.error(
                request, f"An error occurred while deleting the employe: {str(e)}")

        return redirect(reverse(SECURITY_SETTING))
