from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from .models import (
    DatingPartnerProfile, DatingPartnerPhoto, DatingInterest, DatingPartnerPhoto,
    DatingPartnerGuidanceResource
)
from expat_life.models import (
    UserPayableItem, ForeignerProfile, ForeignerLead, ForeignerInterest, WalletAccount,
    PaymentTransactionItem, PaymentTransaction
)
from django.urls import reverse_lazy
from django.contrib.auth import logout
from datetime import date
from django.contrib.auth import get_user_model, login, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import HttpResponseForbidden, JsonResponse
from django.contrib.auth.forms import PasswordChangeForm
import re
import random
import string
from django.views.decorators.http import require_POST
from .forms import (
    DatingPartnerProfileEditForm,
    DatingPartnerProfileImageForm,
    UsernameChangeForm,
    DatingPartnerRegistrationForm,
    DatingInterestForm,
    DatingPartnerPhotoForm,
    DatingPasswordResetForm,
)
from django.core.exceptions import PermissionDenied
from expat_life.utils import (
    get_platform_fee_settings, 
    update_dating_partner_payable_items, 
    mark_dating_partner_transaction_items_paid,
    get_or_create_wallet_account,
    user_can_topup_wallet,
    complete_wallet_topup_transaction,
)

from common.payment_gateway_services import (
    get_paypal_access_token,
    get_paypal_base_url,
    get_paypal_approval_url,
    capture_paypal_order,
)

from expat_life.email_services import (
    send_dating_partner_signup_welcome_email,
    send_dating_partner_interest_notification_email,
)
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from decimal import Decimal, InvalidOperation
from common.choices import NATIONALITY_CHOICES, COUNTRY_CHOICES

from expat_life.forms import ContactMessageForm, WalletTopUpForm

from django.contrib.auth.views import (
    LoginView,
    PasswordResetView,
    PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView,
)
from django.urls import reverse
from django.utils import timezone
import stripe
from django.conf import settings
import requests


User = get_user_model()

def create_dating_partner_paypal_order(payment_transaction, request):
    """
    Creates a PayPal order for Dating Partner payable item checkout.
    """

    access_token = get_paypal_access_token()
    base_url = get_paypal_base_url()

    create_order_url = f'{base_url}/v2/checkout/orders'

    return_url = request.build_absolute_uri(
        reverse(
            'dating_app:dating_partner_paypal_payment_success',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    cancel_url = request.build_absolute_uri(
        reverse(
            'dating_app:dating_partner_payment_cancelled',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    amount_value = payment_transaction.gateway_amount_usd.quantize(Decimal('0.01'))

    payload = {
        'intent': 'CAPTURE',
        'purchase_units': [
            {
                'reference_id': str(payment_transaction.id),
                'description': f'Dating Partner Payment - Transaction #{payment_transaction.id}',
                'custom_id': str(payment_transaction.id),
                'amount': {
                    'currency_code': 'USD',
                    'value': str(amount_value),
                },
            }
        ],
        'application_context': {
            'brand_name': 'Ensolanka Date in Sri Lanka',
            'landing_page': 'BILLING',
            'user_action': 'PAY_NOW',
            'return_url': return_url,
            'cancel_url': cancel_url,
        },
    }

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}',
        'PayPal-Request-Id': f'dating-partner-payable-{payment_transaction.id}',
    }

    response = requests.post(
        create_order_url,
        json=payload,
        headers=headers,
        timeout=30,
    )

    if response.status_code not in [200, 201]:
        raise Exception(f"PayPal order creation failed: {response.text}")

    return response.json()


@login_required
def dating_partner_paypal_payment_success(request, transaction_id):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    paypal_order_id = request.GET.get('token')

    if not paypal_order_id:
        messages.error(request, "PayPal payment order not found.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=transaction_id
        )

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
    )

    if payment_transaction.status == 'paid':
        messages.success(request, "This payment has already been completed.")
        return redirect(
            'dating_app:dating_partner_payment_success',
            transaction_id=payment_transaction.id
        )

    if payment_transaction.payment_method not in ['paypal', 'mixed_paypal_wallet']:
        messages.error(request, "Invalid payment method for PayPal confirmation.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    if payment_transaction.gateway_session_id and payment_transaction.gateway_session_id != paypal_order_id:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = "PayPal order ID mismatch."
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "PayPal payment verification failed.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    try:
        capture_data = capture_paypal_order(paypal_order_id)

    except Exception as e:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"PayPal capture failed: {str(e)}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "Could not capture PayPal payment.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    paypal_status = capture_data.get('status')

    if paypal_status != 'COMPLETED':
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"PayPal payment status was not completed: {paypal_status}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "PayPal payment was not completed.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    try:
        purchase_units = capture_data.get('purchase_units', [])
        first_purchase_unit = purchase_units[0] if purchase_units else {}
        payments = first_purchase_unit.get('payments', {})
        captures = payments.get('captures', [])
        first_capture = captures[0] if captures else {}

        captured_amount = first_capture.get('amount', {})
        captured_value = Decimal(
            str(captured_amount.get('value', '0.00'))
        ).quantize(Decimal('0.01'))
        captured_currency = captured_amount.get('currency_code')

        expected_amount = payment_transaction.gateway_amount_usd.quantize(
            Decimal('0.01')
        )

        if captured_currency != 'USD' or captured_value != expected_amount:
            payment_transaction.status = 'failed'
            payment_transaction.failure_reason = (
                f"PayPal amount mismatch. Expected USD {expected_amount}, "
                f"received {captured_currency} {captured_value}."
            )
            payment_transaction.failed_at = timezone.now()
            payment_transaction.save(update_fields=[
                'status',
                'failure_reason',
                'failed_at',
                'updated_at',
            ])

            messages.error(request, "PayPal payment amount verification failed.")
            return redirect(
                'dating_app:dating_partner_payment_failed',
                transaction_id=payment_transaction.id
            )

        paypal_capture_id = first_capture.get('id', paypal_order_id)

    except Exception as e:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"PayPal capture response parsing failed: {str(e)}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "PayPal payment verification failed.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    try:
        with transaction.atomic():
            locked_transaction = PaymentTransaction.objects.select_for_update().get(
                id=payment_transaction.id,
                user=request.user,
                profile_type='dating_partner',
            )

            if locked_transaction.status == 'paid':
                messages.success(request, "This payment has already been completed.")
                return redirect(
                    'dating_app:dating_partner_payment_success',
                    transaction_id=locked_transaction.id
                )

            wallet_deduction = locked_transaction.wallet_deduction_usd or Decimal('0.00')

            if wallet_deduction > Decimal('0.00'):
                wallet = WalletAccount.objects.select_for_update().get(
                    user=request.user,
                    profile_type='dating_partner',
                )

                if wallet.balance_usd < wallet_deduction:
                    locked_transaction.status = 'failed'
                    locked_transaction.failure_reason = (
                        "Wallet balance was insufficient during PayPal success confirmation."
                    )
                    locked_transaction.failed_at = timezone.now()
                    locked_transaction.save(update_fields=[
                        'status',
                        'failure_reason',
                        'failed_at',
                        'updated_at',
                    ])

                    messages.error(
                        request,
                        "Payment was received by PayPal, but wallet deduction failed. "
                        "Please contact support."
                    )
                    return redirect(
                        'dating_app:dating_partner_payment_failed',
                        transaction_id=locked_transaction.id
                    )

                wallet.balance_usd -= wallet_deduction
                wallet.save(update_fields=['balance_usd'])

            mark_result = mark_dating_partner_transaction_items_paid(
                payment_transaction=locked_transaction,
                notes=f"Paid by PayPal. Transaction #{locked_transaction.id}",
            )

            if not mark_result["success"]:
                locked_transaction.status = 'failed'
                locked_transaction.failure_reason = "\n".join(mark_result["failed"])
                locked_transaction.failed_at = timezone.now()
                locked_transaction.save(update_fields=[
                    'status',
                    'failure_reason',
                    'failed_at',
                    'updated_at',
                ])

                messages.error(
                    request,
                    "PayPal payment was received, but the system could not complete all payment actions. "
                    "Please contact support."
                )

                return redirect(
                    'dating_app:dating_partner_payment_failed',
                    transaction_id=locked_transaction.id
                )

            locked_transaction.gateway_session_id = paypal_order_id
            locked_transaction.gateway_transaction_id = paypal_capture_id
            locked_transaction.status = 'paid'
            locked_transaction.paid_at = timezone.now()
            locked_transaction.failure_reason = ''
            locked_transaction.save(update_fields=[
                'gateway_session_id',
                'gateway_transaction_id',
                'status',
                'paid_at',
                'failure_reason',
                'updated_at',
            ])

    except Exception as e:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"Database payment completion failed: {str(e)}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(
            request,
            "Payment was verified, but the system could not complete the payment record. "
            "Please contact support."
        )

        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    request.session.pop('dating_payment_transaction_id', None)
    request.session.pop('dating_checkout_selected_ids', None)
    request.session.pop('dating_checkout_total', None)
    request.session.pop('dating_checkout_profile_type', None)
    request.session.pop('dating_use_wallet', None)
    request.session.pop('dating_wallet_deduction', None)

    messages.success(request, "PayPal payment completed successfully.")

    return redirect(
        'dating_app:dating_partner_payment_success',
        transaction_id=payment_transaction.id
    )



def about_us_date(request):
    return render(request, 'dating_app/about_us_date.html')

def terms_page(request):
    return render(request, 'dating_app/terms.html')

def faq_page(request):
    return render(request, 'dating_app/faq.html')

def privacy_policy_page(request):
    return render(request, 'dating_app/privacy_policy.html')

def refund_payment_policy_page(request):
    return render(request, 'dating_app/refund_payment_policy.html')

def cookie_policy_page(request):
    return render(request, 'dating_app/cookie_policy.html')

def disclaimer_page(request):
    return render(request, 'dating_app/disclaimer.html')

def contact_page(request):
    if request.method == 'POST':
        form = ContactMessageForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(
                reverse('dating_app:success_page') +
                '?type=contact'
            )
    else:
        form = ContactMessageForm()
    return render(request, 'dating_app/contact_page.html', {'form': form})

def success_page(request):
    success_type = request.GET.get('type', 'general')

    page_data = {
        'general': {
            'title': 'Thank You',
            'heading': 'Thank You for Reaching Out',
            'message': 'Your submission has been received successfully.',
            'button_1_text': 'Go to Home',
            'button_1_url': 'dating_app:home_dating',
            'button_2_text': 'About Ensolanka',
            'button_2_url': 'dating_app:about_us_date',
        },
        'signup': {
            'title': 'Signup Submitted',
            'heading': 'Your Free Signup Has Been Submitted',
            'message': 'Thank you for sharing your details. We have received your information successfully and created your account.',
            'button_1_text': 'Go to Home',
            'button_1_url': 'dating_app:home_dating',
            'button_2_text': 'About Ensolanka',
            'button_2_url': 'dating_app:about_us_date',
        },
        'consultation': {
            'title': 'Consultation Requested',
            'heading': 'Your Consultation Request Has Been Submitted',
            'message': 'Thank you. Your consultation request has been received. We can now review your request and discuss the most suitable next step.',
            'button_1_text': 'Go to Home',
            'button_1_url': 'dating_app:home_dating',
            'button_2_text': 'Contact Us',
            'button_2_url': 'dating_app:contact_page',
        },
        'contact': {
            'title': 'Message Sent',
            'heading': 'Your Message Has Been Sent Successfully',
            'message': 'Thank you for contacting us. We have received your message and will review it as soon as possible.',
            'button_1_text': 'Go to Home',
            'button_1_url': 'dating_app:home_dating',
            'button_2_text': 'Contact Us',
            'button_2_url': 'dating_app:contact_page',
        },
    }

    context = page_data.get(success_type, page_data['general']).copy()

    context['signup_type'] = success_type
    context['username'] = request.session.pop('new_account_username', None)
    context['password'] = request.session.pop('new_account_password', None)
    context['new_account_email'] = request.session.pop('new_account_email', None)
    context['account_role'] = request.session.pop('account_role', None)

    return render(request, 'dating_app/success_page.html', context)

class DatingPasswordResetView(PasswordResetView):
    template_name = 'registration/dating_password_reset.html'
    form_class = DatingPasswordResetForm
    email_template_name = 'emails/dating_app/password_reset_email.txt'
    html_email_template_name = 'emails/dating_app/password_reset_email.html'
    subject_template_name = 'emails/dating_app/password_reset_subject.txt'
    success_url = reverse_lazy('dating_app:dating_password_reset_done')
    from_email = "Date in Sri Lanka <dsjayathunge@gmail.com>" 

    def get_extra_email_context(self):
        return {
            "site_url": self.request.build_absolute_uri("/"),
        }

    def form_valid(self, form):
        self.extra_email_context = self.get_extra_email_context()
        email = form.cleaned_data.get('email')

        user_exists_as_dating = User.objects.filter(
            email__iexact=email,
            dating_profile__isnull=False,
            is_active=True
        ).exists()

        if not user_exists_as_dating:
            messages.warning(
                self.request,
                "If this email belongs to a registered dating partner account, "
                "password reset instructions will be sent."
            )

        return super().form_valid(form)


class DatingPasswordResetDoneView(PasswordResetDoneView):
    template_name = 'registration/dating_password_reset_done.html'


class DatingPasswordResetConfirmView(PasswordResetConfirmView):
    template_name = 'registration/dating_password_reset_confirm.html'
    success_url = reverse_lazy('dating_app:dating_password_reset_complete')


class DatingPasswordResetCompleteView(PasswordResetCompleteView):
    template_name = 'registration/dating_password_reset_complete.html'


@login_required
def dating_partner_profile_page(request):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a dating partner profile.")

    default_image = 'expat_life/images/default-profile-neutral.png'
    if partner.gender == 'male':
        default_image = 'expat_life/images/default-profile-male.png'
    elif partner.gender == 'female':
        default_image = 'expat_life/images/default-profile-female.png'

    additional_photos = partner.additional_photos.all().order_by('display_order', '-uploaded_at')
    photo_form = DatingPartnerPhotoForm()

    return render(request, 'dating_app/dating_partner_profile.html', {
        'partner': partner,
        'default_profile_image': default_image,
        'additional_photos': additional_photos,
        'photo_form': photo_form,
    })

@login_required
def upload_dating_partner_additional_photo(request):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a dating partner profile.")

    if request.method != 'POST':
        return redirect('dating_app:dating_partner_profile_page')

    if partner.additional_photos.count() >= 5:
        messages.warning(request, "You can upload a maximum of 5 additional photos.")
        return redirect('dating_app:dating_partner_profile_page')

    form = DatingPartnerPhotoForm(request.POST, request.FILES)

    if form.is_valid():
        photo = form.save(commit=False)
        photo.profile = partner
        photo.status = 'pending'
        photo.save()
        messages.success(request, "Additional photo uploaded successfully and sent for review.")
    else:
        messages.error(request, "Could not upload the additional photo. Please check the form.")

    return redirect('dating_app:dating_partner_profile_page')

@login_required
def delete_dating_partner_additional_photo(request, photo_id):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a dating partner profile.")

    photo = get_object_or_404(DatingPartnerPhoto, id=photo_id, profile=partner)

    if request.method == 'POST':
        photo.delete()
        messages.success(request, "Additional photo deleted successfully.")

    return redirect('dating_app:dating_partner_profile_page')


@login_required
def edit_dating_partner_profile(request):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a dating partner profile.")

    if request.method == 'POST':
        form = DatingPartnerProfileEditForm(request.POST, instance=partner)
        if form.is_valid():
            form.save()
            messages.success(request, "Profile updated successfully.")
            return redirect('dating_app:dating_partner_profile_page')
    else:
        form = DatingPartnerProfileEditForm(instance=partner)

    additional_photos = partner.additional_photos.all().order_by('display_order', '-uploaded_at')
    photo_form = DatingPartnerPhotoForm()

    return render(request, 'dating_app/edit_dating_partner_profile.html', {
        'form': form,
        'partner': partner,
        'additional_photos': additional_photos,
        'photo_form': photo_form,
    })


@login_required
@require_POST
def upload_dating_profile_image(request):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return JsonResponse({
            'success': False,
            'error': 'Dating partner profile not found.'
        }, status=403)

    if 'profile_photo' not in request.FILES:
        return JsonResponse({
            'success': False,
            'error': 'No image was uploaded.'
        }, status=400)

    form = DatingPartnerProfileImageForm(request.POST, request.FILES, instance=partner)

    if form.is_valid():
        form.save()
        partner.refresh_from_db()

        image_url = partner.profile_photo.url if partner.profile_photo else ''
        return JsonResponse({
            'success': True,
            'image_url': image_url,
            'message': 'Profile image updated successfully.'
        })

    error_message = "Invalid image upload."
    if form.errors.get('profile_photo'):
        error_message = form.errors['profile_photo'][0]

    return JsonResponse({
        'success': False,
        'error': error_message
    }, status=400)


@login_required
def change_dating_partner_username(request):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a dating partner profile.")

    if request.method == 'POST':
        form = UsernameChangeForm(request.POST, instance=request.user, user=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, "Username updated successfully.")
            return redirect('dating_app:dating_partner_profile_page')
    else:
        form = UsernameChangeForm(instance=request.user, user=request.user)

    return render(request, 'dating_app/change_dating_partner_username.html', {
        'form': form,
        'partner': partner,
    })


@login_required
def change_dating_partner_password(request):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a dating partner profile.")

    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, "Password changed successfully.")
            return redirect('dating_app:dating_partner_profile_page')
    else:
        form = PasswordChangeForm(request.user)

    return render(request, 'dating_app/change_dating_partner_password.html', {
        'form': form,
        'partner': partner,
    })



