import requests
from django.shortcuts import redirect, render
from django.contrib import messages
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
from urllib.parse import urlencode
import json
from authentication.models import User
from customer.models import Customer,Customer_Info ,Customernote
from myobconnect.models import MyobModel
from django.contrib.auth.hashers import make_password
from django.core import serializers
from myobconnect.views import refresh_token
from django.utils import timezone
from django.db.models import Q
import string
from leads.models import Lead



from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View

from quotation.models import Invoice,Quotation
from django.db.models import CharField, Value
from django.db.models.functions import Concat
from authentication.models import ActivityLog
from authentication.decorators import is_admin, is_sales, is_technician, is_customer,is_superuser
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import get_object_or_404
import os
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.contrib.auth.hashers import make_password
from dotenv import load_dotenv, find_dotenv
from authentication.models import User,Role
import random
from .models import Customer
from django.urls import reverse
load_dotenv(find_dotenv())
myob_customer_freightaxcode = os.environ.get('MYOB_Customer_FreightTaxCode')
myob_customer_taxcode = os.environ.get('MYOB_Customer_TaxCode')
from django.utils.timezone import localdate,now
from django.db.models import Max,Min
from django.db.models import Subquery, OuterRef
import csv


@method_decorator(csrf_exempt, name='dispatch')
class MarkNotesReadView(View):
    def post(self, request):
        today = localdate()  
        if request.user.is_authenticated:
            # Get user's roles
            user_roles = request.user.role.all().values_list('id', flat=True)

            # Allow update only if user has role 3
            if 3 in user_roles:
                Customernote.objects.filter(
                    deleted_at__isnull=True, 
                    is_read=0, 
                    assigned_to=request.user,
                    reminder_date__in=[today, None]  # Update only notes assigned to the user
                ).update(is_read=1)
                return JsonResponse({'status': 'success', 'message': 'Notes marked as read'})

            return JsonResponse({'status': 'error', 'message': 'Permission denied'}, status=403)

        return JsonResponse({'status': 'error', 'message': 'Unauthorized'}, status=403)
def export_customers_csv(request):
    # response = HttpResponse(content_type='text/csv')
    # response['Content-Disposition'] = 'attachment; filename="customers.csv"'

    # writer = csv.writer(response)
    # writer.writerow(['ID', 'Name', 'Email'])

    # for customer in Customer.objects.all():
    #     # dd(customer)
    #     writer.writerow([customer.id, customer.first_name+customer.last_name, customer.email])
    
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="customers.csv"'

    writer = csv.writer(response)
    writer.writerow(['ID','Customer Type','Position', 'Company Name','Customer Name ', 'Email','Phone','Address'])

    for customer in Customer.objects.all():
        # dd(customer)
        if customer.is_individual:
            cust_type = 'Individual'
            position = 'Customer'
        else:
            cust_type = 'Company'
            position = 'Director'
        address=customer.city+', '+customer.street+', '+customer.state+', '+customer.street+' '+customer.post_code+' '+customer.country;
        writer.writerow([customer.id,cust_type,position,customer.company_name, f"{customer.first_name} {customer.last_name}", customer.email,customer.phone1,address])
        if customer.get_cust_info:
            for customerinfo in  customer.get_cust_info:
                cust_type='Additional Contact'
                position=customerinfo.position
                writer.writerow([customerinfo.id,cust_type,position, customer.company_name,customerinfo.first_name+customerinfo.last_name, customerinfo.email,customerinfo.phone1,''])
               
    return response
def process_note_action(request, note_id):
    if request.method == "POST":
        action_type = request.POST.get("action_type")
        note = Customernote.objects.get(id=note_id)

        if action_type == "mark_read":
            note.is_read = True
            note.updated_by = request.user
            note.save()
            messages.success(request, "Note marked as read.")

        elif action_type == "update_log":
            new_log = request.POST.get("log_note")
            note.is_read = True
            note.updated_by = request.user
            note.save()
            Customernote.objects.create(
                customer=note.customer,
                groupid=request.POST.get("groupid"),
                note=new_log,
                created_by = request.user,
                assigned_to=note.assigned_to,
                created_at=now(),
            )
            messages.success(request, "New log added successfully.")

        elif action_type == "reschedule":
            new_date = request.POST.get("reschedule_date") or None
            note.reminder_date = new_date
            note.updated_by = request.user
            note.save()
            messages.success(request, "Reminder date updated.")

        return redirect("customer:note_list")  # Adjust this URL to match your project

    return JsonResponse({"status": "error", "message": "Invalid request"}, status=400)
def add_customer_note(request, id):
    customer = get_object_or_404(Customer, id=id)
    
    if request.method == "POST":
        note = request.POST.get("note")
        userid = request.POST.get("userid") or None
        reminder_date = request.POST.get("reminder_date") or None  # Optional field
        if not userid == None:
            assigned_user = get_object_or_404(User, id=userid)
        else:
            assigned_user=None
        
        last_group = Customernote.objects.order_by('-groupid').first()
        next_group_id = (last_group.groupid + 1) if last_group else 1
        
        Customernote.objects.create(
            customer=customer,
            note=note,
            reminder_date=reminder_date,
            created_by = request.user,
            assigned_to=assigned_user,
            groupid=next_group_id
        )

        messages.success(request, "Note added successfully!")
        return redirect('customer:list')  # Adjust to your actual view

    return redirect('customer:list')
@login_required
def note_customer(request, id):
    customer = get_object_or_404(Customer, pk=id)
   
    context={'customers': customer}
    # dd(invoice.get_history)
    # dd( customer.note_history)
    note = customer.note_history
    # dd(note)
    excluded_role_ids = [1,4,5]  #
    users = User.objects.filter(deleted_at__isnull=True,is_superuser=0).exclude(role__id__in=excluded_role_ids)
    
    return render(request, 'pages/customer/note.html', {'users':users,'notes':note})
