from django.shortcuts import render, get_object_or_404
from customercore.decorators import *
from customercore.models import *
from billing.add.views import *
from django.http import JsonResponse
import requests
import json
import base64
import json
import random
import string
from customercore.views import *


def basic_auth_header(username, password):
    credentials = f"merchant.{username}:{password}"
    encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
    return f"Basic {encoded_credentials}"



def whish_payment(request, payment_id):
    payment = get_object_or_404(OrderPayment, id = payment_id)

    context = {
        'payment' : payment,
    }

    return render(request, 'payment_pages/whish-payment.html', context) 


def cash_payment(request, payment_id):
    payment = get_object_or_404(OrderPayment, id = payment_id)

    context = {
        'payment' : payment,
    }

    return render(request, 'payment_pages/cash-payment.html', context) 




def card_payment(request, payment_id):
    payment = get_object_or_404(OrderPayment, id = payment_id)

    context = {
        'payment' : payment,
    }

    return render(request, 'payment_pages/card-payment.html', context) 


@customer_login_required
def initiate_payment_checkout(request):
    api_username = 'merchant.06127800'
    api_password = '549c33e1bc4aea6fcf96f9943e6c0256'
    merchant_id = '06127800'
    merchant_name = 'Ositcom Sal'

    customer = request.user.customerprofile

    data = json.loads(request.body)
    payment_id = data.get('payment_id')

    payment = get_object_or_404(OrderPayment, id=payment_id)


    order = payment.order
    order_id = order.order_id

    price = order.get_cart_total

    
    payload = {
        'apiOperation': 'INITIATE_CHECKOUT',
        'apiUsername': api_username,
        'apiPassword': api_password,
        'merchant': merchant_id,
        'interaction.operation': 'PURCHASE',  
        'interaction.merchant.name': merchant_name, 
        'order.id': order_id,
        'order.amount': price,
        'order.currency': 'USD',
        'order.description': 'description_of_order',
        'interaction.returnUrl' : f"https://osina.ositcom.com/payment/check-order-status/{merchant_id}/{order_id}/"
    }

    try:
        response = requests.post('https://creditlibanais-netcommerce.gateway.mastercard.com/api/nvp/version/78', data=payload)
        
        print('Response Content:', response.text)
        
        if response.status_code == 200:
            response_data = response.text
            parsed_data = dict(item.split('=') for item in response_data.split('&'))
            session_id = parsed_data.get('session.id')
            return JsonResponse({'session_id': session_id}, status=200)
            
        else:
            print('Response Status Code:', response.status_code)  
            return JsonResponse({'error': 'Failed to initiate checkout'}, status=500)
    except Exception as e:
        print('Exception:', e)  
        return JsonResponse({'error': 'Internal Server Error'}, status=500)
    