def generate_dating_partner_username(full_name):
    base_name = re.sub(r'[^a-zA-Z0-9]', '', full_name.lower())
    if not base_name:
        base_name = 'datingpartner'

    base = f"dp_{base_name}"
    username = base
    counter = 1

    while User.objects.filter(username=username).exists():
        username = f"{base}{counter}"
        counter += 1

    return username


def generate_random_password(length=10):
    chars = string.ascii_letters + string.digits
    return ''.join(random.choice(chars) for _ in range(length))


@transaction.atomic
def partner_register(request):
    if request.method == 'POST':
        form = DatingPartnerRegistrationForm(request.POST, request.FILES)

        if form.is_valid():
            partner = form.save(commit=False)

            email = form.cleaned_data['email'].strip().lower()
            full_name = form.cleaned_data['full_name'].strip()

            existing_user = User.objects.filter(email__iexact=email).first()
            if existing_user:
                form.add_error('email', 'An account with this email already exists.')
            else:
                username = generate_dating_partner_username(full_name)
                password = generate_random_password()

                name_parts = full_name.split()
                first_name = name_parts[0] if name_parts else ''
                last_name = ' '.join(name_parts[1:]) if len(name_parts) > 1 else ''

                user = User.objects.create_user(
                    username=username,
                    email=email,
                    password=password,
                    first_name=first_name,
                    last_name=last_name
                )

                partner.user = user
                partner.email = email
                partner.status = 'pending'
                partner.is_public = False
                partner.save()

                update_dating_partner_payable_items(user)

                transaction.on_commit(
                    lambda: send_dating_partner_signup_welcome_email(
                        user=user,
                        full_name=full_name,
                        email=email,
                        username=username,
                        temporary_password=password,
                        request=request,
                    )
                )

                login(request, user)

                request.session['new_account_username'] = username
                request.session['new_account_password'] = password
                request.session['new_account_email'] = email
                request.session['account_role'] = 'Dating Partner'
                request.session['just_signed_up'] = True

                messages.success(
                    request,
                    "Your profile has been submitted successfully and is now pending review."
                )
                return redirect('dating_app:dating_partner_dashboard')
        else:
            messages.error(request, "Please correct the errors below and try again.")
    else:
        form = DatingPartnerRegistrationForm()

    return render(request, 'dating_app/partner_register.html', {'form': form})