@login_required
def note_list_customer(request):
    today = localdate()  
    user = request.user 
    excluded_role_ids = [1,4,5]  #
    users = User.objects.filter(deleted_at__isnull=True, is_superuser=0).exclude(role__id__in=excluded_role_ids)

    # note = Customernote.objects.filter(deleted_at__isnull=True)
   
    # users = User.objects.filter(deleted_at__isnull=True,is_superuser=0).exclude(role__id__in=excluded_role_ids)
    # Check user's role
    user_roles = user.role.all().values_list('id', flat=True)  # Get role IDs

    # Check role-based filtering
    if 1 in user_roles:
        # Role 1: Show all customer notes
        # notes = Customernote.objects.filter(deleted_at__isnull=True, reminder_date__in=[today, None]).order_by('-created_at')
        latest_notes = (
            Customernote.objects.filter(
                reminder_date__in=[today, None],
                deleted_at__isnull=True
            )
            .values('groupid')  # Group by groupid
            .annotate(lat_created_at=Max('created_at'))  # Get latest created_at per group
        )

        # Fetch actual notes matching the latest created_at per groupid
        notes =  Customernote.objects.filter(
            reminder_date__in=[today, None],
            deleted_at__isnull=True
        ).filter(
            Q(groupid__in=[note['groupid'] for note in latest_notes]),
            Q(created_at__in=[note['lat_created_at'] for note in latest_notes])
        ).order_by('-created_at') 
    elif 3 in user_roles:
        # Role 3: Show only notes assigned to the logged-in user
        # notes = Customernote.objects.filter(deleted_at__isnull=True, assigned_to__id=user.id, reminder_date__in=[today, None]).order_by('-created_at')
        latest_notes = (
            Customernote.objects.filter(
                reminder_date__in=[today, None],
                assigned_to__id=user.id,
                deleted_at__isnull=True
            )
            .values('groupid')  # Group by groupid
            .annotate(lat_created_at=Max('created_at'))  # Get latest created_at per group
        )

        # Fetch actual notes matching the latest created_at per groupid
        notes =  Customernote.objects.filter(
            reminder_date__in=[today, None],
            assigned_to__id=user.id,
            deleted_at__isnull=True
        ).filter(
            Q(groupid__in=[note['groupid'] for note in latest_notes]),
            Q(created_at__in=[note['lat_created_at'] for note in latest_notes])
        ).order_by('-created_at') 
    else:
        # Other roles: No access
        notes = Customernote.objects.none()
    if request.user.is_authenticated:
        user_roles = list(request.user.role.all().values_list('id', flat=True))
    else:
        user_roles = []
    # dd(user_roles)
    return render(request, 'pages/notification/note_list.html', {'users':users,'notes':notes,'user_roles':user_roles})
@login_required    
def update_customer_note(request,id):
    CustNote=Customernote.objects.get(id=id)
    if request.method == 'POST':
        reminder_date = request.POST.get("reminder_date") or None  # Optional field
        userid = request.POST.get("userid") or None
        if not userid == None:
            assigned_user = get_object_or_404(User, id=userid)
        else:
            assigned_user=None
        
        CustNote.note=request.POST.get("note")
        # dd(customer.user)
        CustNote.reminder_date=reminder_date
        CustNote.assigned_to=assigned_user
        CustNote.updated_by = request.user
        CustNote.save()
    messages.success(request, "Note updated successfully!")
    return redirect(reverse('customer:note_customer', args=[CustNote.customer.id]))
@login_required
def note_delete(request, id):
    # customer = CustNote.objects.get(id=id)
    # customer.deleted_by = request.user  
    # customer.delete()
    # id=2
    note = get_object_or_404(Customernote, id=id)
    note.deleted_by = request.user 
    note.soft_delete()
    # note.delete()
    messages.success(request, 'Customer Note Deleted Successfully.')
    return redirect(reverse('customer:note_customer', args=[note.customer.id])) 

def myhistory(row):
    if not row.model_name == 'Quotation' and not row.model_name == 'SerialNumber'  and not row.model_name == 'Invoice':
            result = []
            old = []
            newarr = []
            activity={}
            activity['model_name']=row.model_name
            activity['timestamp']=row.timestamp
            activity['activity_by'] = str(row.user.userinfo.get_name) if row.user and row.user.userinfo is not None else 'Admin'
            if row.action == 'Updated':
                a = json.dumps(row.new_data[0]['fields'])
                b = json.dumps( row.old_data[0]['fields'])
                a = json.loads(a)
                b = json.loads(b)
                for key in a:
                    if key != 'is_primary':
                        activity['action']='Updated'
                        replace=key

                        if key == 'primary_emails':
                            replace="Primary Email"
                            

                        if key not in b:
                            result.append(f'{dict({replace: a[key]})} -> {"replace deleted"}')
                            activity['log_activity']=f'{dict({replace: a[key]})} -> {"replace deleted"}'
                            # activity['log_activity']=f'Updated <b>{dict({key: b[key]})} </b> <b>{" Added"} </b>'

                        if key in a and key in b and a[key] != b[key] and a[key] != None and  b[key] != None and a[key] != '' and b[key] != ''  :


                            result.append(f'{dict({replace: a[key]})} -> {dict({replace: b[key]})}')
                            if not ( key == 'updated_at' or key == 'updated_at' or key == 'updated_by' or key == 'deleted_at'):
                                old.append(f'Updated {replace} From {a[key]} to {b[key]}')
                                activity['log_activity']=f'<b>{replace} </b> From   <b>{b[key]} </b> To  <b>{a[key]} </b>'
            if row.action == 'Deleted':
                result.append(f'Deleted')
                activity['log_activity']='Deleted'
                activity['action']='Deleted'
            if row.action == 'Created':
                result.append(f'Created')
                activity['log_activity']='Created'
                activity['action']='Created'
            return activity  
