from django.shortcuts import render, get_object_or_404
from .decorators import *
from billing.models import *
from billing.add.views import *
from .models import *
from django.db.models import Q
from django.http import Http404
from django.db.models import OuterRef, Subquery
from customercore.views import *
from django.contrib.auth.hashers import check_password
from django.contrib.auth import update_session_auth_hash, logout
import json
from support .models import *



# Create your views here.
@customer_login_required
def redirect_osimenu(request):
    user_email = request.user.email
    key = 'pbkdf2_sha256600000'
    url = f"https://osimenu.com/login/{user_email}/{key}/"
    return redirect(url)


@customer_login_required
def redirect_osicard(request):
    user_email = request.user.email
    key = 'pbkdf2_sha256600000'
    url = f"https://mybusinesscardpage.com/login/{user_email}/{key}/"
    return redirect(url)


@customer_login_required
def contact(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'contact.html', context)



# LISTING
@customer_login_required
def customer_invoices(request, *args, **kwargs):
    invoices = Invoice.objects.filter(order__customer = request.user.customerprofile)


    context = {
        'invoices' : invoices,
    }

    return render(request, 'listing_pages/customer-invoices.html', context)


@customer_login_required
def all_products(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'listing_pages/products.html', context)



@customer_login_required
def customer_orders(request, *args, **kwargs):
    customer = request.user.customerprofile
    orders = Order.objects.filter(customer=customer, orderstatus__isnull=False).order_by('-order_id')

    
    context = {
        'orders': orders,
    }

    return render(request, 'listing_pages/customer-orders.html', context)


def customer_order_details(request, order_id):
    order = get_object_or_404(Order, order_id=order_id)

    order_items = OrderItem.objects.filter(order=order).order_by('-id')
    order_item_ids = order_items.values_list('item_id', flat=True)

    services = Item.objects.filter(Q(type='Service') & (Q(customer=order.customer) | Q(customer__isnull=True))).exclude(id__in=order_item_ids).order_by('-id')
    products = Item.objects.filter(Q(type='Product') & (Q(customer=order.customer) | Q(customer__isnull=True))).exclude(id__in=order_item_ids).order_by('-id')
    payments = OrderPayment.objects.filter(order = order).order_by('-id')

    context = {
        'order' : order,
        'order_items' : order_items,
        'services': services,
        'payments' : payments,
    }

    return render(request, 'details_templates/inner-customer-order.html', context)



@customer_login_required
def customer_projects(request, *args, **kwargs):
    projects = Project.objects.filter(customer=request.user.customerprofile)

    context = {
        'projects': projects,
        
    }

    return render(request, 'listing_pages/customer-projects.html', context)


@customer_login_required
def customer_project_details(request, project_id):
    project = get_object_or_404(Project, project_id=project_id)

    context = {
        'project': project,
        
    }

    return render(request, 'details_templates/inner-customer-project.html', context)




@customer_login_required
def customer_tickets(request, *args, **kwargs):
    all_tickets = Ticket.objects.filter(customer=request.user.customerprofile)

    all_tickets_with_update_date = all_tickets.annotate(
        latest_update_date=Max('ticketupdate__date_added')
    )
    all_tickets_ordered = all_tickets_with_update_date.order_by('-latest_update_date')
    open_tickets = []
    closed_tickets = []
    for ticket in all_tickets_ordered:
        last_status = ticket.ticketstatus_set.last()
        if last_status:
            last_status = last_status.status
            if last_status == 'Closed':
                closed_tickets.append(ticket)
            else:
                open_tickets.append(ticket)
        else:
            # If no status is found, assume it's open
            open_tickets.append(ticket)
    
    for ticket in open_tickets:
        unread_updates_count = 0
        for ticket_update in ticket.ticketupdate_set.exclude(added_by=request.user): 
            if not TicketRead.objects.filter(ticket_update=ticket_update, user=request.user, read=True).exists():
                unread_updates_count += 1

        ticket.unread_updates_count = unread_updates_count


    context = {
        'open_tickets': open_tickets,
        'closed_tickets': closed_tickets,
    }

    return render(request, 'listing_pages/customer-tickets.html', context)




 