@login_required
def dating_partner_dashboard(request):
    partner = getattr(request.user, 'dating_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a dating partner profile.")

    default_profile_image = 'expat_life/images/default-profile-neutral.png'

    if partner.gender:
        if partner.gender == 'male':
            default_profile_image = 'expat_life/images/default-profile-male.png'
        elif partner.gender == 'female':
            default_profile_image = 'expat_life/images/default-profile-female.png'
        else:
            default_profile_image = 'expat_life/images/default-profile-neutral.png'

    return render(request, 'dating_app/dating_partner_dashboard.html', {
        'partner': partner,
        'default_profile_image': default_profile_image,
        'just_signed_up': request.session.pop('just_signed_up', False),
        'username': request.session.pop('new_account_username', None),
        'password': request.session.pop('new_account_password', None),
        'new_account_email': request.session.pop('new_account_email', None),
        'account_role': request.session.pop('account_role', None),
    })


    
class DatingPartnerLoginView(LoginView):
    template_name = 'registration/dating_partner_login.html'

    def form_valid(self, form):
        response = super().form_valid(form)
        user = self.request.user

        # Check if user has dating partner profile
        dating_profile = getattr(user, 'dating_profile', None)

        if dating_profile:
            return response

        # ❌ Not a dating partner → handle gracefully
        messages.warning(
            self.request,
            "This login is only for dating partners. Please use the correct login page for your account."
        )

        # Logout wrong user
        logout(self.request)

        # Redirect based on profile type
        if hasattr(user, 'foreigner_profile'):
            return redirect('expat_life:foreigner_login')
        elif hasattr(user, 'rental_owner_profile'):
            return redirect('rental_app:rental_owner_login')
        elif hasattr(user, 'service_partner_profile'):
            return redirect('service_partner_app:service_partner_login')

        # fallback → home
        return redirect('dating_app:home_dating')

    def get_success_url(self):
        return self.get_redirect_url() or reverse_lazy('dating_app:dating_partner_dashboard')


def home_dating(request):
    dating_profile = None

    if request.user.is_authenticated:
        dating_profile = getattr(request.user, 'dating_profile', None)

    return render(request, 'dating_app/home_dating.html', {
        'dating_profile': dating_profile,
    })

"""
def dating_home(request):
    foreigner_profile = getattr(request.user, 'foreigner_profile', None)

    show_all_approved_profiles = False

    if request.user.is_authenticated and foreigner_profile:
        lead_confirmed = bool(
            foreigner_profile.lead and foreigner_profile.lead.is_confirmed_foreigner
        )

        show_all_approved_profiles = (
            foreigner_profile.status == 'approved'
            and foreigner_profile.is_confirmed is True
            and foreigner_profile.can_view_private_listings is True
            and lead_confirmed is True
        )

    if show_all_approved_profiles:
        base_profiles = DatingPartnerProfile.objects.filter(
            status='approved',
            is_featured=True
        )
    else:
        base_profiles = DatingPartnerProfile.objects.filter(
            status='approved',
            is_public=True,
            is_featured=True
        )

    featured_profiles = base_profiles.order_by('-created_at')[:6]
    latest_profiles = base_profiles.order_by('-created_at')[:25]

    context = {
        'featured_profiles': featured_profiles,
        'latest_profiles': latest_profiles,
    }
    return render(request, 'dating_app/dating_home.html', context)
"""


def partner_registration_success(request):
    return render(request, 'dating_app/partner_registration_success.html')


def public_partner_list(request):
    dating_profile = None
    is_dating_partner_authenticated = False
    is_approved_dating_partner = False
    can_view_partner_profile_preview = False
    is_public_limited_preview = True

    if request.user.is_authenticated:
        dating_profile = getattr(request.user, 'dating_profile', None)

        if dating_profile:
            is_dating_partner_authenticated = True

            if dating_profile.status == 'approved':
                is_approved_dating_partner = True
                can_view_partner_profile_preview = True
                is_public_limited_preview = False

    # -------------------------------------------------
    # Profile visibility logic
    # -------------------------------------------------
    # In the Dating App, local dating partners and public visitors
    # should only see profiles that are:
    #   - approved
    #   - explicitly public
    #
    # Featured status is intentionally NOT used here.
    # Private profiles must never appear in this local-partner listing.
    profiles = DatingPartnerProfile.objects.filter(
        status='approved',
        is_public=True
    )

    # -------------------------------------------------
    # Filters
    # -------------------------------------------------
    gender = request.GET.get('gender', '').strip()
    goal = request.GET.get('goal', '').strip()
    city = request.GET.get('city', '').strip()

    if gender:
        profiles = profiles.filter(gender=gender)

    if goal:
        profiles = profiles.filter(relationship_goal=goal)

    if city:
        profiles = profiles.filter(city__icontains=city)

    # Featured priority is not useful inside the Dating App partner directory.
    profiles = profiles.order_by('-created_at')

    # -------------------------------------------------
    # Pagination
    # -------------------------------------------------
    paginator = Paginator(profiles, 9)
    page_number = request.GET.get('page')

    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)

    # Keep filters while moving between pages
    query_params = request.GET.copy()

    if 'page' in query_params:
        query_params.pop('page')

    query_string = query_params.urlencode()

    context = {
        'profiles': page_obj,
        'page_obj': page_obj,
        'paginator': paginator,
        'total_results': paginator.count,
        'query_string': query_string,

        'dating_profile': dating_profile,
        'is_dating_partner_authenticated': is_dating_partner_authenticated,
        'is_approved_dating_partner': is_approved_dating_partner,
        'can_view_partner_profile_preview': can_view_partner_profile_preview,
        'is_public_limited_preview': is_public_limited_preview,

        # Useful for template display control
        'show_full_profile_preview': can_view_partner_profile_preview,

        # Important: private dating profiles are never previewed here
        'show_private_profile_preview': False,

        'selected_gender': gender,
        'selected_goal': goal,
        'selected_city': city,
    }

    return render(request, 'dating_app/public_partner_list.html', context)





def public_partner_detail(request, pk):
    dating_profile = None
    is_dating_partner_authenticated = False
    is_approved_dating_partner = False
    can_view_partner_profile_preview = False
    is_public_limited_preview = True

    if request.user.is_authenticated:
        dating_profile = getattr(request.user, 'dating_profile', None)

        if dating_profile:
            is_dating_partner_authenticated = True

            if dating_profile.status == 'approved':
                is_approved_dating_partner = True
                can_view_partner_profile_preview = True
                is_public_limited_preview = False

    # -------------------------------------------------
    # Profile access logic
    # -------------------------------------------------
    if is_approved_dating_partner:
        # Approved local dating partners can preview all approved profiles.
        profile = get_object_or_404(
            DatingPartnerProfile,
            pk=pk,
            status='approved',
        )

        additional_photos = profile.additional_photos.filter(
            status='approved'
        ).order_by('display_order', '-uploaded_at')

    elif is_dating_partner_authenticated:
        # Signed-up but not approved local partners can preview public profiles only.
        profile = get_object_or_404(
            DatingPartnerProfile,
            pk=pk,
            status='approved',
            is_public=True,
        )

        additional_photos = profile.additional_photos.filter(
            status='approved',
            is_public=True
        ).order_by('display_order', '-uploaded_at')

    else:
        # Public visitors can preview only featured public profile examples.
        profile = get_object_or_404(
            DatingPartnerProfile,
            pk=pk,
            status='approved',
            is_public=True,
            is_featured=True,
        )

        additional_photos = profile.additional_photos.filter(
            status='approved',
            is_public=True
        ).order_by('display_order', '-uploaded_at')

    context = {
        'profile': profile,
        'additional_photos': additional_photos,

        'dating_profile': dating_profile,
        'is_dating_partner_authenticated': is_dating_partner_authenticated,
        'is_approved_dating_partner': is_approved_dating_partner,
        'can_view_partner_profile_preview': can_view_partner_profile_preview,
        'is_public_limited_preview': is_public_limited_preview,

        # Template control flags
        'show_full_profile_preview': can_view_partner_profile_preview,
        'show_private_profile_preview': is_approved_dating_partner,
    }

    return render(request, 'dating_app/public_partner_detail.html', context)


@login_required
def express_dating_interest(request, pk):
    foreigner_profile = getattr(request.user, 'foreigner_profile', None)

    if not foreigner_profile:
        messages.warning(
            request,
            "Only registered foreigner users can express interest in dating profiles."
        )
        return redirect('dating_app:home_dating')

    if foreigner_profile.status != 'approved':
        messages.warning(
            request,
            "Your foreigner profile is not approved yet."
        )
        return redirect('expat_life:foreigner_dashboard')

    # If confirmed foreigners can view both public and private profiles
    if foreigner_profile.can_view_private_listings:
        partner = get_object_or_404(
            DatingPartnerProfile,
            pk=pk,
            status='approved'
        )
    else:
        partner = get_object_or_404(
            DatingPartnerProfile,
            pk=pk,
            status='approved',
        )

    if request.method == 'POST':
        form = DatingInterestForm(request.POST)

        if form.is_valid():
            message = form.cleaned_data.get('message', '')

            interest, created = DatingInterest.objects.get_or_create(
                foreigner=foreigner_profile,
                partner=partner,
                defaults={
                    'message': message,
                    'status': 'interested',
                }
            )

            if created:
                send_dating_partner_interest_notification_email(
                    partner=partner,
                    foreigner_profile=foreigner_profile,
                    interest=interest,
                    request=request,
                )

                messages.success(
                    request,
                    "Your interest has been sent successfully."
                )

            else:
                if interest.status == 'withdrawn':
                    interest.status = 'interested'
                    interest.message = message
                    interest.save(update_fields=['status', 'message'])

                    send_dating_partner_interest_notification_email(
                        partner=partner,
                        foreigner_profile=foreigner_profile,
                        interest=interest,
                        request=request,
                    )

                    messages.success(
                        request,
                        "Your interest has been submitted again successfully."
                    )

                elif interest.status in ['matched', 'closed']:
                    messages.warning(
                        request,
                        "This interest cannot be changed because it is already matched or closed. Please contact our team for support."
                    )

                else:
                    if message:
                        interest.message = message
                        interest.save(update_fields=['message'])

                    messages.info(
                        request,
                        "You have already expressed interest in this dating profile. Your message was updated."
                    )

            return redirect('expat_life:public_partner_detail', pk=partner.pk)

    messages.error(request, "Invalid request.")
    return redirect('expat_life:public_partner_detail', pk=partner.pk)

@login_required
@require_POST
def withdraw_dating_interest(request, pk):
    foreigner_profile = getattr(request.user, 'foreigner_profile', None)

    if not foreigner_profile:
        messages.warning(
            request,
            "Only registered foreigner users can cancel dating profile interests."
        )
        return redirect('dating_app:home_dating')

    if foreigner_profile.status != 'approved':
        messages.warning(
            request,
            "Your foreigner profile is not approved yet."
        )
        return redirect('expat_life:foreigner_dashboard')

    partner = get_object_or_404(
        DatingPartnerProfile,
        pk=pk,
        status='approved'
    )

    interest = get_object_or_404(
        DatingInterest,
        foreigner=foreigner_profile,
        partner=partner
    )

    if interest.status == 'withdrawn':
        messages.info(
            request,
            "You have already cancelled your interest in this dating profile."
        )
        return redirect('expat_life:public_partner_detail', pk=partner.pk)

    if interest.status in ['matched', 'closed']:
        messages.warning(
            request,
            "This interest cannot be cancelled because it is already matched or closed. Please contact our team for support."
        )
        return redirect('expat_life:public_partner_detail', pk=partner.pk)

    interest.status = 'withdrawn'
    interest.save(update_fields=['status'])

    messages.success(
        request,
        "Your interest has been cancelled successfully."
    )

    return redirect('expat_life:public_partner_detail', pk=partner.pk)

def calculate_age(date_of_birth):
    if not date_of_birth:
        return None
    today = date.today()
    return (
        today.year
        - date_of_birth.year
        - ((today.month, today.day) < (date_of_birth.month, date_of_birth.day))
    )