@user_passes_test(lambda u: is_admin(u) or is_superuser(u))
@login_required
def activity_customer(request, id):
    customer = get_object_or_404(Customer, pk=id)
   
    context={'customers': customer}
    # dd(invoice.get_history)
    
    history = customer.get_history
    t1=[]
    if history:
        
        for cus in history:
           
            t=myhistory(cus)

            if t is not None:
               t1.append(t)
    counter = 1

    for cust in t1:
        if 'log_activity' in cust and cust['log_activity'] is not None and cust['log_activity'] != ''  :
            cust['row_number'] = counter
            counter += 1
    return render(request, 'pages/customer/activity.html', {'t1':t1,'counter':counter})




@login_required
def list_customer(request):
    env_vars = os.environ
    for key, value in env_vars.items():
        print(f"{key}: {value}")
    customer_id = request.GET.get('customer_id')
    email = request.GET.get('email')
    phone = request.GET.get('phone')
    status = request.GET.get('status')
    customer=Customer.objects.filter(deleted_at__isnull=True)
    # customer = Customer_Info.objects.filter(customer__in=customer_data, is_primary=True)

    
    if customer_id:
        customer = Customer.objects.filter(Q(id=customer_id) )
              
    if email:
        email = request.GET.get('email').strip()
        customer = customer.filter(email__icontains=email)

    if phone:
        phone = request.GET.get('phone').strip()
        customer = customer.filter(phone1__icontains=phone)
    if status:
        customer = customer.filter(is_active=status)
        
    
    total_records = customer.count()
    show_pagination = total_records > settings.PAGE_RECORDS


    if show_pagination:     

        page = request.GET.get('page', 1)
        paginator = Paginator(customer, settings.PAGE_RECORDS)  # Show 10 customers per page
        try:
            customer = paginator.page(page)
        except PageNotAnInteger:
            customer = paginator.page(1)
        except EmptyPage:
            customer = paginator.page(paginator.num_pages)
    excluded_role_ids = [1,4,5]  #
    users = User.objects.filter(deleted_at__isnull=True,is_superuser=0).exclude(role__id__in=excluded_role_ids)
    return render(request,'pages/customer/list.html', {'users':users,'customers': customer,'cust':Customer.objects.filter(deleted_at__isnull=True)})


@login_required
def create_customer(request):
    return render(request,'pages/customer/create.html')