@customer_login_required
def buy_now(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    cycles = RecurringCycle.objects.filter(item = item)

    selected_cycle = None
    
    context = {
        'item' : item,
        'cycles' : cycles,
        'selected_cycle': selected_cycle,
    }

    return render(request, 'payment_pages/buy-now.html', context)



@customer_login_required
def buy_now_checkout(request):
    api_username = 'merchant.06127800'
    api_password = '549c33e1bc4aea6fcf96f9943e6c0256'
    merchant_id = '06127800'
    merchant_name = 'Ositcom Sal'

    customer = request.user.customerprofile

    data = json.loads(request.body)
    item_id = data.get('item_id')
    cycle_id = data.get('cycle_id') 

    item = Item.objects.get(id=item_id)

    cycle = RecurringCycle.objects.get(id = cycle_id)
    price = cycle.cycle_price


    existing_order = Order.objects.filter(customer=customer, orderstatus__isnull=True).first()


    if existing_order:
        existing_order.orderitem_set.all().delete()
        order = existing_order
    else:
        order = Order.objects.create(customer=customer)
    
    order.save()
    order_id = order.order_id


    order_item = OrderItem.objects.create(order=order, item=item, end_at = datetime.now() + timedelta(days=(cycle.months * 30)))
    order_item.save()

    
    payload = {
        'apiOperation': 'INITIATE_CHECKOUT',
        'apiUsername': api_username,
        'apiPassword': api_password,
        'merchant': merchant_id,
        'interaction.operation': 'PURCHASE',  
        'interaction.merchant.name': merchant_name, 
        'order.id': order_id,
        'order.amount': price,
        'order.currency': 'USD',
        'order.description': 'description_of_order',
        'interaction.returnUrl' : f"https://osina.ositcom.com/payment/check-order-status/{merchant_id}/{order_id}/"
    }

    try:
        response = requests.post('https://creditlibanais-netcommerce.gateway.mastercard.com/api/nvp/version/78', data=payload)
        
        print('Response Content:', response.text)
        
        if response.status_code == 200:
            response_data = response.text
            parsed_data = dict(item.split('=') for item in response_data.split('&'))
            session_id = parsed_data.get('session.id')
            return JsonResponse({'session_id': session_id}, status=200)
            
        else:
            print('Response Status Code:', response.status_code)  
            return JsonResponse({'error': 'Failed to initiate checkout'}, status=500)
    except Exception as e:
        print('Exception:', e)  
        return JsonResponse({'error': 'Internal Server Error'}, status=500)
    




def check_order_status(request, merchant_id, order_id):
    api_password = '549c33e1bc4aea6fcf96f9943e6c0256'
    url = f"https://creditlibanais-netcommerce.gateway.mastercard.com/api/rest/version/78/merchant/{merchant_id}/order/{order_id}"
    order = Order.objects.get(order_id=order_id)
    payment_type = get_object_or_404(PaymentType, name='Online Payment')

    headers = {
        'Content-Type': 'application/json',
        'Authorization': basic_auth_header(merchant_id, api_password)
    }

    try:
        response = requests.get(url, headers=headers)

        if response.status_code == 200:
            order_details = response.json()
            if order_details.get('result') == 'SUCCESS':
                OrderStatus.objects.create(
                    order = order,
                    status = 'Completed',
                    date = datetime.now()
                )
                payment = OrderPayment.objects.create(
                    order = order,
                    amount = order.get_cart_total,
                    date_paid =  datetime.now(),
                )
                payment.type.add(payment_type)
                payment.save()
                order_items = OrderItem.objects.filter(order=order)
                for order_item in order_items:
                    order_item.purchased_at = datetime.now()
                    if order_item.item.item_type.name == 'OSIMENU':
                        api_url = 'https://osimenu.com/api/create-subscription/'
                        random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
                        end_date_str = order_item.end_at.strftime('%Y-%m-%d')
                        api_data = {
                                'user': {
                                    'username': request.user.email,
                                    'email': request.user.email,
                                    'password': random_string,
                                    'first_name': request.user.first_name,
                                    'last_name': request.user.last_name
                                },
                                'customer': {
                                    'mobile_number': request.user.customerprofile.mobile_number
                                },
                                'subscription': {
                                    'plan': order_item.item.title,
                                    'end_date': end_date_str
                                }
                        }
                        response = requests.post(api_url, json=api_data)
                        order_item.active = True
                        old_order_items = OrderItem.objects.exclude(order__id=order.id).filter(item__item_type__name='OSIMENU', order__customer=request.user.customerprofile)
                        for item in old_order_items:
                            item.active = False
                            item.save()
                    order_item.save()
                add_invoice_pdf(request, order_id=order.id)
                return redirect('customerorders')
            error_message = 'Failed to retrieve order details: ' + response.text
            return JsonResponse({'error': error_message}, status=500)  
    except Exception as e:
        error_message = 'Exception: ' + str(e)
        return JsonResponse({'error': error_message}, status=500)  




def buy_free_osimenu(request):
    api_url = 'https://osimenu.com/api/create-subscription/'
    random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
    api_data = {
        'user': {
            'username': request.user.email,
            'email': request.user.email,
            'password': random_string,
            'first_name': request.user.first_name,
            'last_name': request.user.last_name
        },
        'customer': {
            'mobile_number': request.user.customerprofile.mobile_number
        },
        'subscription': {
            'plan': 'OSIMENU BASIC'
        }
    }

    order = Order.objects.create(
        customer = request.user.customerprofile,
    )

    order_status = OrderStatus.objects.create(
        order=order,
        status = 'Completed',
        date = datetime.now()
    )

    order_item = OrderItem.objects.create(
        order = order,
        item = get_object_or_404(Item, title='OSIMENU BASIC'),
        purchased_at = datetime.now(),
        active = True,
    )

    old_order_items = OrderItem.objects.exclude(order__id=order.id).filter(item__item_type__name='OSIMENU', order__customer=request.user.customerprofile)
    for item in old_order_items:
        item.active = False
        item.save()

    response = requests.post(api_url, json=api_data)
    print(response)
    return redirect('customerorders')




def buy_free_osicard(request):
    api_url = 'https://mybusinesscardpage.com/api/create-subscription/'
    random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
    api_data = {
        'user': {
            'username': request.user.email,
            'email': request.user.email,
            'password': random_string,
            'first_name': request.user.first_name,
            'last_name': request.user.last_name
        },
        'profile': {
            'mobile_number': request.user.customerprofile.mobile_number
        },
        'subscription': {
            'plan': 'OSICARD BASIC'
        }
    }

    order = Order.objects.create(
        customer = request.user.customerprofile,
    )

    order_status = OrderStatus.objects.create(
        order=order,
        status = 'Completed',
        date = datetime.now()
    )

    order_item = OrderItem.objects.create(
        order = order,
        item = get_object_or_404(Item, title='OSICARD BASIC'),
        purchased_at = datetime.now(),
        active = True,
    )

    old_order_items = OrderItem.objects.exclude(order__id=order.id).filter(item__item_type__name='OSICARD', order__customer=request.user.customerprofile)
    for item in old_order_items:
        item.active = False
        item.save()

    response = requests.post(api_url, json=api_data)
    print(response)
    return redirect_osicard(request)