@login_required
def interested_foreigners_list(request):
    partner = getattr(request.user, 'dating_profile', None)

    if not partner:
        messages.error(request, "This account is not registered as a dating partner.")
        return redirect('dating_app:home_dating')

    if partner.status != 'approved':
        messages.warning(request, "Your dating partner profile is not approved yet.")
        return redirect('dating_app:dating_partner_dashboard')

    interests = (
        DatingInterest.objects
        .filter(partner=partner)
        .select_related('foreigner', 'foreigner__lead', 'foreigner__user')
        .order_by('-created_at')
    )

    foreigner_cards = []

    for interest in interests:
        foreigner = interest.foreigner
        lead = foreigner.lead

        age = None
        if lead and hasattr(lead, 'date_of_birth') and lead.date_of_birth:
            age = calculate_age(lead.date_of_birth)

        foreigner_cards.append({
            'interest': interest,
            'foreigner': foreigner,
            'lead': lead,
            'name': lead.full_name if lead and lead.full_name else foreigner.user.username,
            'country': lead.country if lead and lead.country else '',
            'monthly_budget': lead.get_monthly_budget_display() if lead and lead.monthly_budget else '',
            'age': age,
            'profile_image': foreigner.profile_image.url if foreigner.profile_image else '',
        })

    context = {
        'partner': partner,
        'foreigner_cards': foreigner_cards,
        'total_interests': len(foreigner_cards),
    }
    return render(request, 'dating_app/interested_foreigners_list.html', context)

@login_required
def dating_partner_payment_center(request):
    dating_partner = getattr(request.user, 'dating_profile', None)
    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    # Ensure dating payable items exist / refresh unpaid ones
    update_dating_partner_payable_items(request.user)

    # --- NEW: get or create the foreigner wallet ---
    wallet, created = WalletAccount.objects.get_or_create(
        user=request.user,
        profile_type='dating_partner',
        defaults={'balance_usd': 0}   # not strictly needed because default=0, but explicit
    )

    payable_items = list(
        UserPayableItem.objects.filter(
            user=request.user,
            profile_type='dating_partner',
            is_active=True
        )
    )

    payment_order = {
        'dating_confirmation': 1,
        'dating_partner_featured': 2,
        'other': 99,
    }

    payable_items.sort(
        key=lambda item: (
            payment_order.get(item.payment_for, 50),
            item.due_date or item.created_at.date(),
            item.created_at,
        )
    )

    due_items = [
        item for item in payable_items
        if item.payment_status == 'due'
    ]

    upcoming_items = [
        item for item in payable_items
        if item.payment_status == 'upcoming' and not item.is_optional
    ]

    optional_items = [
        item for item in payable_items
        if item.is_optional and item.payment_status not in ['due', 'paid']
    ]

    paid_items = [
        item for item in payable_items
        if item.payment_status == 'paid'
    ]

    selectable_item_ids = [
        item.id for item in payable_items
        if item.payment_status == 'due' and item.amount_usd > 0
    ]

    total_due = sum((item.amount_usd for item in due_items), Decimal('0.00'))
    total_upcoming = sum((item.amount_usd for item in upcoming_items), Decimal('0.00'))
    total_paid = sum((item.amount_usd for item in paid_items), Decimal('0.00'))

    context = {
        'dating_partner': dating_partner,
        'wallet': wallet, 
        'payable_items': payable_items,
        'due_items': due_items,
        'upcoming_items': upcoming_items,
        'optional_items': optional_items,
        'paid_items': paid_items,
        'selectable_item_ids': selectable_item_ids,
        'total_due': total_due,
        'total_upcoming': total_upcoming,
        'total_paid': total_paid,
    }
    return render(request, 'dating_app/payment_center.html', context)

@login_required
def dating_partner_payment_checkout(request):
    dating_partner = getattr(request.user, 'dating_profile', None)
    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    if request.method != 'POST':
        messages.error(request, "Please select at least one payment item first.")
        return redirect('dating_app:dating_partner_payment_center')
    
    # --- NEW: get or create the foreigner wallet ---
    wallet, created = WalletAccount.objects.get_or_create(
        user=request.user,
        profile_type='dating_partner',
        defaults={'balance_usd': Decimal('0.00')}
    )

    selected_ids = request.POST.getlist('selected_items')

    if not selected_ids:
        messages.error(request, "Please select at least one payment item.")
        return redirect('dating_app:dating_partner_payment_center')

    payable_items = list(
        UserPayableItem.objects.filter(
            id__in=selected_ids,
            user=request.user,
            profile_type='dating_partner',
            is_active=True,
            payment_status='due'
        ).exclude(amount_usd__lte=0)
    )

    if not payable_items:
        messages.error(request, "No valid payable items were selected.")
        return redirect('dating_app:dating_partner_payment_center')

    total_amount = sum((item.amount_usd for item in payable_items), Decimal('0.00'))

    context = {
        'dating_partner': dating_partner,
        'wallet': wallet,  
        'payable_items': payable_items,
        'selected_ids': [str(item.id) for item in payable_items],
        'total_amount': total_amount,
    }
    return render(request, 'dating_app/payment_checkout.html', context)


@login_required
def dating_partner_payment_checkout_pay(request):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    if request.method != 'POST':
        messages.error(request, "Invalid payment request.")
        return redirect('dating_app:dating_partner_payment_center')

    # ---------------------------------------------------------
    # 1. Collect selected items and checkout options
    # ---------------------------------------------------------
    selected_ids = request.POST.getlist('selected_items')
    payment_method = request.POST.get('payment_method')
    use_wallet = request.POST.get('use_wallet') == '1'

    if not selected_ids:
        messages.error(request, "Please select at least one payment item.")
        return redirect('dating_app:dating_partner_payment_center')

    payable_items = list(
        UserPayableItem.objects.filter(
            id__in=selected_ids,
            user=request.user,
            profile_type='dating_partner',
            is_active=True,
            payment_status='due',
        ).exclude(amount_usd__lte=0)
    )

    if not payable_items:
        messages.error(request, "No valid payable items were selected.")
        return redirect('dating_app:dating_partner_payment_center')

    total_amount = sum(
        (item.amount_usd for item in payable_items),
        Decimal('0.00')
    ).quantize(Decimal('0.01'))

    # ---------------------------------------------------------
    # 2. Wallet calculation
    # ---------------------------------------------------------
    wallet, created = WalletAccount.objects.get_or_create(
        user=request.user,
        profile_type='dating_partner',
        defaults={'balance_usd': Decimal('0.00')}
    )

    wallet_balance = wallet.balance_usd or Decimal('0.00')
    wallet_deduction = Decimal('0.00')
    amount_to_charge = total_amount

    if use_wallet and wallet_balance > Decimal('0.00'):
        wallet_deduction = min(wallet_balance, total_amount).quantize(Decimal('0.01'))
        amount_to_charge = (total_amount - wallet_deduction).quantize(Decimal('0.01'))

    # ---------------------------------------------------------
    # 3. Wallet-only payment
    # ---------------------------------------------------------
    if amount_to_charge <= Decimal('0.00'):
        with transaction.atomic():
            locked_wallet = WalletAccount.objects.select_for_update().get(
                id=wallet.id
            )

            if locked_wallet.balance_usd < wallet_deduction:
                messages.error(
                    request,
                    "Your wallet balance changed. Please try again."
                )
                return redirect('dating_app:dating_partner_payment_center')

            payment_transaction = PaymentTransaction.objects.create(
                user=request.user,
                profile_type='dating_partner',
                payment_purpose='payable_items',
                payment_method='wallet',
                total_amount_usd=total_amount,
                wallet_deduction_usd=wallet_deduction,
                gateway_amount_usd=Decimal('0.00'),
                status='paid',
                paid_at=timezone.now(),
            )

            for item in payable_items:
                PaymentTransactionItem.objects.create(
                    transaction=payment_transaction,
                    payable_item=item,
                    amount_usd=item.amount_usd,
                )

            mark_result = mark_dating_partner_transaction_items_paid(
                payment_transaction=payment_transaction,
                notes=f"Paid using wallet. Transaction #{payment_transaction.id}",
            )

            if not mark_result["success"]:
                payment_transaction.status = 'failed'
                payment_transaction.failure_reason = "\n".join(mark_result["failed"])
                payment_transaction.failed_at = timezone.now()
                payment_transaction.save(update_fields=[
                    'status',
                    'failure_reason',
                    'failed_at',
                    'updated_at',
                ])

                messages.error(
                    request,
                    "Payment could not be fully completed. Please contact support."
                )

                return redirect(
                    'dating_app:dating_partner_payment_failed',
                    transaction_id=payment_transaction.id
                )

            locked_wallet.balance_usd -= wallet_deduction
            locked_wallet.save(update_fields=['balance_usd'])

        # Clear old checkout session values
        request.session.pop('dating_payment_transaction_id', None)
        request.session.pop('dating_checkout_selected_ids', None)
        request.session.pop('dating_checkout_total', None)
        request.session.pop('dating_checkout_profile_type', None)
        request.session.pop('dating_use_wallet', None)
        request.session.pop('dating_wallet_deduction', None)

        messages.success(
            request,
            "Payment completed successfully using your wallet balance."
        )

        return redirect(
            'dating_app:dating_partner_payment_success',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 4. Validate gateway payment method
    # ---------------------------------------------------------
    if payment_method == 'stripe':
        final_payment_method = (
            'mixed_stripe_wallet'
            if wallet_deduction > Decimal('0.00')
            else 'stripe'
        )

    elif payment_method == 'paypal':
        final_payment_method = (
            'mixed_paypal_wallet'
            if wallet_deduction > Decimal('0.00')
            else 'paypal'
        )

    else:
        messages.error(request, "Please choose a valid payment method.")
        return redirect('dating_app:dating_partner_payment_center')

    # ---------------------------------------------------------
    # 5. Create pending payment transaction
    # ---------------------------------------------------------
    with transaction.atomic():
        payment_transaction = PaymentTransaction.objects.create(
            user=request.user,
            profile_type='dating_partner',
            payment_purpose='payable_items',
            payment_method=final_payment_method,
            total_amount_usd=total_amount,
            wallet_deduction_usd=wallet_deduction,
            gateway_amount_usd=amount_to_charge,
            status='pending',
        )

        for item in payable_items:
            PaymentTransactionItem.objects.create(
                transaction=payment_transaction,
                payable_item=item,
                amount_usd=item.amount_usd,
            )

    # ---------------------------------------------------------
    # 6. Store checkout details in session for gateway step
    # ---------------------------------------------------------
    request.session['dating_payment_transaction_id'] = payment_transaction.id
    request.session['dating_checkout_selected_ids'] = [
        item.id for item in payable_items
    ]
    request.session['dating_checkout_total'] = str(amount_to_charge)
    request.session['dating_checkout_profile_type'] = 'dating_partner'
    request.session['dating_use_wallet'] = use_wallet
    request.session['dating_wallet_deduction'] = str(wallet_deduction)

    # ---------------------------------------------------------
    # 7. Redirect to selected gateway
    # ---------------------------------------------------------
    if payment_method == 'stripe':
        return redirect('dating_app:start_dating_partner_stripe_checkout')

    if payment_method == 'paypal':
        return redirect('dating_app:start_dating_partner_paypal_checkout')

    messages.error(request, "Please choose a valid payment method.")
    return redirect('dating_app:dating_partner_payment_center')

@login_required
def start_dating_partner_stripe_checkout(request):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    transaction_id = request.session.get('dating_payment_transaction_id')

    if not transaction_id:
        messages.error(request, "No checkout transaction found.")
        return redirect('dating_app:dating_partner_payment_center')

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
        status='pending',
    )

    if payment_transaction.payment_method not in ['stripe', 'mixed_stripe_wallet']:
        messages.error(request, "Invalid payment method for Stripe checkout.")
        return redirect('dating_app:dating_partner_payment_center')

    if payment_transaction.gateway_amount_usd <= Decimal('0.00'):
        messages.error(request, "Invalid Stripe payment amount.")
        return redirect('dating_app:dating_partner_payment_center')

    payable_items = list(
        payment_transaction.items.select_related('payable_item').all()
    )

    if not payable_items:
        messages.error(request, "No payment items found for this transaction.")
        return redirect('dating_app:dating_partner_payment_center')

    if not settings.STRIPE_SECRET_KEY:
        messages.error(request, "Stripe payment is not configured.")
        return redirect('dating_app:dating_partner_payment_center')

    stripe.api_key = settings.STRIPE_SECRET_KEY

    try:
        line_items = []

        # ---------------------------------------------------------
        # If wallet is partially used, Stripe should charge only
        # the remaining gateway amount.
        # ---------------------------------------------------------
        if payment_transaction.wallet_deduction_usd > Decimal('0.00'):
            stripe_amount_cents = int(
                (payment_transaction.gateway_amount_usd * Decimal('100')).quantize(Decimal('1'))
            )

            line_items = [{
                'price_data': {
                    'currency': 'usd',
                    'product_data': {
                        'name': f'Dating Partner Payment - Transaction #{payment_transaction.id}',
                        'description': (
                            f'Total: ${payment_transaction.total_amount_usd}, '
                            f'Wallet used: ${payment_transaction.wallet_deduction_usd}, '
                            f'Stripe payment: ${payment_transaction.gateway_amount_usd}'
                        ),
                    },
                    'unit_amount': stripe_amount_cents,
                },
                'quantity': 1,
            }]

        else:
            for transaction_item in payable_items:
                payable_item = transaction_item.payable_item

                stripe_amount_cents = int(
                    (transaction_item.amount_usd * Decimal('100')).quantize(Decimal('1'))
                )

                line_items.append({
                    'price_data': {
                        'currency': 'usd',
                        'product_data': {
                            'name': payable_item.title,
                            'description': (
                                getattr(payable_item, 'description', '')
                                or 'Dating partner payment item'
                            ),
                        },
                        'unit_amount': stripe_amount_cents,
                    },
                    'quantity': 1,
                })

        success_url = request.build_absolute_uri(
            reverse(
                'dating_app:dating_partner_stripe_payment_success',
                kwargs={'transaction_id': payment_transaction.id}
            )
        ) + '?session_id={CHECKOUT_SESSION_ID}'

        cancel_url = request.build_absolute_uri(
            reverse(
                'dating_app:dating_partner_payment_cancelled',
                kwargs={'transaction_id': payment_transaction.id}
            )
        )

        checkout_session = stripe.checkout.Session.create(
            payment_method_types=['card'],
            mode='payment',
            line_items=line_items,
            success_url=success_url,
            cancel_url=cancel_url,
            customer_email=request.user.email or None,
            client_reference_id=str(payment_transaction.id),
            metadata={
                'payment_transaction_id': str(payment_transaction.id),
                'user_id': str(request.user.id),
                'profile_type': 'dating_partner',
                'payment_purpose': 'payable_items',
            },
        )

        if not checkout_session.url:
            messages.error(
                request,
                "Stripe checkout session was created, but no checkout URL was returned."
            )
            return redirect('dating_app:dating_partner_payment_center')

        payment_transaction.gateway_session_id = checkout_session.id
        payment_transaction.status = 'processing'
        payment_transaction.save(update_fields=[
            'gateway_session_id',
            'status',
            'updated_at',
        ])

        return redirect(checkout_session.url)

    except Exception as e:
        payment_transaction.failure_reason = str(e)
        payment_transaction.save(update_fields=[
            'failure_reason',
            'updated_at',
        ])

        messages.error(
            request,
            "Stripe checkout could not be started. Please try again."
        )

        return redirect('dating_app:dating_partner_payment_center')