@login_required
def post_customer(request):
    
    context={}
    refresh_token(request)
    print(refresh_token)
    myobdata = MyobModel.objects.first()
    if not myobdata:
        messages.error(request,'Please First create Access Code')
        return redirect('/myob/initiate-connection')
    
    api_url = f"https://ar2.api.myob.com/accountright/{settings.COMPANY_FILE_ID}/Contact/Customer"
    if request.method == 'POST':

        # dd(request.POST)
        form = request.POST
        context['first_name_0'] = request.POST.getlist('first_name')[0]
        context['last_name_0'] = request.POST.getlist('last_name')[0]
        context['email_0'] = request.POST.getlist('email')[0]
        context['phone1_0'] = request.POST.getlist('phone1')[0]
        context['is_sent_creadentials_0']=request.POST.getlist('send_credentials[]')[0]
        customer_type=form.customer_type = request.POST.get('customer_type')
        first_names = request.POST.getlist('first_name')
        last_names = request.POST.getlist('last_name')
        positions = request.POST.getlist('position')
        emails = request.POST.getlist('email')
        app_access = request.POST.getlist('app_access[]')
        is_sent_creadentials=request.POST.getlist('send_credentials[]')
        is_communication=request.POST.getlist('receive_emails[]')
        primary_email = emails[0]
        phone_numbers = request.POST.getlist('phone1')
        is_active= request.POST.get('is_active')
        # dd(form)

        if is_active is None:
           is_active = False
        else:
            is_active = True

        for e in range(len(emails)):
            # dd(app_access)
            if app_access[e] is None:
                pass
            else:
                if User.objects.filter(email=emails[e]).exists():
                    if User.objects.filter(email=emails[e],deleted_at__isnull=False).exists():
                        pass
                    else:
                        messages.error(request, 'Email Id already exists.')
                        context['form'] = form
                        
                        # dd(form.first_name[0])=request.POST.getlist('first_name')[0]
                        return render(request, 'pages/customer/create.html', context)
                    
        app_accesss=0
        is_sent_creadentials1=0
        is_communication1=0
        if app_access[0] == 'on':
            app_accesss=1
        if is_sent_creadentials[0] == 'on':
            is_sent_creadentials1=1
        if is_communication[0] == 'on':
            is_communication1=1
        user=User.objects.filter(email=primary_email,deleted_at__isnull = False).exists()
        if user:
            user=User.objects.get(email=primary_email,deleted_at__isnull = False)
            # user.is_active=1 if is_active else 0
            user.is_active=is_active
            user.username=primary_email
            user.app_access=1
            user.isprimary=1
            # customer=customer
            user.deleted_at=None
            user.is_communication=1
            user.reset_password=0
            user.email=primary_email
            user.deleted_at=None
            user.save()
        else:
            user = User.objects.create(
                is_active=is_active,
                username=primary_email,
                app_access=1,
                isprimary=1,
                # customer=customer,
                is_communication=1,
                reset_password=0,
                email=primary_email,
            )
        user.role.set('4')
        new_password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
        user.set_password('Excitech@123')
        user.save()
        if is_sent_creadentials1 == 1:
            # send credentials to primary_email
            
            subject = f'EXCITECH Australia - Your Account Credentials'
            username= primary_email  #user.email
            password="Excitech@123"
            template_data = {'password': password,'username':username}
            message = render_to_string('pages/customer/cust_email_temp.html', template_data)
    
            # message += "Please find attached Quote."
            
            from_email = settings.FROM_EMAIL
        
            recipient_email =primary_email #user.email 
        
            email = EmailMessage(subject, message, from_email, [recipient_email])
           
            email.content_subtype = 'html'
            email.send()
            done=1
            if done:
                user.is_sent_creadentials= 1
                user.reset_password=1
                user.save()
        print('here')

        customer_data = {
            'customer':user,
            'is_active':is_active,
            'street': request.POST.get('street'),
            'city': request.POST.get('city'),
            'state': request.POST.get('state'),
            'post_code': request.POST.get('post_code'),
            'country': request.POST.get('country'),

            'phone2': request.POST.get('phone2'),
            'phone3': request.POST.get('phone3'),
            'fax': request.POST.get('fax'),

            'website': request.POST.get('website'),
            'contact_name': request.POST.get('contact_name'),
            'salutation': request.POST.get('salutation'),
            'abn': request.POST.get('abn'),

            }
        if customer_type == '1':

            customer = Customer(
                user=user,
                is_individual=int(customer_type),
                first_name=first_names[0],
                last_name=last_names[0],
                phone1=phone_numbers[0],
                email=emails[0],

                is_primary=1,

                **customer_data,
                created_by=request.user,
            )
            customer.lead_id=request.POST.get('lead_id') or None
            customer.primary_mail=primary_email
            customer.save()
            if request.POST.get('lead_id'):
                lead = Lead.objects.get(id=request.POST.get('lead_id'))
                lead.customer_id=customer.id
                lead.save()

        else:

            company_name = request.POST.get('company_name')
            customer = Customer(
                user=user,
                is_individual=int(customer_type),
                company_name=company_name,
                first_name=first_names[0],
                last_name=last_names[0],
                phone1=phone_numbers[0],
                email=emails[0],
                is_primary=1,

                **customer_data,
                created_by=request.user,
                updated_by=request.user,
            )
            customer.lead_id=request.POST.get('lead_id') or None
            customer.primary_mail=primary_email
            customer.save()
            if request.POST.get('lead_id'):
                lead = Lead.objects.get(id=request.POST.get('lead_id'))
                lead.customer_id=customer.id
                lead.save()
            
        customer_info = []
        
        
       
        for e in range(1, len(emails)):
            customer_info = []
            app_accesss=0
            is_sent_creadentials1=0
            is_communication1=0
            if app_access[e] == 'on':
                app_accesss=1
            if is_sent_creadentials[e] == 'on':
                is_sent_creadentials1=1
            if is_communication[e] == 'on':
                is_communication1=1
            user=User.objects.filter(email=primary_email,deleted_at__isnull=False).exists()
            if user:
                user.username=emails[e]
                user.email=emails[e]
                user.app_access=app_accesss
                user.isprimary=0
                user.is_sent_creadentials= 0 
                # customer=customer
                user.deleted_at=None
                user.is_communication=is_communication1
                user.reset_password=0
                user.save()
            else:
                user = User.objects.create(
                    is_active=is_active,
                    username=emails[e],
                    email=emails[e],
                    app_access=app_accesss,
                    isprimary=0,
                    is_sent_creadentials= 0 ,
                    # customer=customer,
                    is_communication=is_communication1,
                    reset_password=0
                )
            user.role.set('4')
            new_password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
            user.set_password('Excitech@123')
            user.save()
            if is_sent_creadentials1 == 1:
                # send email to kiran@beedev.co.in
                subject = f'EXCITECH Australia - Your Account Credentials'
                username= emails[e]  #user.email
                password="Excitech@123"
                template_data = {'password': password,'username':username}
                message = render_to_string('pages/customer/cust_email_temp.html', template_data)
        
                # message += "Please find attached Quote."
                
                from_email = settings.FROM_EMAIL
            
                recipient_email =emails[e] #user.email 
            
                email = EmailMessage(subject, message, from_email, [recipient_email])
               
                email.content_subtype = 'html'
                email.send()
                            
                done=1
                if done:
                    user.is_sent_creadentials= 1 
                    user.reset_password=1
                    user.save()
            customer_detail = Customer_Info(
                customer=customer,
                first_name=first_names[e],
                last_name=last_names[e],
                email=emails[e],
                phone1=phone_numbers[e],
                position=positions[1-e],
                is_primary=0,
                user=user
            )
            customer_info.append(customer_detail)
            Customer_Info.objects.bulk_create(customer_info)
        # Bulk create the remaining customer details
        # Customer_Info.objects.bulk_create(customer_info)


        customers=Customer.objects.filter(created_by=request.user).last()
        if customers.abn  and len(customers.abn ) == 11:
            abnres = f"{customers.abn[:2]} {customers.abn[2:5]} {customers.abn[5:8]} {customers.abn[8:]}"
        else:
            abnres=customers.abn
    
        customer_data={
            "LastName" :customers.last_name,
            "FirstName" : customers.first_name,
           "Addresses" : [
                {
                 "Location" : 1,
            "Street" : customers.street,
            "City" : customers.city,
            "State" : customers.state,
            "PostCode" : customers.post_code,
            "Country" : customers.country,
            "Phone1" : customers.phone1,
            "Phone2" : customers.phone2,
            "Phone3" : customers.phone3,
            "Fax" : customers.fax,
            "Email" : customers.email,
            "Website" : customers.website,
            "ContactName" : customers.contact_name,
            "Salutation" : customers.salutation
                }
            ],
            "IsIndividual" : customers.is_individual,
            "IsActive" : customers.is_active  ,
            
            "SellingDetails" : {
            "SaleLayout" : "NoDefault",
            "InvoiceDelivery" : "Print",
            "TaxCode" : {
                "UID": myob_customer_taxcode,
                    "Code" : "GST",
                    "URI": "https://arl2.api.myob.com/accountright/ed1538a2-94c4-4188-81c6-c21ee5bff73c/GeneralLedger/Account/ba60da97-26df-4700-9435-3752f65c2826"       
                    
                        
                    },
            "FreightTaxCode" : {
                    "UID": myob_customer_freightaxcode,
                    "Code" : "GST",
                    "URI": "https://arl2.api.myob.com/accountright/ed1538a2-94c4-4188-81c6-c21ee5bff73c/GeneralLedger/Account/ba60da97-26df-4700-9435-3752f65c2826"       
                    },
            "ABN":abnres,
            }
                

        }

        if not customers.is_individual:
            customer_data["CompanyName"] = customers.company_name


        headers = {
            'Authorization': f'Bearer {myobdata.access_token}',
            'x-myobapi-key': settings.MYOB_CLIENT_ID,
            'x-myobapi-version': 'v2',
            'Content-Type': 'application/json',
            'Accept-Encoding': 'gzip,deflate'
        }

        customer_json = json.dumps(customer_data)
        try:
            response = requests.post(api_url, data=customer_json, headers=headers)
            data=response.headers

            if response.status_code == 201:
                location = data['Location']
                if location:
                    parts = location.split('/')
                    uid = parts[-1]
                    customers.myob_location = location
                    customers.myob_uid = uid
                    customers.save()
                    messages.success(request, 'Customer Added Successfully.')
                    return redirect('customer:list')
                else:
                    messages.error(request, 'Location header not found in API response.')
            else:
                messages.error(request, 'Failed To Added Customer.')

        except requests.exceptions.RequestException as e:
            messages.error(request, f'An error occurred: {str(e)}')
        return redirect('customer:list')        
    else:      
        context['form'] = {}
        context['users']= Customer.objects.all()
        return render(request, 'pages/customer/create.html', context)

        