# PRODUCTS
@customer_login_required
def osimenu_plans(request, *args, **kwargs):
    osimenu_basic = Item.objects.filter(title='OSIMENU BASIC').first()
    osimenu_standard = Item.objects.filter(title='OSIMENU STANDARD').first()
    osimenu_premium = Item.objects.filter(title='OSIMENU PREMIUM').first()

    active_order_item_basic = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=osimenu_basic, active=True)
    active_order_item_standard = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=osimenu_standard, active=True)
    active_order_item_premium = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=osimenu_premium, active=True)
    
    context = {
        'osimenu_basic': osimenu_basic,
        'osimenu_standard': osimenu_standard,
        'osimenu_premium': osimenu_premium,

        'active_order_item_basic': active_order_item_basic,
        'active_order_item_standard': active_order_item_standard,
        'active_order_item_premium': active_order_item_premium,
    }

    return render(request, 'products/osimenu-plans.html', context)


@customer_login_required
def osicard_plans(request, *args, **kwargs):

    osicard_basic = Item.objects.filter(title='OSICARD BASIC').first()
    osicard_standard = Item.objects.filter(title='OSICARD STANDARD').first()
    osicard_premium= Item.objects.filter(title='OSICARD PREMIUM').first()
    active_order_item_basic = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=osicard_basic, active=True)
    active_order_item_standard = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=osicard_standard, active=True)
    active_order_item_premium = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=osicard_premium, active=True)
    
    
    context = {
        'active_order_item_basic': active_order_item_basic,  
        'active_order_item_standard': active_order_item_standard,
        'active_order_item_premium': active_order_item_premium,
        'osicard_standard': osicard_standard,
        'osicard_premium': osicard_premium,
        'active_order_item_premium': active_order_item_premium,

    }

    return render(request, 'products/osicard-plans.html', context)



@customer_login_required
def shared_hosting_plans(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'products/shared-hosting-plans.html', context)


@customer_login_required
def cloud_vps_hosting_plans(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'products/cloud-vps-hosting-plans.html', context)


@customer_login_required
def dedicated_servers_plans(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'products/dedicated-servers-plans.html', context)


@customer_login_required
def cpanel_licenses(request, *args, **kwargs):
    admin_cloud = Item.objects.filter(title='ADMIN CLOUD').first()
    pro_cloud = Item.objects.filter(title='PRO CLOUD').first()
    premier_cloud = Item.objects.filter(title='PREMIER CLOUD').first()
    premier_metal = Item.objects.filter(title='PREMIER METAL').first()


    active_order_admin_cloud = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=admin_cloud, active=True)
    active_order_pro_cloud = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=pro_cloud, active=True)
    active_order_premier_cloud = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=premier_cloud, active=True)
    active_order_premier_metal = OrderItem.objects.filter(order__customer=request.user.customerprofile, item=premier_metal, active=True)
    
    context = {
        'admin_cloud' : admin_cloud,
        'pro_cloud' : pro_cloud,
        'premier_cloud' : premier_cloud,
        'premier_metal' : premier_metal,
        
        'active_order_admin_cloud' : active_order_admin_cloud,
        'active_order_pro_cloud' : active_order_pro_cloud,
        'active_order_premier_cloud' : active_order_premier_cloud,
        'active_order_premier_metal' : active_order_premier_metal,
    }

    return render(request, 'products/cpanel-licenses.html', context)




# USER PROFILE
@customer_login_required
def user_profile(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'user_profile_pages/user-profile.html', context)



@customer_login_required
def user_settings(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'user_profile_pages/user-settings.html', context)




def change_password(request):
    if request.method == 'POST':
        current_password = request.POST['current_password']
        new_password = request.POST['new_password']
        confirm_password = request.POST['confirm_password']

        if check_password(current_password, request.user.password):
            if new_password == confirm_password:
                request.user.set_password(new_password)
                request.user.save()
                update_session_auth_hash(request, request.user)
                logout(request)
                return redirect('home') 
            
    return render(request, 'accounts/change_password.html')



def check_current_password(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            current_password = data.get('current_password')
        except json.JSONDecodeError:
            return JsonResponse({'is_current_password_correct': False})

        user = request.user

        if check_password(current_password, request.user.password):
            return JsonResponse({'is_current_password_correct': True})
        else:
            return JsonResponse({'is_current_password_correct': False})

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



# CLOSE TICKET CONFIRMATION MODAL
@customer_login_required
def close_ticket_status_modal(request, *args, **kwargs):
    
    context = {

    }

    return render(request, 'edit_templates/close-ticket-status-modal.html', context)