@login_required
def dating_partner_stripe_payment_success(request, transaction_id):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    session_id = request.GET.get('session_id')

    if not session_id:
        messages.error(request, "Stripe payment session not found.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=transaction_id
        )

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
    )

    # Prevent duplicate wallet deduction / duplicate item marking.
    if payment_transaction.status == 'paid':
        messages.success(request, "This payment has already been completed.")
        return redirect(
            'dating_app:dating_partner_payment_success',
            transaction_id=payment_transaction.id
        )

    if payment_transaction.payment_method not in ['stripe', 'mixed_stripe_wallet']:
        messages.error(request, "Invalid payment method for Stripe confirmation.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    if not settings.STRIPE_SECRET_KEY:
        messages.error(request, "Stripe payment is not configured.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    stripe.api_key = settings.STRIPE_SECRET_KEY

    # ---------------------------------------------------------
    # 1. Retrieve Stripe Checkout Session
    # ---------------------------------------------------------
    try:
        stripe_session = stripe.checkout.Session.retrieve(session_id)

    except Exception as e:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"Stripe session retrieve failed: {str(e)}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "Could not verify Stripe payment.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 2. Verify metadata transaction ID
    # ---------------------------------------------------------
    metadata_transaction_id = None
    stripe_metadata = getattr(stripe_session, 'metadata', None)

    if stripe_metadata:
        try:
            stripe_metadata = dict(stripe_metadata)
            metadata_transaction_id = stripe_metadata.get('payment_transaction_id')
        except Exception:
            metadata_transaction_id = getattr(
                stripe_metadata,
                'payment_transaction_id',
                None
            )

    if str(metadata_transaction_id) != str(payment_transaction.id):
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = "Stripe metadata transaction ID mismatch."
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "Stripe payment verification failed.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 3. Verify payment status
    # ---------------------------------------------------------
    stripe_payment_status = getattr(stripe_session, 'payment_status', None)

    if stripe_payment_status != 'paid':
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = (
            f"Stripe payment status was not paid: {stripe_payment_status}"
        )
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "Stripe payment was not completed.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 4. Verify amount
    # ---------------------------------------------------------
    expected_amount_cents = int(
        (payment_transaction.gateway_amount_usd * Decimal('100')).quantize(Decimal('1'))
    )

    stripe_amount_total = getattr(stripe_session, 'amount_total', None)

    if stripe_amount_total is not None and int(stripe_amount_total) != expected_amount_cents:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = (
            f"Stripe amount mismatch. Expected {expected_amount_cents}, "
            f"received {stripe_amount_total}."
        )
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "Stripe payment amount verification failed.")
        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 5. Payment verified. Safely update database.
    # ---------------------------------------------------------
    try:
        with transaction.atomic():
            locked_transaction = PaymentTransaction.objects.select_for_update().get(
                id=payment_transaction.id,
                user=request.user,
                profile_type='dating_partner',
            )

            if locked_transaction.status == 'paid':
                messages.success(request, "This payment has already been completed.")
                return redirect(
                    'dating_app:dating_partner_payment_success',
                    transaction_id=locked_transaction.id
                )

            wallet_deduction = locked_transaction.wallet_deduction_usd or Decimal('0.00')

            # Deduct wallet only for mixed Stripe + wallet payments.
            if wallet_deduction > Decimal('0.00'):
                wallet = WalletAccount.objects.select_for_update().get(
                    user=request.user,
                    profile_type='dating_partner',
                )

                if wallet.balance_usd < wallet_deduction:
                    locked_transaction.status = 'failed'
                    locked_transaction.failure_reason = (
                        "Wallet balance was insufficient during Stripe success confirmation."
                    )
                    locked_transaction.failed_at = timezone.now()
                    locked_transaction.save(update_fields=[
                        'status',
                        'failure_reason',
                        'failed_at',
                        'updated_at',
                    ])

                    messages.error(
                        request,
                        "Payment was received by Stripe, but wallet deduction failed. "
                        "Please contact support."
                    )
                    return redirect(
                        'dating_app:dating_partner_payment_failed',
                        transaction_id=locked_transaction.id
                    )

                wallet.balance_usd -= wallet_deduction
                wallet.save(update_fields=['balance_usd'])

            # Mark selected dating partner payable items as paid.
            # This must run for both full Stripe and mixed Stripe + wallet payments.
            mark_result = mark_dating_partner_transaction_items_paid(
                payment_transaction=locked_transaction,
                notes=f"Paid by Stripe. Transaction #{locked_transaction.id}",
            )

            if not mark_result["success"]:
                locked_transaction.status = 'failed'
                locked_transaction.failure_reason = "\n".join(mark_result["failed"])
                locked_transaction.failed_at = timezone.now()
                locked_transaction.save(update_fields=[
                    'status',
                    'failure_reason',
                    'failed_at',
                    'updated_at',
                ])

                messages.error(
                    request,
                    "Stripe payment was received, but the system could not complete all payment actions. "
                    "Please contact support."
                )

                return redirect(
                    'dating_app:dating_partner_payment_failed',
                    transaction_id=locked_transaction.id
                )

            locked_transaction.gateway_session_id = stripe_session.id
            locked_transaction.gateway_transaction_id = (
                getattr(stripe_session, 'payment_intent', '') or stripe_session.id
            )
            locked_transaction.status = 'paid'
            locked_transaction.paid_at = timezone.now()
            locked_transaction.failure_reason = ''
            locked_transaction.save(update_fields=[
                'gateway_session_id',
                'gateway_transaction_id',
                'status',
                'paid_at',
                'failure_reason',
                'updated_at',
            ])

    except Exception as e:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"Database payment completion failed: {str(e)}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(
            request,
            "Payment was verified, but the system could not complete the payment record. "
            "Please contact support."
        )

        return redirect(
            'dating_app:dating_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 6. Clear checkout session data
    # ---------------------------------------------------------
    request.session.pop('dating_payment_transaction_id', None)
    request.session.pop('dating_checkout_selected_ids', None)
    request.session.pop('dating_checkout_total', None)
    request.session.pop('dating_checkout_profile_type', None)
    request.session.pop('dating_use_wallet', None)
    request.session.pop('dating_wallet_deduction', None)

    messages.success(request, "Stripe payment completed successfully.")

    return redirect(
        'dating_app:dating_partner_payment_success',
        transaction_id=payment_transaction.id
    )

@login_required
def dating_partner_payment_success(request, transaction_id):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
    )

    return render(request, 'dating_app/payment_success.html', {
        'dating_partner': dating_partner,
        'payment_transaction': payment_transaction,
        'page_title': 'Payment Successful',
    })