def reset_password_contact(request,id):
    user=User.objects.filter(id=id).first()
    if not user:
        # return HttpResponse('User not found.')
        messages.error(request, 'User not found.')
        return redirect('customer:list')
    subject = f'EXCITECH Australia - Your New Credentials Are Here'
    username= user.email 
    print(username)
    new_password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
    user.set_password(new_password)
    user.is_sent_creadentials=1
    user.reset_password=1
    user.save()
    
    template_data = {'password': new_password,'username':username}
    message = render_to_string('pages/customer/cust_email_temp.html', template_data)

    from_email = settings.FROM_EMAIL
    recipient_email =username #user.email 

    email = EmailMessage(subject, message, from_email, [recipient_email])
   
    email.content_subtype = 'html'
    email.send()
    messages.success(request, 'New credentials sent to Customer email.')
    return redirect('customer:list')
def reset_password(request,id):
    # kiran@beedev.co.in reset password
    cust = Customer.objects.filter(id=id).first()
    if cust:
        user=User.objects.filter(id=cust.user.id).first()
        if not user:
            # return HttpResponse('User not found.')
            messages.error(request, 'User not found.')
            return redirect('customer:list')
    else:
        messages.error(request, 'Customer not found.')
        return redirect('customer:list')
    subject = f'EXCITECH Australia - Your New Credentials Are Here'
    username= cust.user.email 
    print(username)
    new_password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
    user.set_password(new_password)
    user.is_sent_creadentials=1
    user.reset_password=1
    user.save()
    
    template_data = {'password': new_password,'username':username}
    message = render_to_string('pages/customer/cust_email_temp.html', template_data)

    from_email = settings.FROM_EMAIL
    recipient_email =username # 'kiran@beedev.co.in' #username #user.email 

    email = EmailMessage(subject, message, from_email, [recipient_email])
   
    email.content_subtype = 'html'
    email.send()
    messages.success(request, 'New credentials sent to Customer email.')
    return redirect('customer:list')
    # return HttpResponse('New credentials sent to your email.')

