from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from users.models import User
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from decouple import config
import stripe
from django.http.response import JsonResponse # new
from .models import *
from django.http import HttpResponse
from reservations.models import Booking

@login_required
def payment_canceled(request):
    return render(request, 'payment/canceled.html')  

@login_required
def payment_success(request):
    checkout_session_id = request.GET.get('session_id', None)
    
    if checkout_session_id:
        session = stripe.checkout.Session.retrieve(checkout_session_id)
        customer_id = session.customer
        customer = stripe.Customer.retrieve(customer_id)
        
        line_item = stripe.checkout.Session.list_line_items(checkout_session_id).data[0]
        
        try:
            
            p = Payment.objects.get_or_create(
            user = request.user, 
            stripe_customer = customer_id,
            stripe_checkout_id = checkout_session_id,
            stripe_product_id = line_item.price.product,
            product_name = line_item.description,
            quantity = line_item.quantity,
            price = line_item.price.unit_amount / 100.0,
            currency = line_item.price.currency,
            has_paid = True
            )
            try:
                booking = Booking.objects.get(stripe_checkout_id=checkout_session_id)
                booking.payment=p[0]
                booking.save()
            except Exception as e:
                print("Exception ==> ", e)
            
        except Exception as e:
            print(e)
           

        if line_item.description == 'Carte de membre':
            request.user.frais_carte=True
            request.user.save()
        
        else:
            try:
                booking = Booking.objects.get(stripe_checkout_id=checkout_session_id)
                booking.stand.stock -= 1
                booking.stand.save()
                booking.save()
            except Exception as e:
                print("Error", e)
                pass
    
    return render(request, 'payment/success.html')  # Render the template with the given context

@login_required
def member_card_payment(request):
    if request.user.frais_carte:
        return redirect('member_card_details')
    
    if request.method == 'GET':
        domain_url = config('DOMAIN_URL')
        stripe.api_key = config('STRIPE_SECRET_KEY')
        try:
            # test
            # price_id = 'price_1R1rFmKa65RVF9Bfl5KtTxIi'

            price_id = 'price_1R4116Ka65RVF9Bfvz6PVLzV'
            checkout_session = stripe.checkout.Session.create(
                success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
                cancel_url=domain_url + 'canceled',
                payment_method_types=['card'],
                mode='payment',
                customer_creation = 'always',
                line_items=[
                    {
                        'price': price_id,
                        'quantity': 1,
                    }
                ]
            )
        
            return redirect(checkout_session.url, code =303)
        except Exception as e:
            return JsonResponse({'error': str(e)})
        


@require_POST
@csrf_exempt
def stripe_webhook(request):
    endpoint_secret = config('STRIPE_WEBHOOK_SECRET')
    payload = request.body
    signature_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None
    
    try:
       
        event = stripe.Webhook.construct_event(
            payload, signature_header, endpoint_secret
        )
    except Exception as e:
        print(e)
        return HttpResponse(status=400)
    
    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']
        checkout_session_id = session.get('id')
        user_payment = Payment.objects.get(stripe_checkout_id=checkout_session_id)
        user_payment.has_paid = True
        user_payment.save()
        user = user_payment.user
        user.frais_carte = True
        user.save()
        
    return HttpResponse(status=200)


def create_transaction(product_data, amount):

    domain_url = config('DOMAIN_URL')
    stripe.api_key = config('STRIPE_SECRET_KEY')
    try:
        checkout_session = stripe.checkout.Session.create(
            success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
            cancel_url=domain_url + 'canceled',
            payment_method_types=['card'],
            mode='payment',
            customer_creation = 'always',
            line_items=[
                {
                    "price_data": {
                        "unit_amount": (amount * 100),
                        "currency": "eur",
                        "product_data": product_data
                    },
                    "quantity": 1,

                }
            ]
        )
        return checkout_session
    except Exception as e:
        return JsonResponse({'error': str(e)})