@login_required
def dating_partner_payment_cancelled(request, transaction_id):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
    )

    if payment_transaction.status in ['pending', 'processing']:
        payment_transaction.status = 'cancelled'
        payment_transaction.cancelled_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'cancelled_at',
            'updated_at',
        ])

    messages.warning(
        request,
        "Payment was cancelled. Your selected payment items are still due."
    )

    return render(request, 'dating_app/payment_cancelled.html', {
        'dating_partner': dating_partner,
        'payment_transaction': payment_transaction,
        'page_title': 'Payment Cancelled',
    })

@login_required
def dating_partner_payment_failed(request, transaction_id):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
    )

    return render(request, 'dating_app/payment_failed.html', {
        'dating_partner': dating_partner,
        'payment_transaction': payment_transaction,
        'page_title': 'Payment Failed',
    })

@login_required
def start_dating_partner_paypal_checkout(request):
    dating_partner = getattr(request.user, 'dating_profile', None)

    if not dating_partner:
        messages.error(request, "Dating partner profile not found.")
        return redirect('dating_app:home_dating')

    transaction_id = request.session.get('dating_payment_transaction_id')

    if not transaction_id:
        messages.error(request, "No checkout transaction found.")
        return redirect('dating_app:dating_partner_payment_center')

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
        status='pending',
    )

    if payment_transaction.payment_method not in ['paypal', 'mixed_paypal_wallet']:
        messages.error(request, "Invalid payment method for PayPal checkout.")
        return redirect('dating_app:dating_partner_payment_center')

    if payment_transaction.gateway_amount_usd <= Decimal('0.00'):
        messages.error(request, "Invalid PayPal payment amount.")
        return redirect('dating_app:dating_partner_payment_center')

    payable_items = list(
        payment_transaction.items.select_related('payable_item').all()
    )

    if not payable_items:
        messages.error(request, "No payment items found for this transaction.")
        return redirect('dating_app:dating_partner_payment_center')

    try:
        order_data = create_dating_partner_paypal_order(
            payment_transaction=payment_transaction,
            request=request,
        )

        approval_url = get_paypal_approval_url(order_data)

        if not approval_url:
            raise Exception("PayPal approval URL not found.")

        payment_transaction.gateway_session_id = order_data.get('id', '')
        payment_transaction.status = 'processing'
        payment_transaction.save(update_fields=[
            'gateway_session_id',
            'status',
            'updated_at',
        ])

        return redirect(approval_url)

    except Exception as e:
        payment_transaction.failure_reason = str(e)
        payment_transaction.save(update_fields=[
            'failure_reason',
            'updated_at',
        ])

        messages.error(
            request,
            "PayPal checkout could not be started. Please try again."
        )

        return redirect('dating_app:dating_partner_payment_center')


def public_foreigners_list(request):
    dating_profile = None

    is_dating_partner_authenticated = False
    is_approved_dating_partner = False
    is_confirmed_dating_partner = False
    is_featured_dating_partner = False

    can_view_public_guest_profiles = False
    can_view_private_guest_profiles = False
    can_connect_with_guests = False

    if request.user.is_authenticated:
        dating_profile = getattr(request.user, 'dating_profile', None)

        if dating_profile:
            is_dating_partner_authenticated = True
            is_approved_dating_partner = dating_profile.status == 'approved'
            is_confirmed_dating_partner = dating_profile.is_confirmed
            is_featured_dating_partner = bool(dating_profile.is_featured)

            # Signed-up dating partner can at least see featured public guests.
            can_view_public_guest_profiles = True

            # Approved + featured dating partners can see private guest profiles too.
            # I also keep can_view_private_listings as an admin override.
            can_view_private_guest_profiles = (
                is_approved_dating_partner
                and (
                    dating_profile.is_featured is True
                    or dating_profile.can_view_private_listings is True
                )
            )

            # Confirmed dating partners can connect / express interest if arrangement access is enabled.
            can_connect_with_guests = (
                is_approved_dating_partner
                and is_confirmed_dating_partner
                and dating_profile.can_book_arrangements is True
            )

    # -------------------------------------------------
    # Real statistics
    # -------------------------------------------------
    real_total_guests = ForeignerProfile.objects.filter(
        status='approved'
    ).count()

    real_public_guests = ForeignerProfile.objects.filter(
        status='approved',
        is_public=True
    ).count()

    real_featured_guests = ForeignerProfile.objects.filter(
        status='approved',
        is_public=True,
        is_featured=True
    ).count()

    real_confirmed_guests = ForeignerProfile.objects.filter(
        status='approved',
        is_confirmed=True
    ).count()

    real_private_guests = ForeignerProfile.objects.filter(
        status='approved',
        is_public=False
    ).count()

    # -------------------------------------------------
    # Safe marketing display stats
    # Do not show fake exact numbers. Use "20+" style labels.
    # -------------------------------------------------
    display_total_guests = real_total_guests if real_total_guests >= 20 else 20
    display_featured_guests = real_featured_guests if real_featured_guests >= 8 else 8
    display_confirmed_guests = real_confirmed_guests if real_confirmed_guests >= 5 else 5

    use_marketing_stats = real_total_guests < 20

    # -------------------------------------------------
    # Profile visibility logic
    # -------------------------------------------------
    if not is_dating_partner_authenticated:
        # Public visitor:
        # Show only featured public guest samples.
        profiles = ForeignerProfile.objects.filter(
            status='approved',
            is_public=True,
            is_featured=True
        ).select_related('lead', 'user')

        access_level_label = 'Public Preview'
        access_message = (
            'You are viewing a limited public preview. Sign up as a local dating partner '
            'to view more guest profile opportunities.'
        )

    elif not is_approved_dating_partner:
        # Signed up but not approved:
        # Show only featured public profiles.
        profiles = ForeignerProfile.objects.filter(
            status='approved',
            is_public=True,
            is_featured=True
        ).select_related('lead', 'user')

        access_level_label = 'Signup Completed - Approval Pending'
        access_message = (
            'Your local dating partner profile is pending approval. You can preview featured public guest profiles while waiting.'
        )

    elif can_view_private_guest_profiles:
        # Approved + featured dating partner:
        # Can see public + private approved profiles.
        profiles = ForeignerProfile.objects.filter(
            status='approved'
        ).select_related('lead', 'user')

        access_level_label = 'Featured Dating Partner Access'
        access_message = (
            'Your featured dating partner profile gives you wider visibility and access to public and private approved guest profiles.'
        )

    else:
        # Approved normal dating partner:
        # Can see public profiles, featured and non-featured.
        profiles = ForeignerProfile.objects.filter(
            status='approved',
            is_public=True
        ).select_related('lead', 'user')

        access_level_label = 'Approved Dating Partner Access'
        access_message = (
            'You can view approved public guest profiles. Featured dating partners may receive wider private-profile access.'
        )

    # -------------------------------------------------
    # Sample preview wall
    # Always use limited public-safe profiles.
    # -------------------------------------------------
    sample_profiles = ForeignerProfile.objects.filter(
        status='approved',
        is_public=True
    ).select_related('lead', 'user').order_by(
        '-is_featured',
        '-joined_at'
    )[:15]

    # -------------------------------------------------
    # Filters
    # Public visitors can still filter samples, but only within their allowed queryset.
    # -------------------------------------------------
    nationality = request.GET.get('nationality', '').strip()
    gender = request.GET.get('gender', '').strip()
    budget = request.GET.get('monthly_budget', '').strip()

    if nationality:
        profiles = profiles.filter(lead__nationality=nationality)

    if gender:
        profiles = profiles.filter(lead__gender=gender)

    if budget:
        profiles = profiles.filter(lead__monthly_budget=budget)

    profiles = profiles.order_by('-is_featured', '-joined_at')

    paginator = Paginator(profiles, 9)
    page_number = request.GET.get('page')

    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)

    query_params = request.GET.copy()
    query_params.pop('page', None)
    query_string = query_params.urlencode()

    return render(request, 'dating_app/public_foreigners_list.html', {
        'profiles': page_obj,
        'page_obj': page_obj,
        'paginator': paginator,
        'total_results': paginator.count,
        'query_string': query_string,

        'sample_profiles': sample_profiles,

        'dating_profile': dating_profile,
        'is_dating_partner_authenticated': is_dating_partner_authenticated,
        'is_approved_dating_partner': is_approved_dating_partner,
        'is_confirmed_dating_partner': is_confirmed_dating_partner,
        'is_featured_dating_partner': is_featured_dating_partner,

        'can_view_public_guest_profiles': can_view_public_guest_profiles,
        'can_view_private_guest_profiles': can_view_private_guest_profiles,
        'can_connect_with_guests': can_connect_with_guests,

        'is_public_limited_preview': not is_dating_partner_authenticated,
        'show_guest_profile_detail_link': is_approved_dating_partner,
        'show_connect_message': can_connect_with_guests,

        'access_level_label': access_level_label,
        'access_message': access_message,

        'real_total_guests': real_total_guests,
        'real_public_guests': real_public_guests,
        'real_featured_guests': real_featured_guests,
        'real_confirmed_guests': real_confirmed_guests,
        'real_private_guests': real_private_guests,

        'display_total_guests': display_total_guests,
        'display_featured_guests': display_featured_guests,
        'display_confirmed_guests': display_confirmed_guests,
        'use_marketing_stats': use_marketing_stats,

        'selected_nationality': nationality,
        'selected_gender': gender,
        'selected_budget': budget,
        'nationality_choices': NATIONALITY_CHOICES,
        'gender_choices': ForeignerLead.GENDER_CHOICES,
        'budget_choices': ForeignerLead.BUDGET_CHOICES,
    })

