from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path,include
from api import views
from paypal.standard.ipn.views import ipn
from api.models import PaypalDeposit
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
import logging
from urllib.parse import parse_qs
import requests

logger = logging.getLogger(__name__)

@csrf_exempt
def ipn_debug(request):
    if request.method == 'POST':
        ipn_data = parse_qs(request.body.decode('utf-8'))
        payment_status = ipn_data.get('payment_status', [''])[0]
        invoice_id = ipn_data.get('invoice', [''])[0]
        # Validate IPN with PayPal
        PAYPAL_VERIFY_URL = (
            "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr"
            if settings.PAYPAL_TEST
            else "https://ipnpb.paypal.com/cgi-bin/webscr"
        )

        # send verification request to paypal
        verification_response = requests.post(
            PAYPAL_VERIFY_URL,
            data={'cmd': '_notify-validate', **{k: v[0] for k, v in ipn_data.items()}},
        )

        if verification_response.text == 'VERIFIED':
            payment = PaypalDeposit.objects.filter(invoice=invoice_id).first()
            if payment_status == 'Completed':
                if payment:
                    payment.status = "Completed"
                    payment.save()

                    # TODO
                    # Alert user that payment is successfull
                    return HttpResponse("Payment Completed")
                # process payment here
                logger.info(f"IPN POST received: {request.body}")
                return HttpResponse("valid IPN received")
            else:

                logger.warning(f"Payment not completed. Status: {payment_status}")
    else:
        logger.warning(f"IPN endpoint accessed with method: {request.method}")
        return HttpResponse("Method not allowed", status=405)
urlpatterns = [
    path('', views.index, name="index"),
    path('jet/', include("jet.urls")),
    path('admin/', admin.site.urls),
    path('api/', include("api.urls")),
    path("", include('paypal.standard.ipn.urls')),
    path('paypal-ipn/', ipn_debug, name='paypal-ipn'),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)