from django.shortcuts import render, get_object_or_404
from customercore.decorators import *
from customercore.models import *
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
from support .models import *


@customer_login_required
def customer_add_ticket(request, *args, **kwargs):
    customer_orders = Order.objects.filter(customer=request.user.customerprofile)
    customer_orders_with_last_status = customer_orders.annotate(max_status_date=Max('orderstatus__date'))
    customer_orders_completed = customer_orders_with_last_status.filter(orderstatus__status='Completed',orderstatus__date=F('max_status_date'))
    customer_products = OrderItem.objects.filter(active__in=[True, None], item__type = 'Product', order__customer = request.user.customerprofile, order__in=customer_orders_completed )
    customer_projects = Project.objects.filter(customer=request.user.customerprofile)
    support_department = get_object_or_404(Department, name='Support')

    if request.method == 'POST':
        project = None
        product = None
        regarding = 'General/Account/Billing'
        if request.POST.get('project') and request.POST.get('regarding') == 'Project':
            project = get_object_or_404(Project, id=request.POST.get('project'))
            regarding = 'Project/Product'
        elif request.POST.get('product') and request.POST.get('regarding') == 'Product':
            product = get_object_or_404(Item, id=request.POST.get('product'))
            regarding = 'Project/Product'
        ticket = Ticket(
            customer = request.user.customerprofile,
            title = request.POST.get('title'),
            description =  request.POST.get('description'),
            regarding = regarding,
            project = project,
            product = product,
            opened_by = request.user,
            opened_date = datetime.now(),
        )
        ticket.save()
        
        ticket_status = TicketStatus(
            ticket = ticket,
            status = 'Open',
            added_by = request.user,
            date_added = datetime.now()
        )
        ticket_status.save()

        ticket_department = TicketDepartment(
            ticket=ticket,
            department=support_department,
            date_added=datetime.now()
        )
        ticket_department.save()
        

        file_paths = request.POST.getlist('filePath') 

        for file_path in file_paths:
            ticket_attachment = TicketAttachment(
                ticket=ticket,
                file_path=file_path  
            )
            ticket_attachment.save()

        return redirect('ticketroom', ticket_number=ticket.ticket_number)

    
    context = {
        'customer_products': customer_products,
        'customer_projects': customer_projects,

    }

    return render(request, 'add_templates/customer-add-ticket.html', context)