@login_required
def public_foreigner_detail(request, pk):
    dating_profile = getattr(request.user, 'dating_profile', None)

    if not dating_profile:
        messages.warning(
            request,
            "Only registered local dating partners can view guest profile details."
        )
        return redirect('dating_app:home_dating')

    if dating_profile.status != 'approved':
        messages.warning(
            request,
            "Your local dating partner profile is not approved yet, so guest profile details are not available."
        )
        return redirect('dating_app:dating_partner_dashboard')

    is_dating_partner_authenticated = True
    dating_partner_is_confirmed = dating_profile.is_confirmed

    can_view_private_listings = (
        dating_profile.is_confirmed
        and dating_profile.can_view_private_listings
    )

    can_notify_interest = (
        dating_profile.is_confirmed
        and dating_profile.can_book_arrangements
    )

    profile = ForeignerProfile.objects.select_related(
        'lead',
        'user'
    ).filter(
        pk=pk,
        status='approved'
    ).first()

    if not profile:
        messages.warning(
            request,
            "The requested guest profile was not found or is not available."
        )
        return redirect('dating_app:public_foreigners_list')

    if not profile.is_public and not can_view_private_listings:
        messages.warning(
            request,
            "This guest profile is private. Your dating partner account does not currently have permission to view private profiles."
        )
        return redirect('dating_app:public_foreigners_list')

    allowed_statuses = [
        'interested',
        'reviewing',
        'contacted',
        'matched',
    ]

    existing_interest = ForeignerInterest.objects.filter(
        dating_partner=dating_profile,
        foreigner=profile,
        status__in=allowed_statuses
    ).first()

    foreigner_interest_in_partner = DatingInterest.objects.filter(
        foreigner=profile,
        partner=dating_profile,
        status__in=allowed_statuses
    ).first()

    mutual_interest_exists = bool(
        existing_interest and foreigner_interest_in_partner
    )

    can_view_contact_details = bool(
        dating_partner_is_confirmed
        and mutual_interest_exists
    )

    return render(request, 'dating_app/public_foreigner_detail.html', {
        'profile': profile,

        'dating_profile': dating_profile,
        'is_dating_partner_authenticated': is_dating_partner_authenticated,
        'dating_partner_is_confirmed': dating_partner_is_confirmed,

        'can_view_private_listings': can_view_private_listings,
        'can_notify_interest': can_notify_interest,
        'can_view_contact_details': can_view_contact_details,
        'mutual_interest_exists': mutual_interest_exists,

        'existing_interest': existing_interest,
        'foreigner_interest_in_partner': foreigner_interest_in_partner,
    })

def foreigners_home(request):
    dating_profile = None
    is_dating_partner_authenticated = False
    is_approved_dating_partner = False
    is_confirmed_dating_partner = False
    can_view_all_featured_foreigners = False

    if request.user.is_authenticated:
        dating_profile = getattr(request.user, 'dating_profile', None)

        if dating_profile:
            is_dating_partner_authenticated = True
            is_approved_dating_partner = dating_profile.status == 'approved'
            is_confirmed_dating_partner = dating_profile.is_confirmed

            can_view_all_featured_foreigners = (
                dating_profile.status == 'approved'
                and dating_profile.is_public is True
            )

    if can_view_all_featured_foreigners:
        base_profiles = ForeignerProfile.objects.filter(
            status='approved',
            is_featured=True
        ).select_related('lead', 'user')
    else:
        base_profiles = ForeignerProfile.objects.filter(
            status='approved',
            is_public=True,
            is_featured=True
        ).select_related('lead', 'user')

    featured_profiles = base_profiles.order_by('-joined_at')[:6]
    latest_profiles = base_profiles.order_by('-joined_at')[:25]

    context = {
        'featured_profiles': featured_profiles,
        'latest_profiles': latest_profiles,

        'dating_profile': dating_profile,
        'is_dating_partner_authenticated': is_dating_partner_authenticated,
        'is_approved_dating_partner': is_approved_dating_partner,
        'is_confirmed_dating_partner': is_confirmed_dating_partner,
        'can_view_all_featured_foreigners': can_view_all_featured_foreigners,
    }

    return render(request, 'dating_app/foreigners_home.html', context)

def dating_partner_information_center(request):
    selected_language = request.GET.get('lang', 'en')

    allowed_languages = ['en', 'si', 'ta']

    if selected_language not in allowed_languages:
        selected_language = 'en'

    guidance_resources = DatingPartnerGuidanceResource.objects.filter(
        is_active=True
    ).order_by('language')

    available_languages = list(
        guidance_resources.values_list('language', flat=True)
    )

    if selected_language not in available_languages and available_languages:
        if 'en' in available_languages:
            selected_language = 'en'
        else:
            selected_language = available_languages[0]

    selected_resource = guidance_resources.filter(
        language=selected_language
    ).first()

    context = {
        'guidance_resources': guidance_resources,
        'selected_resource': selected_resource,
        'selected_language': selected_language,
    }

    return render(
        request,
        'dating_app/dating_partner_information_center.html',
        context
    )

# wallet Top up:

@login_required
def dating_partner_wallet_topup(request):
    """
    Dating Partner direct wallet top-up page.

    No UserPayableItem is created here.
    User enters amount and selects Stripe or PayPal.
    """

    profile = (
        getattr(request.user, 'dating_profile', None)
        or getattr(request.user, 'dating_partner_profile', None)
    )

    if not profile:
        messages.error(
            request,
            "Dating Partner wallet top-up is available only for registered Dating Partner accounts."
        )
        return redirect('dating_app:home_dating')

    profile_type = 'dating_partner'
    wallet = get_or_create_wallet_account(request.user, profile_type)

    if request.method == 'POST':
        form = WalletTopUpForm(request.POST)

        if form.is_valid():
            amount_usd = form.cleaned_data['amount_usd']
            payment_method = form.cleaned_data['payment_method']

            request.session['dating_wallet_topup_profile_type'] = profile_type
            request.session['dating_wallet_topup_amount_usd'] = str(amount_usd)
            request.session['dating_wallet_topup_return_url'] = 'dating_app:dating_partner_wallet_topup'

            if payment_method == 'stripe':
                return redirect('dating_app:start_dating_partner_wallet_topup_stripe_checkout')

            if payment_method == 'paypal':
                return redirect('dating_app:start_dating_partner_wallet_topup_paypal_checkout')

            messages.error(request, "Please select a valid payment method.")
    else:
        form = WalletTopUpForm(initial={
            'payment_method': 'stripe',
        })

    return render(request, 'dating_app/dating_partner_wallet_topup.html', {
        'form': form,
        'wallet': wallet,
        'profile': profile,
        'profile_type': profile_type,
        'page_title': 'Dating Partner Wallet Top-up',
        'account_label': 'Dating Partner Wallet',
    })

@login_required
def start_dating_partner_wallet_topup_stripe_checkout(request):
    profile_type = request.session.get('dating_wallet_topup_profile_type')
    amount_usd = request.session.get('dating_wallet_topup_amount_usd')
    return_url = request.session.get(
        'dating_wallet_topup_return_url',
        'dating_app:dating_partner_wallet_topup'
    )

    if not profile_type or not amount_usd:
        messages.error(request, "No wallet top-up checkout details found.")
        return redirect(return_url)

    if profile_type != 'dating_partner':
        messages.error(request, "Invalid wallet top-up profile type.")
        return redirect(return_url)

    if not user_can_topup_wallet(request.user, profile_type):
        messages.error(
            request,
            "Wallet top-up is not available for this Dating Partner account."
        )
        return redirect(return_url)

    try:
        amount_usd = Decimal(str(amount_usd)).quantize(Decimal('0.01'))
    except (InvalidOperation, TypeError, ValueError):
        messages.error(request, "Invalid wallet top-up amount.")
        return redirect(return_url)

    if amount_usd <= Decimal('0.00'):
        messages.error(request, "Wallet top-up amount must be greater than zero.")
        return redirect(return_url)

    if not settings.STRIPE_SECRET_KEY:
        messages.error(request, "Stripe payment is not configured.")
        return redirect(return_url)

    stripe.api_key = settings.STRIPE_SECRET_KEY

    try:
        payment_transaction = PaymentTransaction.objects.create(
            user=request.user,
            profile_type='dating_partner',
            payment_purpose='wallet_topup',
            payment_method='stripe',
            total_amount_usd=amount_usd,
            wallet_deduction_usd=Decimal('0.00'),
            gateway_amount_usd=amount_usd,
            status='pending',
        )

        success_url = request.build_absolute_uri(
            reverse(
                'dating_app:dating_partner_wallet_topup_stripe_success',
                kwargs={'transaction_id': payment_transaction.id}
            )
        ) + '?session_id={CHECKOUT_SESSION_ID}'

        cancel_url = request.build_absolute_uri(
            reverse(
                'dating_app:dating_partner_wallet_topup_cancelled',
                kwargs={'transaction_id': payment_transaction.id}
            )
        )

        stripe_amount_cents = int(
            (amount_usd * Decimal('100')).quantize(Decimal('1'))
        )

        checkout_session = stripe.checkout.Session.create(
            payment_method_types=['card'],
            mode='payment',
            line_items=[
                {
                    'price_data': {
                        'currency': 'usd',
                        'product_data': {
                            'name': 'Dating Partner Wallet Top-up',
                            'description': (
                                f'Wallet top-up for Dating Partner account. '
                                f'Transaction #{payment_transaction.id}'
                            ),
                        },
                        'unit_amount': stripe_amount_cents,
                    },
                    'quantity': 1,
                }
            ],
            success_url=success_url,
            cancel_url=cancel_url,
            customer_email=request.user.email or None,
            client_reference_id=str(payment_transaction.id),
            metadata={
                'payment_transaction_id': str(payment_transaction.id),
                'user_id': str(request.user.id),
                'profile_type': 'dating_partner',
                'payment_purpose': 'wallet_topup',
                'amount_usd': str(amount_usd),
            },
        )

        if not checkout_session.url:
            raise Exception("Stripe checkout URL was not returned.")

        payment_transaction.gateway_session_id = checkout_session.id
        payment_transaction.status = 'processing'
        payment_transaction.save(update_fields=[
            'gateway_session_id',
            'status',
            'updated_at',
        ])

        request.session['dating_wallet_topup_transaction_id'] = payment_transaction.id

        return redirect(checkout_session.url)

    except Exception as e:
        messages.error(
            request,
            f"Stripe wallet top-up checkout could not be started. {str(e)}"
        )
        return redirect(return_url)
    