@login_required    
def edit_customer(request,id):
    refresh_token(request)
    myobdata = MyobModel.objects.first()
    if not myobdata:
        messages.error(request,'Please First create Access Code')
        return redirect('/myob/initiate-connection')
    customer = Customer.objects.get(id=id)
    customer_info =Customer_Info.objects.filter(customer=customer)
    UID=customer.myob_uid
    print(UID)
    api_url = f"https://ar2.api.myob.com/accountright/{settings.COMPANY_FILE_ID}/Contact/Customer/{UID}"
    context={}
    if request.method == 'POST':
        # dd(request.POST)
        form = request.POST
        customer_type = request.POST.get('customer_type')
        is_active=request.POST.get('is_active')
        if is_active is None:
           is_active = False
        else:
            is_active = True

        first_names = request.POST.getlist('first_name')
        last_names = request.POST.getlist('last_name')
        positions = request.POST.getlist('position')
        is_primary= request.POST.getlist('is_primary')
        customer_info_id  = request.POST.getlist('customer_info_id[]')
        emails = request.POST.getlist('email[]')
        phone_numbers = request.POST.getlist('phone1')
        delete_list = request.POST.getlist('deleted[]')
        app_access = request.POST.getlist('app_access[]')
        is_sent_creadentials=request.POST.getlist('send_credentials[]')
        is_communication=request.POST.getlist('receive_emails[]')
        primary_email = emails[0]
        
        # if 'True' not in is_primary:
        #     messages.error(request, 'Please select at least one primary email.')
        #     context['form'] = form
        #     return redirect('customer:edit' ,id )
            
        # index_of_true = is_primary.index('True')
      
        # if is_primary[index_of_true]:
        #     customer.primary_mail=primary_email
        #     print(f"{primary_email} is marked as primary.")
        # else:
        #     print(f"{primary_email} is not marked as primary.")
        
        for e in range(0,len(emails)):
            # dd(app_access)
            # print(len(emails))
            if app_access[e] is None:
                print('not exist')
                pass
            else:
                if e == 0:
                    print('00')
                    if User.objects.filter(email=primary_email).exclude(id=customer.user.id).exists():
                        if User.objects.filter(email=primary_email,deleted_at__isnull=False).exclude(id=customer.user.id).exists():
                            # pass
                            messages.error(request,  f'User With Email {primary_email} Is Already Exists.')
                            return redirect('customer:edit' ,id )
                        else:
                            messages.error(request,  f'User With Email {primary_email} Is Already Exists.')
                            return redirect('customer:edit' ,id )
                            
                else:
                    c=Customer_Info.objects.filter(email=emails[e],customer=customer).first()
                    # print(emails[e])
                    # print(customer)
                    # print(c)
                    if c:
                        if Customer_Info.objects.filter(email=emails[e]).exclude(id=c.id).exists():
                            # print('exist')
                            messages.error(request,  f'User With Email {primary_email} Is Already Exists.')
                            return redirect('customer:edit' ,id )
        
        user=User.objects.get(id=customer.customer.id)
        # if User.objects.filter(email=primary_email).exclude(id=customer.user.id).exists():
        #     if User.objects.filter(email=primary_email,deleted_at__isnull=False).exclude(id=customer.user.id).exists():
        is_sent_creadentials1=user.is_sent_creadentials
        if is_sent_creadentials[0] == '1':
            is_sent_creadentials1=1
        if user.email == primary_email:
            # dd('if')
            user.email=primary_email 
            user.is_active=is_active
            user.username=primary_email
            user.app_access=1
            user.isprimary=1
            deleted_at=None
            user.is_communication=1
            user.save() 
        else:
            # user.soft_delete()
            # user=User.objects.get(email=primary_email)
            # dd(user.id)
            user.email=primary_email 
            user.is_active=is_active
            user.username=primary_email
            user.app_access=1
            user.deleted_at=None
            user.isprimary=1
            deleted_at=None
            user.is_communication=1
            user.save() 
        # print(is_sent_creadentials[0])
        if is_sent_creadentials[0] == '1':
            # print(primary_email)
            subject = f'EXCITECH Australia - Your Account Credentials'
            username= primary_email  #user.email
            password="Excitech@123"
            template_data = {'password': password,'username':username}
            message = render_to_string('pages/customer/cust_email_temp.html', template_data)
            # message += "Please find attached Quote."
            from_email = settings.FROM_EMAIL
            recipient_email =primary_email #user.email 
            email = EmailMessage(subject, message, from_email, [recipient_email])
            email.content_subtype = 'html'
            email.send()
            done=1
            if done:
                user.is_sent_creadentials= 1
                user.reset_password=1
                user.save()

        if customer_type=="1":
            customer.first_name =first_names[0]
            customer.last_name = last_names[0]
            # Set other individual fields
        else:
            customer.first_name =first_names[0]
            customer.last_name = last_names[0]
            customer.company_name = request.POST.get('company_name')

        customer.user=user
        # dd(customer.user)
        customer.is_primary=is_primary[0]
        customer.is_active=is_active
        customer.street = request.POST.get('street')
        customer.city = request.POST.get('city')
        customer.state = request.POST.get('state')
        customer.post_code = request.POST.get('post_code')
        customer.country = request.POST.get('country')
        customer.phone1 = phone_numbers[0]
        customer.phone2 = request.POST.get('phone2')
        customer.phone3 = request.POST.get('phone3')
        customer.fax = request.POST.get('fax')
        customer.email = emails[0]
        customer.website = request.POST.get('website')
        customer.contact_name = request.POST.get('contact_name')
        customer.salutation = request.POST.get('salutation')
        customer.abn = request.POST.get('abn')
        customer.customer = user
        customer.updated_by = request.user

        if customer.abn  and len(customer.abn ) == 11:
            abnres = f"{customer.abn[:2]} {customer.abn[2:5]} {customer.abn[5:8]} {customer.abn[8:]}"
        else:
            abnres=customer.abn
        customer.save()    

        # Update customer_info records
        if  delete_list:
            # dd(delete_list)
            for i in range(len(delete_list)):
                deleted_value =delete_list[i]
                if deleted_value == 0   or   deleted_value =='' :
                    pass
                else:
                    c=Customer_Info.objects.filter(id=deleted_value).first()
                    # dd(c)
                    if c:
                        u=User.objects.get(id=c.user.id)
                        u.deleted_at = timezone.now()
                        u.save()
                        customerdetail = Customer_Info.objects.filter(id=deleted_value).delete()

        cus_infos = []

        for i in range(1,len(first_names)):
            # try:
            #     # Try to get an existing customer_info record
            # dd(emails)
            if  customer_info_id[i] != '0' :
                print(emails[i])
                # customer_detail = Customer_Info.objects.get( customer=customer,first_name=first_names[i],last_name=last_names[i])
                customer_detail = Customer_Info.objects.get(customer=customer,id=customer_info_id[i])
                app_accesss=customer_detail.user.app_access
                is_sent_creadentials1=customer_detail.user.is_sent_creadentials
                is_communication1=customer_detail.user.is_communication
                # dd(app_access[i])
                # dd(request.POST)
                
                if is_sent_creadentials[i] == '1':
                    is_sent_creadentials1=1
                # if is_communication[i] == 1:
                #     is_communication1=1

                # Update customer_info fields for existing record
                customer_detail.email = emails[i]
                customer_detail.first_name = first_names[i]
                customer_detail.last_name = last_names[i]
                customer_detail.phone1 = phone_numbers[i]
                customer_detail.position = positions[1-i]

                customer_detail.is_primary = 0
                customer_detail.save()
                u=User.objects.filter(id=customer_detail.user.id).first()
                # dd(u)
                u.app_access=app_access[i]
                u.email=emails[i]
                u.deleted_at=None
                u.username=emails[i]
                u.is_communication=is_communication[i]
                # dd(is_communication1)
                u.save()
                if is_sent_creadentials[i] == '1':
                    # send email to kiran@beedev.co.in
                    subject = f'EXCITECH Australia - Your Account Credentials'
                    username= emails[i]  #user.email
                    password="Excitech@123"
                    template_data = {'password': password,'username':username}
                    message = render_to_string('pages/customer/cust_email_temp.html', template_data)
                    # message += "Please find attached Quote."
                    from_email = settings.FROM_EMAIL
                    recipient_email =emails[e] #user.email 
                    email = EmailMessage(subject, message, from_email, [recipient_email])
                    email.content_subtype = 'html'
                    email.send()
                    done=1
                    if done:
                        user.is_sent_creadentials= 1 
                        user.reset_password=1
                        user.save()
            else:
                user=User.objects.filter(email=emails[i]).first()
                if user:
                    user.app_access=app_access[i]
                    user.email=emails[i]
                    user.deleted_at=None
                    user.username=emails[i]
                    user.is_communication=is_communication[i]
                    # dd(is_communication1)
                    user.save()
                else:
                    user = User.objects.create(
                        username=emails[i],
                        email=emails[i],
                        app_access=app_access[i],
                        is_communication=is_communication[i]
                    )
                user.role.set('4')
                new_password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
                user.set_password('Excitech@123')
                user.save()
                 
                if is_sent_creadentials[i] == '1':
                    # send email to kiran@beedev.co.in
                    subject = f'EXCITECH Australia - Your Account Credentials'
                    username= emails[i]  #user.email
                    password="Excitech@123"
                    template_data = {'password': password,'username':username}
                    message = render_to_string('pages/customer/cust_email_temp.html', template_data)
                    # message += "Please find attached Quote."
                    from_email = settings.FROM_EMAIL
                    recipient_email =emails[e] #user.email 
                    email = EmailMessage(subject, message, from_email, [recipient_email])
                    email.content_subtype = 'html'
                    email.send()
                                
                    done=1
                    if done:
                        user.is_sent_creadentials= 1 
                        user.reset_password=1
                        user.save()

                customer_detail = Customer_Info(
                    customer=customer,
                    email=emails[i],
                    first_name=first_names[i],
                    last_name=last_names[i],
                    phone1=phone_numbers[i],
                    position=positions[1-i],
                    is_primary=0,
                    user=user

                )
        
                # Save the new customer_info record
                customer_detail.save()
        
            # Append the customer_info instance to the list
            cus_infos.append(customer_detail)

        headers = {
            'Authorization': f'Bearer {myobdata.access_token}',
            'x-myobapi-key': settings.MYOB_CLIENT_ID,
            'x-myobapi-version': 'v2',
            'Content-Type': 'application/json',
            'Accept-Encoding': 'gzip,deflate'
        }


        if UID:
      
            response = requests.get(api_url, headers=headers)
            response_json = response.json()
            current_row_version = response_json.get('RowVersion')


            customer_data={
                "RowVersion": current_row_version,
                "UID":customer.myob_uid,
                "LastName" :customer.last_name,
                "FirstName" : customer.first_name,
                "Addresses" : [
                {
                 "Location" : 1,
            "Street" : customer.street,
            "City" : customer.city,
            "State" : customer.state,
            "PostCode" : customer.post_code,
            "Country" : customer.country,
            "Phone1" : customer.phone1,
            "Phone2" : customer.phone2,
            "Phone3" : customer.phone3,
            "Fax" : customer.fax,
            "Email" : customer.email,
            "Website" : customer.website,
            "ContactName" : customer.contact_name,
            "Salutation" : customer.salutation
                }
            ],
                "IsIndividual" : customer.is_individual,
                "IsActive" : customer.is_active  ,
             
                "SellingDetails" : {
            
                    "TaxCode" : {
                        "UID": myob_customer_taxcode,
                    
                        
                            
                                
                                },
                    "FreightTaxCode" : {
                                "UID": myob_customer_freightaxcode,
                                
                                },
                    "ABN": abnres,
                        },


                "BuyingDetails" : {
            
                    "TaxCode" : {
                        "UID": myob_customer_taxcode,
                    
                        
                            
                                
                                },
                        "FreightTaxCode" : {
                                "UID": myob_customer_freightaxcode,
                                
                                },
                        }

                                

                    }

            if not customer.is_individual:
                customer_data["CompanyName"] = customer.company_name

            customer_json = json.dumps(customer_data)
            response = requests.put(api_url, data=customer_json, headers=headers)
            data=response.headers

            if response.status_code == 200:
                location = data['Location']
                print(location)
                if location:
                    parts = location.split('/')
                    uid = parts[-1]
                    customer.myob_location = location
                    customer.current_row_version=current_row_version
                    customer.myob_uid = uid
                    customer.updated_by=request.user
                    customer.save()
                messages.success(request, 'Customer Updated Successfully')
                return redirect('customer:list')
            else:
                messages.error(request, 'Failed To Update Customer.')
                return redirect('customer:create')
        else:
            messages.success(request, 'Customer Updated Successfully.')
            return redirect('customer:list')

    return render(request,'pages/customer/edit.html',{'customer': customer,'customer_info':customer_info})

