# Create your views here.
from django.conf import settings
from django.http import BadHeaderError
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django import forms
from userapp.models import Enquiry, Feedback, Order, Payment, User
from .models import AdTemplate, AdType, Category
from .forms import AdTypeForm, CategoryForm, AdTemplateForm 
import os
from django.core.mail import send_mail
from django.core.paginator import Paginator
from django.contrib.auth import update_session_auth_hash


def admin_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('index')  # Redirect to dashboard
        else:
            messages.error(request, "Invalid username or password")
            return redirect('admin_login')  # Redirect back to login page

    return render(request, 'adminapp/adminlogin.html')

def admin_logout(request):
    logout(request)
    return redirect(admin_login )





def index(request):
    context = {
        'total_users': User.objects.filter(role='User').count(),
        'total_adtype': AdType.objects.count(),
        'total_categories': Category.objects.count(),
        'total_ads_templates': AdTemplate.objects.count(),
        'total_orders': Order.objects.count(),
        'total_payment': Payment.objects.count(),
        'total_feedback': Feedback.objects.count(),
        'total_enquiries': Enquiry.objects.count(),
        }
    return render(request, 'adminapp/index.html',context)




@login_required
def admin_profile(request):
    return render(request, 'adminapp/admin_profile.html')

@login_required
def admin_change_password(request):
    if request.method == 'POST':
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        if new_password == confirm_password:
            request.user.set_password(new_password)
            request.user.save()
            update_session_auth_hash(request, request.user)  # Prevent logout
            messages.success(request, "Password changed successfully!")
        else:
            messages.error(request, "Passwords do not match!")

    return redirect('admin_profile')

@login_required
def admin_screenlock(request):
    if request.method == "POST":
        password = request.POST.get("password")
        user = authenticate(request, username=request.user.username, password=password)
        
        if user is not None:
            login(request, user)
            return redirect("index")  # Redirect to admin dashboard
        else:
            messages.error(request, "Incorrect password. Please try again.")
    
    return render(request, "adminapp/admin_screenlock.html")

def manageuser(request):
    users = User.objects.filter(role="User")  # Fetch all users from the database
    return render(request, 'adminapp/manageuser.html', {'data': users})

def block_user(request, user_id):
    user = get_object_or_404(User, id=user_id)
    user.is_active = False
    user.save()
    return redirect('manageuser')

def unblock_user(request, user_id):
    user = get_object_or_404(User, id=user_id)
    user.is_active = True
    user.save()
    return redirect('manageuser')

def managecategory(request):
    categories = Category.objects.all()
    return render(request, 'adminapp/managecategory.html', {'categories': categories})

# CATEGORY VIEWS
def category_add(request):
    if request.method == "POST":
        form = CategoryForm(request.POST, request.FILES)  # Add request.FILES for image upload
        if form.is_valid():
            form.save()
            return redirect('managecategory')
    else:
        form = CategoryForm()
    return render(request, 'adminapp/category_form.html', {'form': form, 'title': 'Add Category'})

def category_edit(request, id):
    category = get_object_or_404(Category, id=id)
    if request.method == "POST":
        form = CategoryForm(request.POST, request.FILES, instance=category)  # Include request.FILES
        if form.is_valid():
            form.save()
            return redirect('managecategory')
    else:
        form = CategoryForm(instance=category)
    return render(request, 'adminapp/category_form.html', {'form': form, 'title': 'Edit Category'})

def category_delete(request, id):
    category = get_object_or_404(Category, id=id)
    if request.method == "POST":
        category.delete()
        return redirect('managecategory')
    return render(request, 'adminapp/confirm_delete.html', {'object': category, 'type': 'Category'})

def manageadtype(request):
    adtypes = AdType.objects.all()
    return render(request, 'adminapp/manageadtype.html', {'adtypes': adtypes})

# AD TYPE VIEWS
def adtype_add(request):
    if request.method == "POST":
        form = AdTypeForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('manageadtype')
    else:
        form = AdTypeForm()
    return render(request, 'adminapp/adtype_form.html', {'form': form, 'title': 'Add Ad Type'})

def adtype_edit(request, id):
    adtype = get_object_or_404(AdType, id=id)
    if request.method == "POST":
        form = AdTypeForm(request.POST, instance=adtype)
        if form.is_valid():
            form.save()
            return redirect('manageadtype')
    else:
        form = AdTypeForm(instance=adtype)
    return render(request, 'adminapp/adtype_form.html', {'form': form, 'title': 'Edit Ad Type'})

def adtype_delete(request, id):
    adtype = get_object_or_404(AdType, id=id)  # Ensures 404 is raised if not found
    adtype.delete()
    messages.success(request, "Ad Type deleted successfully.")
    return redirect('manageadtype')  # Adjust the redirect URL name if needed

# View to display all ad templates
def managetemplate(request):
    ad_type_id = request.GET.get('ad_type')
    ad_types = AdType.objects.all()

    templates = AdTemplate.objects.all()
    if ad_type_id:
        templates = templates.filter(ad_type_id=ad_type_id)

    paginator = Paginator(templates, 5)  # 5 templates per page
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'page_obj': page_obj,
        'ad_types': ad_types,
        'selected_ad_type': ad_type_id
    }
    return render(request, 'adminapp/managetemplate.html', context)
    
