from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Ticket, Comment
from .forms import TicketForm, CommentForm

@login_required
def dashboard(request):
    """User dashboard showing their tickets."""
    if request.user.is_staff:
        tickets = Ticket.objects.all()
    else:
        tickets = Ticket.objects.filter(created_by=request.user)
    
    context = {
        'tickets': tickets,
        'open_count': tickets.filter(status='open').count(),
        'pending_count': tickets.filter(status='pending').count(),
        'resolved_count': tickets.filter(status='resolved').count(),
    }
    return render(request, 'core/index.html', context)

@login_required
def ticket_create(request):
    """View to create a new ticket."""
    if request.method == 'POST':
        form = TicketForm(request.POST)
        if form.is_valid():
            ticket = form.save(commit=False)
            ticket.created_by = request.user
            ticket.save()
            messages.success(request, "Ticket created successfully!")
            return redirect('dashboard')
    else:
        form = TicketForm()
    
    return render(request, 'core/ticket_form.html', {'form': form})

@login_required
def ticket_detail(request, pk):
    """View ticket details and handle comments."""
    ticket = get_object_or_404(Ticket, pk=pk)
    
    # Simple permission check
    if not request.user.is_staff and ticket.created_by != request.user:
        messages.error(request, "You do not have permission to view this ticket.")
        return redirect('dashboard')
    
    if request.method == 'POST':
        # Check if it's a comment or a status update
        if 'status' in request.POST and request.user.is_staff:
            ticket.status = request.POST.get('status')
            ticket.save()
            messages.success(request, f"Status updated to {ticket.get_status_display()}")
            return redirect('ticket_detail', pk=pk)
        
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.ticket = ticket
            comment.author = request.user
            comment.save()
            messages.success(request, "Reply added!")
            return redirect('ticket_detail', pk=pk)
    else:
        comment_form = CommentForm()
    
    return render(request, 'core/ticket_detail.html', {
        'ticket': ticket,
        'comment_form': comment_form,
    })