def show_customer(request,id):
    refresh_token(request)
    myobdata = MyobModel.objects.first()
    if not myobdata:
        messages.error(request,'Please First create Access Code')
        return redirect('/myob/initiate-connection')
    customer = Customer.objects.get(id=id)
    customer_info =Customer_Info.objects.filter(customer=customer)
    UID=customer.myob_uid
    print(UID)
    api_url = f"https://ar2.api.myob.com/accountright/{settings.COMPANY_FILE_ID}/Contact/Customer/{UID}"
    context={}
    
    return render(request,'pages/customer/show.html',{'customer': customer,'customer_info':customer_info})
    

def sync_myob_customer(request, id):

    refresh_token(request)
    myobdata = MyobModel.objects.first()
    if not myobdata:
        messages.error(request,'Please First create Access Code')
        return redirect('/myob/initiate-connection')
    
    customers = Customer.objects.get(id=id)
    api_url = f"https://ar2.api.myob.com/accountright/{settings.COMPANY_FILE_ID}/Contact/Customer/"

    headers = {
        'Authorization': f'Bearer {myobdata.access_token}',
        'x-myobapi-key': settings.MYOB_CLIENT_ID,
        'x-myobapi-version': 'v2',
        'Content-Type': 'application/json',
        'Accept-Encoding': 'gzip,deflate'
    }

    if customers.abn  and len(customers.abn ) == 11:
        abnres = f"{customers.abn[:2]} {customers.abn[2:5]} {customers.abn[5:8]} {customers.abn[8:]}"
    else:
        abnres=customers.abn
 
    customer_data={
            "LastName" :customers.last_name,
            "FirstName" : customers.first_name,
            "Addresses" : [
                {
                 "Location" : 1,
            "Street" : customers.street,
            "City" : customers.city,
            "State" : customers.state,
            "PostCode" : customers.post_code,
            "Country" : customers.country,
            "Phone1" : customers.phone1,
            "Phone2" : customers.phone2,
            "Phone3" : customers.phone3,
            "Fax" : customers.fax,
            "Email" : customers.email,
            "Website" : customers.website,
            "ContactName" : customers.contact_name,
            "Salutation" : customers.salutation
                }
            ],
           
            "IsIndividual" : customers.is_individual,
            "IsActive" : customers.is_active  ,
            
            "SellingDetails" : {
            "SaleLayout" : "Item",
            "InvoiceDelivery" : "Print",
            "TaxCode" : {
                "UID": myob_customer_taxcode,
                    "Code" : "GST",
                    "URI": "https://arl2.api.myob.com/accountright/ed1538a2-94c4-4188-81c6-c21ee5bff73c/GeneralLedger/Account/ba60da97-26df-4700-9435-3752f65c2826"       
                    
                        
                    },
            "FreightTaxCode" : {
                    "UID": myob_customer_freightaxcode,
                    "Code" : "GST",
                    "URI": "https://arl2.api.myob.com/accountright/ed1538a2-94c4-4188-81c6-c21ee5bff73c/GeneralLedger/Account/ba60da97-26df-4700-9435-3752f65c2826"       
                    },
            "ABN":abnres,
            }
                

        }

    if not customers.is_individual:
        customer_data["CompanyName"] = customers.company_name

    customer_json = json.dumps(customer_data)
    response = requests.post(api_url, data=customer_json, headers=headers)

    data=response.headers
    print(customer_json)
    print(response)
    if response.status_code == 201:
        location = data['Location']
        if location:
            parts = location.split('/')
            uid = parts[-1]
            customers.myob_location = location
            customers.myob_uid = uid
            customers.updated_by=request.user
            customers.save()
        messages.success(request, 'Customer successfully Sync Myob.')
        return redirect('customer:list')
    else:
        messages.error(request, 'Failed to update customer.')
        return redirect('customer:list')