# View to add a new ad template
def adtemplate_add(request):
    categories = Category.objects.all()
    ad_types = AdType.objects.all()

    if request.method == "POST":
        form = AdTemplateForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            return redirect('managetemplate')  # ✅ Redirect after saving
        else:
            print("❌ Form Errors:", form.errors)  # ✅ Print errors in the terminal

    else:
        form = AdTemplateForm()

    return render(request, 'adminapp/adtemplate_add.html', {
        'categories': categories,
        'ad_types': ad_types,
        'form': form,
    })

# View to edit an existing ad template
def adtemplate_edit(request, template_id):
    
    
    ad_template = get_object_or_404(AdTemplate, id=template_id)
    
    categories = Category.objects.all()
    ad_types = AdType.objects.all()

    if request.method == "POST":
        form = AdTemplateForm(request.POST, request.FILES, instance=ad_template)

        if form.is_valid():
            form.save()
            return redirect('managetemplate')  # ✅ Redirect after updating
        else:
            print("❌ Form Errors:", form.errors)  # ✅ Print errors in the terminal

    else:
        form = AdTemplateForm(instance=ad_template)

    return render(request, 'adminapp/adtemplate_edit.html', {
        'form': form,
        'categories': categories,
        'ad_types': ad_types,
        'ad_template': ad_template,
    })

# View to delete an ad template
def adtemplate_delete(request, id): 
    ad_template = get_object_or_404(AdTemplate, id=id)

    # Delete image from storage
    if ad_template.image and os.path.exists(ad_template.image.path):
        os.remove(ad_template.image.path)

    ad_template.delete()  # Delete the template
    return redirect('managetemplate')  # Redirect to a success page after deletion

def manageorder(request):
    orders = Order.objects.all()
    return render(request, 'adminapp/manageorder.html', {'orders': orders})

def update_order_status(request, order_id):
    order = get_object_or_404(Order, id=order_id)

    if request.method == "POST":
        new_status = request.POST.get("status")

        # If order is cancelled, update payment status
        if new_status == "cancelled":
            payment = Payment.objects.filter(order=order).first()
            if payment and payment.payment_status.lower() == "paid":  # Use 'payment_status'
                payment.payment_status = "refunded"
                payment.save()
                messages.success(request, f"Order #{order.id} has been cancelled, and payment has been refunded.")

        # Update order status
        order.status = new_status
        order.save()
        
        messages.success(request, f"Order #{order.id} status updated successfully.")
    
    return redirect("manageorder")

def order_detail(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    payment = Payment.objects.filter(order=order).first()
    print(payment)
    return render(request, 'adminapp/order_detail.html', {'order': order,'payment_status': payment.payment_status if payment else "Not Available"})

def view_payments(request):
    payment_status = request.GET.get('payment_status', '')

    # Filter transactions based on payment status if selected
    if payment_status:
        transactions = Payment.objects.filter(payment_status=payment_status)
    else:
        transactions = Payment.objects.all()

    from django.core.paginator import Paginator
    paginator = Paginator(transactions, 5) 
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'transactions': page_obj,
        'page_obj': page_obj,
        'payment_status': payment_status, 
    }
    return render(request, 'adminapp/viewpayment.html', context)


def managefeedback(request):
    feedbacks = Feedback.objects.all().order_by('-created_at') 
    return render(request, 'adminapp/managefeedback.html', {'feedbacks': feedbacks})

def delete_feedback(request, feedback_id):
    if request.method == 'POST':
        feedback = get_object_or_404(Feedback, id=feedback_id)
        feedback.delete()
        messages.success(request, 'Feedback deleted successfully.')
    else:
        messages.error(request, 'Invalid request.')
    return redirect('managefeedback')

def manageenquiries(request):
    status = request.GET.get('status')
    enquiries = Enquiry.objects.all()

    if status == "replied":
        enquiries = enquiries.filter(is_replied=True)
    elif status == "pending":
        enquiries = enquiries.filter(is_replied=False)

    return render(request, 'adminapp/manageenquiry.html', {'enquiries': enquiries})

def reply_enquiry(request, id):
    enquiry = get_object_or_404(Enquiry, id=id)
    if request.method == "POST":
        # Static professional reply message
        reply_message = (
            f"Dear {getattr(enquiry, 'name', 'Customer')},\n\n"
            "Thank you for your enquiry "
            f" Our team has received your request "
            "and will provide you with further details soon.\n\n"
            "If you need immediate assistance, please contact us directly.\n\n"
            "Best Regards,\n"
            "Customer Support Team\n"
            "AdFusion \n"
            "adfusion9@gmail.com"
        )
        try:
            send_mail(
                f"Re: {enquiry.subject}",
                reply_message,
                settings.EMAIL_HOST_USER,  # Use Django settings email
                [enquiry.email],
                fail_silently=False,
            )
            enquiry.is_replied = True  # Mark as replied
            enquiry.save()
            messages.success(request, "Reply sent successfully.")
        except Exception as e:
            messages.error(request, f"Failed to send email: {e}")
        return redirect('manageenquiries')
    return render(request, 'adminapp/reply_enquiry.html', {'enquiry': enquiry})

def delete_enquiry(request, id):
    enquiry = get_object_or_404(Enquiry, id=id)
    enquiry.delete()
    messages.success(request, "Enquiry deleted successfully.")
    return redirect('manageenquiries')