@login_required
def dating_partner_wallet_topup_stripe_success(request, transaction_id):
    session_id = request.GET.get('session_id')

    if not session_id:
        messages.error(request, "Stripe wallet top-up session not found.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=transaction_id
        )

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
        payment_purpose='wallet_topup',
    )

    if payment_transaction.status == 'paid':
        messages.success(request, "This wallet top-up has already been completed.")
        return redirect('dating_app:dating_partner_wallet_topup')

    if payment_transaction.payment_method != 'stripe':
        messages.error(request, "Invalid payment method for Stripe wallet top-up.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    if not settings.STRIPE_SECRET_KEY:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = "Stripe payment is not configured."
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "Stripe payment is not configured.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    stripe.api_key = settings.STRIPE_SECRET_KEY

    try:
        stripe_session = stripe.checkout.Session.retrieve(session_id)

        # ---------------------------------------------------------
        # 1. Verify metadata transaction ID
        # ---------------------------------------------------------
        metadata_transaction_id = None
        stripe_metadata = getattr(stripe_session, 'metadata', None)

        if stripe_metadata:
            try:
                stripe_metadata = dict(stripe_metadata)
                metadata_transaction_id = stripe_metadata.get('payment_transaction_id')
            except Exception:
                metadata_transaction_id = getattr(
                    stripe_metadata,
                    'payment_transaction_id',
                    None
                )

        if str(metadata_transaction_id) != str(payment_transaction.id):
            raise Exception("Stripe metadata transaction ID mismatch.")

        # ---------------------------------------------------------
        # 2. Verify payment status
        # ---------------------------------------------------------
        stripe_payment_status = getattr(stripe_session, 'payment_status', None)

        if stripe_payment_status != 'paid':
            raise Exception(
                f"Stripe payment status was not paid: {stripe_payment_status}"
            )

        # ---------------------------------------------------------
        # 3. Verify amount
        # ---------------------------------------------------------
        expected_amount_cents = int(
            (payment_transaction.gateway_amount_usd * Decimal('100')).quantize(
                Decimal('1')
            )
        )

        stripe_amount_total = getattr(stripe_session, 'amount_total', None)

        if stripe_amount_total is not None and int(stripe_amount_total) != expected_amount_cents:
            raise Exception(
                f"Stripe amount mismatch. Expected {expected_amount_cents}, "
                f"received {stripe_amount_total}."
            )

        gateway_transaction_id = (
            getattr(stripe_session, 'payment_intent', '') or stripe_session.id
        )

        # ---------------------------------------------------------
        # 4. Credit dating partner wallet
        # ---------------------------------------------------------
        complete_wallet_topup_transaction(
            payment_transaction=payment_transaction,
            gateway_session_id=stripe_session.id,
            gateway_transaction_id=gateway_transaction_id,
        )

    except Exception as e:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"Stripe wallet top-up failed: {str(e)}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "Stripe wallet top-up could not be completed.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 5. Clear dating wallet top-up session data
    # ---------------------------------------------------------
    request.session.pop('dating_wallet_topup_profile_type', None)
    request.session.pop('dating_wallet_topup_amount_usd', None)
    request.session.pop('dating_wallet_topup_return_url', None)
    request.session.pop('dating_wallet_topup_transaction_id', None)

    messages.success(
        request,
        "Your Dating Partner wallet has been topped up successfully."
    )

    return redirect('dating_app:dating_partner_wallet_topup')

def create_dating_partner_wallet_topup_paypal_order(payment_transaction, request):
    """
    Creates a PayPal order for Dating Partner wallet top-up.
    """

    access_token = get_paypal_access_token()
    base_url = get_paypal_base_url()

    create_order_url = f'{base_url}/v2/checkout/orders'

    return_url = request.build_absolute_uri(
        reverse(
            'dating_app:dating_partner_wallet_topup_paypal_success',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    cancel_url = request.build_absolute_uri(
        reverse(
            'dating_app:dating_partner_wallet_topup_cancelled',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    amount_value = payment_transaction.gateway_amount_usd.quantize(Decimal('0.01'))

    payload = {
        'intent': 'CAPTURE',
        'purchase_units': [
            {
                'reference_id': str(payment_transaction.id),
                'description': (
                    f'Dating Partner Wallet Top-up - Transaction '
                    f'#{payment_transaction.id}'
                ),
                'custom_id': str(payment_transaction.id),
                'amount': {
                    'currency_code': 'USD',
                    'value': str(amount_value),
                },
            }
        ],
        'application_context': {
            'brand_name': 'Ensolanka Date in Sri Lanka',
            'landing_page': 'BILLING',
            'user_action': 'PAY_NOW',
            'return_url': return_url,
            'cancel_url': cancel_url,
        },
    }

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}',
        'PayPal-Request-Id': f'dating-wallet-topup-{payment_transaction.id}',
    }

    response = requests.post(
        create_order_url,
        json=payload,
        headers=headers,
        timeout=30,
    )

    if response.status_code not in [200, 201]:
        raise Exception(f"PayPal wallet top-up order creation failed: {response.text}")

    return response.json()

@login_required
def start_dating_partner_wallet_topup_paypal_checkout(request):
    profile_type = request.session.get('dating_wallet_topup_profile_type')
    amount_usd = request.session.get('dating_wallet_topup_amount_usd')
    return_url = request.session.get(
        'dating_wallet_topup_return_url',
        'dating_app:dating_partner_wallet_topup'
    )

    if not profile_type or not amount_usd:
        messages.error(request, "No wallet top-up checkout details found.")
        return redirect(return_url)

    if profile_type != 'dating_partner':
        messages.error(request, "Invalid wallet top-up profile type.")
        return redirect(return_url)

    if not user_can_topup_wallet(request.user, profile_type):
        messages.error(
            request,
            "Wallet top-up is not available for this Dating Partner account."
        )
        return redirect(return_url)

    try:
        amount_usd = Decimal(str(amount_usd)).quantize(Decimal('0.01'))
    except (InvalidOperation, TypeError, ValueError):
        messages.error(request, "Invalid wallet top-up amount.")
        return redirect(return_url)

    if amount_usd <= Decimal('0.00'):
        messages.error(request, "Wallet top-up amount must be greater than zero.")
        return redirect(return_url)

    try:
        payment_transaction = PaymentTransaction.objects.create(
            user=request.user,
            profile_type='dating_partner',
            payment_purpose='wallet_topup',
            payment_method='paypal',
            total_amount_usd=amount_usd,
            wallet_deduction_usd=Decimal('0.00'),
            gateway_amount_usd=amount_usd,
            status='pending',
        )

        order_data = create_dating_partner_wallet_topup_paypal_order(
            payment_transaction=payment_transaction,
            request=request,
        )

        approval_url = get_paypal_approval_url(order_data)

        if not approval_url:
            raise Exception("PayPal approval URL not found.")

        payment_transaction.gateway_session_id = order_data.get('id', '')
        payment_transaction.status = 'processing'
        payment_transaction.save(update_fields=[
            'gateway_session_id',
            'status',
            'updated_at',
        ])

        request.session['dating_wallet_topup_transaction_id'] = payment_transaction.id

        return redirect(approval_url)

    except Exception as e:
        messages.error(
            request,
            f"PayPal wallet top-up checkout could not be started. {str(e)}"
        )
        return redirect(return_url)
    
@login_required
def dating_partner_wallet_topup_paypal_success(request, transaction_id):
    paypal_order_id = request.GET.get('token')

    if not paypal_order_id:
        messages.error(request, "PayPal wallet top-up order not found.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=transaction_id
        )

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
        payment_purpose='wallet_topup',
    )

    if payment_transaction.status == 'paid':
        messages.success(request, "This wallet top-up has already been completed.")
        return redirect('dating_app:dating_partner_wallet_topup')

    if payment_transaction.payment_method != 'paypal':
        messages.error(request, "Invalid payment method for PayPal wallet top-up.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    if (
        payment_transaction.gateway_session_id and
        payment_transaction.gateway_session_id != paypal_order_id
    ):
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = "PayPal wallet top-up order ID mismatch."
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "PayPal wallet top-up verification failed.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    try:
        capture_data = capture_paypal_order(paypal_order_id)

        paypal_status = capture_data.get('status')

        if paypal_status != 'COMPLETED':
            raise Exception(
                f"PayPal payment status was not completed: {paypal_status}"
            )

        purchase_units = capture_data.get('purchase_units', [])
        first_purchase_unit = purchase_units[0] if purchase_units else {}
        payments = first_purchase_unit.get('payments', {})
        captures = payments.get('captures', [])
        first_capture = captures[0] if captures else {}

        captured_amount = first_capture.get('amount', {})
        captured_value = Decimal(
            str(captured_amount.get('value', '0.00'))
        ).quantize(Decimal('0.01'))
        captured_currency = captured_amount.get('currency_code')

        expected_amount = payment_transaction.gateway_amount_usd.quantize(
            Decimal('0.01')
        )

        if captured_currency != 'USD' or captured_value != expected_amount:
            raise Exception(
                f"PayPal amount mismatch. Expected USD {expected_amount}, "
                f"received {captured_currency} {captured_value}."
            )

        paypal_capture_id = first_capture.get('id', paypal_order_id)

        complete_wallet_topup_transaction(
            payment_transaction=payment_transaction,
            gateway_session_id=paypal_order_id,
            gateway_transaction_id=paypal_capture_id,
        )

    except Exception as e:
        payment_transaction.status = 'failed'
        payment_transaction.failure_reason = f"PayPal wallet top-up failed: {str(e)}"
        payment_transaction.failed_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'failure_reason',
            'failed_at',
            'updated_at',
        ])

        messages.error(request, "PayPal wallet top-up could not be completed.")
        return redirect(
            'dating_app:dating_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    request.session.pop('dating_wallet_topup_profile_type', None)
    request.session.pop('dating_wallet_topup_amount_usd', None)
    request.session.pop('dating_wallet_topup_return_url', None)
    request.session.pop('dating_wallet_topup_transaction_id', None)

    messages.success(
        request,
        "Your Dating Partner wallet has been topped up successfully."
    )

    return redirect('dating_app:dating_partner_wallet_topup')

@login_required
def dating_partner_wallet_topup_cancelled(request, transaction_id):
    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
        payment_purpose='wallet_topup',
    )

    if payment_transaction.status in ['pending', 'processing']:
        payment_transaction.status = 'cancelled'
        payment_transaction.cancelled_at = timezone.now()
        payment_transaction.save(update_fields=[
            'status',
            'cancelled_at',
            'updated_at',
        ])

    request.session.pop('dating_wallet_topup_profile_type', None)
    request.session.pop('dating_wallet_topup_amount_usd', None)
    request.session.pop('dating_wallet_topup_return_url', None)
    request.session.pop('dating_wallet_topup_transaction_id', None)

    messages.warning(
        request,
        "Wallet top-up was cancelled. No amount was added to your Dating Partner wallet."
    )

    return redirect('dating_app:dating_partner_wallet_topup')

@login_required
def dating_partner_wallet_topup_failed(request, transaction_id):
    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='dating_partner',
        payment_purpose='wallet_topup',
    )

    messages.error(
        request,
        "Wallet top-up failed. Please try again or contact support if money was deducted."
    )

    return redirect('dating_app:dating_partner_wallet_topup')

