from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.db import connection
from django.contrib import messages
from .models import Login
from .models import TravelBill
from .forms import TravelBillForm 
from datetime import datetime
from django.core.files.storage import default_storage
import os

from django.views.decorators.csrf import csrf_exempt
import traceback

def login_view(request):
    if request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]

        try:
            user = Login.objects.get(username=username)
            if user.check_password(password):
                request.session["user_type"] = user.user_type
                
                if user.user_type == "kds":
                   
                    return redirect("kds")  
                elif user.user_type == "agent":
             
                    return redirect("agent")  

                return redirect("report") 
           
            return render(request, "login.html", {"error": "Invalid credentials"})
        except Login.DoesNotExist:
       
            return render(request, "login.html", {"error": "Invalid credentials"})

    return render(request, "login.html")



def kds(request):
    user_type = request.session.get("user_type", "Unknown")
    travel_bills = TravelBill.objects.all()  
    return render(request, "report.html", {"user_type": user_type, "travel_bills": travel_bills,"show_bill_generate": False})


def agent(request):
    request.session["show_bill_generate"] = True  
    travel_bills = TravelBill.objects.all()  

    
    return render(request, "report.html", {"user_type": "Agent","travel_bills": travel_bills, "show_bill_generate": True})


def welcome_view(request):
    user_type = request.session.get('user_type')
    travel_bills = TravelBill.objects.all()  

    

    for bill in travel_bills:
     

     return JsonResponse({
        "user_type": user_type,
        "travel_bills": list(travel_bills)  
    })

def travel_bill_submission(request):
    if request.method == 'POST':
        guest_name = request.POST.get('guest_name')
        cell_no = request.POST.get('cell_no')
        vehicle_type = request.POST.get('vehicle_type')
        vehicle_details = request.POST.get('vehicle_details')
        from_date_time = request.POST.get('from_date_time')
        to_date_time = request.POST.get('to_date_time')
        visit_places = request.POST.get('visit_places')
        opening_kms = request.POST.get('opening_kms')
        closing_kms = request.POST.get('closing_kms')
        amt = request.POST.get('amt')
        night = request.POST.get('night', 0)  # Handle optional fields
        toll = request.POST.get('toll')
        driver_name = request.POST.get('driver_name', '')
        driver_mobile = request.POST.get('driver_mobile', '')
        document = request.FILES.get('document')
        

        try:

            if document:
                if document.content_type != "application/pdf":
                    return JsonResponse({"success": False, "message": "Only PDF files are allowed."}, status=400)
                if document.size > 1024 * 1024:  # 1MB limit
                    return JsonResponse({"success": False, "message": "File size should not exceed 1MB."}, status=400)

            # Convert data to appropriate types
            opening_kms = int(opening_kms) if opening_kms else 0
            closing_kms = int(closing_kms) if closing_kms else 0
            amt = float(amt) if amt else 0
            night = float(night) if night else 0
            toll = float(toll) if toll else 0

            # Convert string to datetime format
            from_date_time = datetime.strptime(from_date_time, '%Y-%m-%dT%H:%M') if from_date_time else None
            to_date_time = datetime.strptime(to_date_time, '%Y-%m-%dT%H:%M') if to_date_time else None

            # Save to database
            TravelBill.objects.create(
                guest_name=guest_name,
                cell_no=cell_no,
                vehicle_type=vehicle_type,
                vehicle_details=vehicle_details,
                from_date_time=from_date_time,
                to_date_time=to_date_time,
                visit_places=visit_places,
                opening_kms=opening_kms,
                closing_kms=closing_kms,
                total_kms = closing_kms - opening_kms,
                amt=amt,
                night=night,
                toll=toll,
                total_amount = amt + night + toll,
                driver_name=driver_name,
                driver_mobile=driver_mobile,
                document=document
            )

            messages.success(request, "Bill submitted successfully!")
            return JsonResponse({"success": True, "message": "Bill submitted successfully!"})

        except Exception as e:
            messages.error(request, f"Error submitting bill: {str(e)}")
            return JsonResponse({"success": False, "message": f"Error submitting bill: {str(e)}"})

    return JsonResponse({"success": True})  # Return success response
    return JsonResponse({"success": False, "message": "Invalid request"}, status=400)
    return render(request, 'report.html')



def travel_bill_report(request):
    
    user_type = request.session.get('user_type')

    show_bill_generate = user_type.lower() == "agent"

    from_date = request.GET.get('from_date')
    to_date = request.GET.get('to_date')

    travel_bills = TravelBill.objects.all()

    if from_date and to_date:
        try:
            from_date = datetime.strptime(from_date, '%Y-%m-%d')
            to_date = datetime.strptime(to_date, '%Y-%m-%d')

            travel_bills = travel_bills.filter(from_date_time__date__gte=from_date, to_date_time__date__lte=to_date)
        except ValueError:
            pass  # Handle invalid date format gracefully

    return render(request, "report.html", {
        "user_type": user_type,
        "travel_bills": travel_bills,
        "show_bill_generate": show_bill_generate
    })

    


def bill_generate(request):
    return render(request, 'bill_generate.html', {'show_bill_generate': True})
    


def update_record(request, record_id):
    if request.method == "POST":
        try:
            record = TravelBill.objects.get(id=record_id)

            # Update text fields
            for key, value in request.POST.items():
                setattr(record, key, value)

            # Handle file upload
            if "document" in request.FILES:
                uploaded_file = request.FILES["document"]
                file_path = os.path.join("uploads/", uploaded_file.name)
                saved_path = default_storage.save(file_path, uploaded_file)
                record.document = saved_path  # Save new document path

            record.save()

            return JsonResponse({
                "success": True,
                "message": "Record updated successfully!",
                "document_url": record.document.url if record.document else None
            })

        except TravelBill.DoesNotExist:
            return JsonResponse({"success": False, "error": "Record not found"}, status=404)
        except Exception as e:
            print(traceback.format_exc())  # 🔥 Debugging: Print full error traceback
            return JsonResponse({"success": False, "error": str(e)}, status=500)

    return JsonResponse({"success": False, "error": "Invalid request"}, status=400)

@csrf_exempt
def delete_record(request, record_id):
    if request.method == "POST":
        try:
            record = TravelBill.objects.get(id=record_id)
            record.delete()
            return JsonResponse({"success": True, "message": "Record deleted successfully."})
        except TravelBill.DoesNotExist:
            return JsonResponse({"success": False, "error": "Record not found."}, status=404)
    return JsonResponse({"success": False, "error": "Invalid request method."}, status=400)