def sync_myob_customer_all(request):

    refresh_token(request)
    myobdata = MyobModel.objects.first()
    if not myobdata:
        messages.error(request,'Please First create Access Code')
        return redirect('/myob/initiate-connection')

    customers = Customer.objects.filter(myob_uid=None)
    api_url = f"https://ar2.api.myob.com/accountright/{settings.COMPANY_FILE_ID}/Contact/Customer/"

    headers = {
        'Authorization': f'Bearer {myobdata.access_token}',
        'x-myobapi-key': settings.MYOB_CLIENT_ID,
        'x-myobapi-version': 'v2',
        'Content-Type': 'application/json',
        'Accept-Encoding': 'gzip,deflate'
    }

    for customer in customers:
        if customer.abn  and len(customer.abn ) == 11:
            abnres = f"{customer.abn[:2]} {customer.abn[2:5]} {customer.abn[5:8]} {customer.abn[8:]}"
        else:
            abnres=customer.abn
        customer_data={
            # "RowVersion": current_row_version,
            # "UID":customer.myob_uid,
            "LastName" :customer.last_name,
            "FirstName" : customer.first_name,
            "Addresses" : [
                {
                 "Location" : 1,
            "Street" : customer.street,
            "City" : customer.city,
            "State" : customer.state,
            "PostCode" : customer.post_code,
            "Country" : customer.country,
            "Phone1" : customer.phone1,
            "Phone2" : customer.phone2,
            "Phone3" : customer.phone3,
            "Fax" : customer.fax,
            "Email" : customer.email,
            "Website" : customer.website,
            "ContactName" : customer.contact_name,
            "Salutation" : customer.salutation
                }
            ],
            "IsIndividual" : customer.is_individual,
            "IsActive" : customer.is_active  ,
           
            "SellingDetails" : {
            "SaleLayout" : "NoDefault",
            "InvoiceDelivery" : "Print",
            "TaxCode" : {
                "UID": myob_customer_taxcode,
                    "Code" : "GST",
                    "URI": "https://arl2.api.myob.com/accountright/ed1538a2-94c4-4188-81c6-c21ee5bff73c/GeneralLedger/Account/ba60da97-26df-4700-9435-3752f65c2826"       
                    
                        
                        },
                "FreightTaxCode" : {
                        "UID": myob_customer_freightaxcode,
                        "Code" : "GST",
                        "URI": "https://arl2.api.myob.com/accountright/ed1538a2-94c4-4188-81c6-c21ee5bff73c/GeneralLedger/Account/ba60da97-26df-4700-9435-3752f65c2826"       
                        },
                 "ABN":abnres,
                }
                    

            }

        if not customer.is_individual:
            customer_data["CompanyName"] = customer.company_name

        customer_json = json.dumps(customer_data)
        response = requests.post(api_url, data=customer_json, headers=headers)

        data=response.headers
        if response.status_code == 201:
            location = data['Location']
            if location:
                parts = location.split('/')
                uid = parts[-1]
                customer.myob_location = location
                customer.myob_uid = uid
                customer.updated_by=request.user
                customer.save()
            messages.success(request, 'Customer successfully Sync Myob.')
            return redirect('customer:list')
        else:
            messages.error(request, 'Failed to update customer.')
            return redirect('customer:list')
   


@login_required
def delete_customer(request, id):
    customer = Customer.objects.get(id=id)
    u=User.objects.get(id=customer.user.id)
    u.soft_delete()
    customer.deleted_by = request.user  
    customer.delete()
    
    
    messages.success(request, 'Customer Deleted Successfully.')
    return redirect('customer:list')

@login_required
def delete_customer_contact(request, id):
    c=Customer_Info.objects.filter(id=id).first()
    # dd(c)
    if c:
        u=User.objects.get(id=c.user.id)
        # u.deleted_at = timezone.now()
        u.soft_delete()
        c.deleted_by = request.user  
        c.save()
        customerdetail = Customer_Info.objects.filter(id=id).delete()
    messages.success(request, 'Customer Deleted Successfully.')
    return redirect('customer:list')
    # customer = Customer.objects.get(id=id)
    # customer.deleted_by = request.user  
    # customer.soft_delete()
   

