from django.contrib import messages
from django.contrib.auth import get_user_model, login, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.db import transaction
from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
import re
import random
import string
from django.db import models
from .models import ServicePartnerProfile, ServicePartnerInterest, ServicePartnerGuidanceResource
from common.choices import SRI_LANKA_CITY_CHOICES
from django.urls import reverse_lazy
from django.contrib.auth.forms import PasswordChangeForm
from expat_life.email_services import send_service_partner_signup_welcome_email
from django.views.decorators.http import require_POST
from expat_life.utils import (
    get_platform_fee_settings, 
    update_service_partner_payable_items,
    mark_service_partner_transaction_items_paid,
    get_or_create_wallet_account,
    user_can_topup_wallet,
    complete_wallet_topup_transaction,
)
from expat_life.models import (
    UserPayableItem,
    WalletAccount,
    PaymentTransaction,
    PaymentTransactionItem,
)
from datetime import date
from decimal import Decimal, InvalidOperation
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .forms import (
    ServicePartnerProfileEditForm,
    ServicePartnerProfileImageForm,
    UsernameChangeForm,
    ServicePartnerRegistrationForm,
    ServicePartnerInterestForm,
    ServicePartnerPasswordResetForm,
)

from django.contrib.auth.views import (
    LoginView,
    PasswordResetView,
    PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView,
)
from expat_life.forms import ContactMessageForm, WalletTopUpForm
from django.urls import reverse
from django.utils import timezone
import stripe
from django.conf import settings
from common.payment_gateway_services import (
    get_paypal_access_token,
    get_paypal_base_url,
    get_paypal_approval_url,
    capture_paypal_order,
)
import requests

User = get_user_model()

def about_us_assistants(request):
    return render(request, 'service_partner_app/about_us_assistants.html')

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

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

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

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

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

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

def contact_page(request):
    if request.method == 'POST':
        form = ContactMessageForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(
                reverse('service_partner_app:success_page') +
                '?type=contact'
            )
    else:
        form = ContactMessageForm()
    return render(request, 'service_partner_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': 'service_partner_app:home_service_partner',
            'button_2_text': 'About Ensolanka',
            'button_2_url': 'service_partner_app:about_us_assistants',
        },
        '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': 'service_partner_app:home_service_partner',
            'button_2_text': 'About Ensolanka',
            'button_2_url': 'service_partner_app:about_us_assistants',
        },
        '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': 'service_partner_app:home_service_partner',
            'button_2_text': 'Contact Us',
            'button_2_url': 'service_partner_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': 'service_partner_app:home_service_partner',
            'button_2_text': 'Contact Us',
            'button_2_url': 'service_partner_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, 'service_partner_app/success_page.html', context)

class ServicePartnerPasswordResetView(PasswordResetView):
    template_name = 'registration/assistant_password_reset.html'   # assistant_ prefix
    form_class = ServicePartnerPasswordResetForm
    email_template_name = 'emails/service_partner_app/password_reset_email.txt'
    html_email_template_name = 'emails/service_partner_app/password_reset_email.html'
    subject_template_name = 'emails/service_partner_app/password_reset_subject.txt'
    success_url = reverse_lazy('service_partner_app:assistant_password_reset_done')
    from_email = "Hired 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_service_partner = User.objects.filter(
            email__iexact=email,
            service_partner_profile__isnull=False,
            is_active=True
        ).exists()

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

        return super().form_valid(form)


class ServicePartnerPasswordResetDoneView(PasswordResetDoneView):
    template_name = 'registration/assistant_password_reset_done.html'


class ServicePartnerPasswordResetConfirmView(PasswordResetConfirmView):
    template_name = 'registration/assistant_password_reset_confirm.html'
    success_url = reverse_lazy('service_partner_app:assistant_password_reset_complete')


class ServicePartnerPasswordResetCompleteView(PasswordResetCompleteView):
    template_name = 'registration/assistant_password_reset_complete.html'




@login_required
def service_partner_profile_page(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a service 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'

    return render(request, 'service_partner_app/service_partner_profile.html', {
        'partner': partner,
        'default_profile_image': default_image,
    })


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

    if request.method == 'POST':
        form = ServicePartnerProfileEditForm(
            request.POST,
            request.FILES,
            instance=partner
        )
        if form.is_valid():
            form.save()
            messages.success(request, "Profile updated successfully.")
            return redirect('service_partner_app:service_partner_profile_page')
    else:
        form = ServicePartnerProfileEditForm(instance=partner)

    return render(request, 'service_partner_app/edit_service_partner_profile.html', {
        'form': form,
        'partner': partner,
    })


@login_required
@require_POST
def upload_service_partner_profile_image(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        return JsonResponse({
            'success': False,
            'error': 'Service 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 = ServicePartnerProfileImageForm(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_service_partner_username(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a service 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('service_partner_app:service_partner_profile_page')
    else:
        form = UsernameChangeForm(instance=request.user, user=request.user)

    return render(request, 'service_partner_app/change_service_partner_username.html', {
        'form': form,
        'partner': partner,
    })


@login_required
def change_service_partner_password(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a service 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('service_partner_app:service_partner_profile_page')
    else:
        form = PasswordChangeForm(request.user)



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

    base = f"sp_{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))


def home_service_partner(request):
    service_partner_profile = None

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

    return render(request, 'service_partner_app/home_service_partner.html', {
        'service_partner_profile': service_partner_profile,
    })

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

    show_all_featured_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_featured_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_featured_profiles:
        base_profiles = ServicePartnerProfile.objects.filter(
            status='approved',
            is_featured=True
        )
    else:
        base_profiles = ServicePartnerProfile.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')[:8]

    return render(request, 'service_partner_app/service_partner_home.html', {
        'featured_profiles': featured_profiles,
        'latest_profiles': latest_profiles,
    })
"""

@transaction.atomic
def service_partner_register(request):
    if request.method == 'POST':
        form = ServicePartnerRegistrationForm(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_service_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 = True
                partner.save()

                update_service_partner_payable_items(user)

                transaction.on_commit(
                    lambda: send_service_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'] = 'Service Partner'
                request.session['just_signed_up'] = True

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

    return render(request, 'service_partner_app/service_partner_register.html', {'form': form})


class ServicePartnerLoginView(LoginView):
    template_name = 'registration/service_partner_login.html'

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

        # Check correct role
        service_profile = getattr(user, 'service_partner_profile', None)

        if service_profile:
            return response

        # ❌ Wrong role → handle nicely
        messages.warning(
            self.request,
            "This login is only for service partners. Please use the correct login page for your account."
        )

        logout(self.request)

        # Redirect to correct portal
        if hasattr(user, 'foreigner_profile'):
            return redirect('expat_life:foreigner_login')
        elif hasattr(user, 'dating_profile'):
            return redirect('dating_app:dating_partner_login')
        elif hasattr(user, 'rental_owner_profile'):
            return redirect('rental_app:rental_owner_login')

        return redirect('expat_life:home')

    def get_success_url(self):
        return self.get_redirect_url() or reverse_lazy('service_partner_app:service_partner_dashboard')


@login_required
def service_partner_dashboard(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a service 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, 'service_partner_app/service_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),
    })

@login_required
def service_partner_profile_page(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        return HttpResponseForbidden("You do not have a service 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'

    return render(request, 'service_partner_app/service_partner_profile.html', {
        'partner': partner,
        'default_profile_image': default_image,
    })


def public_assistant_list(request):
    service_partner_profile = None

    is_service_partner_authenticated = False
    is_approved_service_partner = False
    is_featured_service_partner = False

    can_view_public_service_profiles = False
    can_view_private_service_profiles = False
    can_manage_service_profile = False

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

        if service_partner_profile:
            is_service_partner_authenticated = True
            is_approved_service_partner = service_partner_profile.status == 'approved'
            is_featured_service_partner = bool(service_partner_profile.is_featured)

            # Signed-up service partners can manage their own profile.
            can_manage_service_profile = True

            # This page is only a public-profile preview page inside
            # the Service Partner App. No service partner should gain
            # access to private assistant profiles here.
            can_view_public_service_profiles = True
            can_view_private_service_profiles = False

    # -------------------------------------------------
    # Profile visibility logic
    # -------------------------------------------------
    # In the Service Partner App, local assistants/service partners
    # should only see profiles that are:
    #   - approved
    #   - explicitly public
    #
    # Featured status is intentionally NOT used here.
    # Private profiles must never appear in this local assistant listing.
    profiles = ServicePartnerProfile.objects.filter(
        status='approved',
        is_public=True
    )

    # -------------------------------------------------
    # Access label / message
    # -------------------------------------------------
    if not is_service_partner_authenticated:
        access_level_label = "Public Service Partner Preview"
        access_message = (
            "You are viewing approved public local service partner profiles in a limited preview. "
            "Sign up as a local service partner to understand how profiles are presented "
            "within the Ensolanka trusted partner network."
        )

    elif not is_approved_service_partner:
        access_level_label = "Signup Completed - Approval Pending"
        access_message = (
            "Your service partner profile is pending approval. "
            "You can preview approved public local service partner profiles while waiting."
        )

    else:
        access_level_label = "Approved Service Partner Access"
        access_message = (
            "You can preview approved public local service partner profiles, "
            "understand the presentation style, and manage your own service partner profile "
            "from your dashboard."
        )

    # -------------------------------------------------
    # Stats / sample wall
    # -------------------------------------------------
    real_total_profiles = ServicePartnerProfile.objects.filter(
        status='approved'
    ).count()

    real_public_profiles = ServicePartnerProfile.objects.filter(
        status='approved',
        is_public=True
    ).count()

    # These counts may still be useful elsewhere in the template or marketing,
    # but they do NOT affect visibility in this local service partner list.
    real_featured_profiles = ServicePartnerProfile.objects.filter(
        status='approved',
        is_public=True,
        is_featured=True
    ).count()

    real_private_profiles = ServicePartnerProfile.objects.filter(
        status='approved',
        is_public=False
    ).count()

    # Since ServicePartnerProfile has no is_confirmed field,
    # use approved profiles as the "serious/approved partners" count.
    real_serious_profiles = real_total_profiles

    display_total_profiles = real_total_profiles if real_total_profiles >= 20 else 20
    display_featured_profiles = real_featured_profiles if real_featured_profiles >= 8 else 8
    display_serious_profiles = real_serious_profiles if real_serious_profiles >= 5 else 5

    use_marketing_stats = real_total_profiles < 20

    # Sample profiles must also be approved + public only.
    # Featured status should not affect ordering inside the Service Partner App.
    sample_profiles = ServicePartnerProfile.objects.filter(
        status='approved',
        is_public=True
    ).order_by(
        '-created_at'
    )[:15]

    # -------------------------------------------------
    # Filters
    # -------------------------------------------------
    service_type = request.GET.get('service_type', '').strip()
    city = request.GET.get('city', '').strip()
    q = request.GET.get('q', '').strip()

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

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

    if q:
        profiles = profiles.filter(
            models.Q(display_name__icontains=q) |
            models.Q(full_name__icontains=q) |
            models.Q(short_intro__icontains=q) |
            models.Q(about_me__icontains=q) |
            models.Q(skills__icontains=q) |
            models.Q(experience_summary__icontains=q) |
            models.Q(languages_spoken__icontains=q)
        )

    # Featured priority is not meaningful inside the local service partner app.
    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)

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

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

        'sample_profiles': sample_profiles,

        'service_partner_profile': service_partner_profile,
        'is_service_partner_authenticated': is_service_partner_authenticated,
        'is_approved_service_partner': is_approved_service_partner,
        'is_featured_service_partner': is_featured_service_partner,

        'can_view_public_service_profiles': can_view_public_service_profiles,
        'can_view_private_service_profiles': False,
        'can_manage_service_profile': can_manage_service_profile,

        'is_public_limited_preview': not is_service_partner_authenticated,
        'show_service_profile_detail_link': is_approved_service_partner,

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

        'real_total_profiles': real_total_profiles,
        'real_public_profiles': real_public_profiles,
        'real_featured_profiles': real_featured_profiles,
        'real_private_profiles': real_private_profiles,
        'real_serious_profiles': real_serious_profiles,

        'display_total_profiles': display_total_profiles,
        'display_featured_profiles': display_featured_profiles,
        'display_serious_profiles': display_serious_profiles,
        'use_marketing_stats': use_marketing_stats,

        'selected_service_type': service_type,
        'selected_city': city,
        'search_query': q,
        'service_type_choices': ServicePartnerProfile.SERVICE_TYPE_CHOICES,
        'city_choices': SRI_LANKA_CITY_CHOICES,
    })

def public_assistant_detail(request, pk):
    service_partner_profile = None

    is_service_partner_authenticated = False
    is_approved_service_partner = False
    is_featured_service_partner = False

    can_view_private_service_profiles = False
    is_public_limited_preview = True
    show_full_service_profile_preview = False
    show_private_service_profile_preview = False

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

        if service_partner_profile:
            is_service_partner_authenticated = True
            is_approved_service_partner = service_partner_profile.status == 'approved'
            is_featured_service_partner = bool(service_partner_profile.is_featured)

            can_view_private_service_profiles = (
                is_approved_service_partner
                and is_featured_service_partner
            )

            if is_approved_service_partner:
                show_full_service_profile_preview = True
                is_public_limited_preview = False

            if can_view_private_service_profiles:
                show_private_service_profile_preview = True

    # -------------------------------------------------
    # Profile access logic
    # -------------------------------------------------
    if not is_service_partner_authenticated:
        # Public visitor:
        # Only featured public approved profiles.
        profile = get_object_or_404(
            ServicePartnerProfile,
            pk=pk,
            status='approved',
            is_public=True,
            is_featured=True,
        )

        access_level_label = "Public Service Partner Preview"
        access_message = (
            "You are viewing a limited public preview. Sign up as a service partner "
            "to understand how profiles are presented to international guests."
        )

    elif not is_approved_service_partner:
        # Signed-up but not approved:
        # Featured public approved profiles only.
        profile = get_object_or_404(
            ServicePartnerProfile,
            pk=pk,
            status='approved',
            is_public=True,
            is_featured=True,
        )

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

    elif can_view_private_service_profiles:
        # Approved + featured:
        # Can view public and private approved profiles.
        profile = get_object_or_404(
            ServicePartnerProfile,
            pk=pk,
            status='approved',
        )

        access_level_label = "Featured Service Partner Access"
        access_message = (
            "Your featured service partner profile can access a wider profile preview, including public and private approved profiles."
        )

    else:
        # Approved normal service partner:
        # Public approved profiles only.
        profile = get_object_or_404(
            ServicePartnerProfile,
            pk=pk,
            status='approved',
            is_public=True,
        )

        access_level_label = "Approved Service Partner Access"
        access_message = (
            "You can view approved public service partner profiles. Featured service partners may receive wider private-profile access."
        )

    return render(request, 'service_partner_app/public_assistant_detail.html', {
        'profile': profile,

        'service_partner_profile': service_partner_profile,
        'is_service_partner_authenticated': is_service_partner_authenticated,
        'is_approved_service_partner': is_approved_service_partner,
        'is_featured_service_partner': is_featured_service_partner,

        'can_view_private_service_profiles': can_view_private_service_profiles,
        'is_public_limited_preview': is_public_limited_preview,
        'show_full_service_profile_preview': show_full_service_profile_preview,
        'show_private_service_profile_preview': show_private_service_profile_preview,

        'access_level_label': access_level_label,
        'access_message': access_message,
    })

@login_required
def express_service_partner_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 local service assistants."
        )
        return redirect('expat_life:home')

    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(
        ServicePartnerProfile,
        pk=pk,
        status='approved',
        
    )

    if request.method == 'POST':
        form = ServicePartnerInterestForm(request.POST)
        if form.is_valid():
            interest, created = ServicePartnerInterest.objects.get_or_create(
                foreigner=foreigner_profile,
                partner=partner,
                defaults={
                    'message': form.cleaned_data['message'],
                    'status': 'interested',
                }
            )

            if created:
                messages.success(
                    request,
                    "Your interest has been submitted successfully."
                )
            else:
                if form.cleaned_data['message']:
                    interest.message = form.cleaned_data['message']
                    interest.save(update_fields=['message'])
                messages.info(
                    request,
                    "You have already expressed interest in this assistant. Your message was updated."
                )

    return redirect('expat_life:public_assistant_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, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "This account is not registered as a local service partner.")
        return redirect('expat_life:home')

    if partner.status != 'approved':
        messages.warning(request, "Your local service partner profile is not approved yet.")
        return redirect('service_partner_app:service_partner_dashboard')

    interests = (
        ServicePartnerInterest.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,
        'service_partner_app/interested_foreigners_list.html',
        context
    )

@login_required
def service_partner_payment_center(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

    # Ensure service partner payable items exist / refresh unpaid ones
    update_service_partner_payable_items(request.user)

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

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

    payment_order = {
        'service_partner_featured': 1,
        '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 = {
        'partner': 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, 'service_partner_app/payment_center.html', context)

@login_required
def service_partner_payment_checkout(request):
    partner = getattr(request.user, 'service_partner_profile', None)
    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

    if request.method != 'POST':
        messages.error(request, "Please select at least one payment item first.")
        return redirect('service_partner_app:service_partner_payment_center')

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


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

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

    payable_items = list(
        UserPayableItem.objects.filter(
            id__in=selected_ids,
            user=request.user,
            profile_type='service_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('service_partner_app:service_partner_payment_center')

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

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


@login_required
def service_partner_payment_checkout_pay(request):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

    if request.method != 'POST':
        messages.error(request, "Invalid payment request.")
        return redirect('service_partner_app:service_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('service_partner_app:service_partner_payment_center')

    payable_items = list(
        UserPayableItem.objects.filter(
            id__in=selected_ids,
            user=request.user,
            profile_type='service_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('service_partner_app:service_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='service_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('service_partner_app:service_partner_payment_center')

            payment_transaction = PaymentTransaction.objects.create(
                user=request.user,
                profile_type='service_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_service_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(
                    'service_partner_app:service_partner_payment_failed',
                    transaction_id=payment_transaction.id
                )

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

        request.session.pop('service_partner_payment_transaction_id', None)
        request.session.pop('service_partner_checkout_selected_ids', None)
        request.session.pop('service_partner_checkout_total', None)
        request.session.pop('service_partner_checkout_profile_type', None)
        request.session.pop('service_partner_use_wallet', None)
        request.session.pop('service_partner_wallet_deduction', None)

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

        return redirect(
            'service_partner_app:service_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('service_partner_app:service_partner_payment_center')

    # ---------------------------------------------------------
    # 5. Create pending payment transaction
    # ---------------------------------------------------------
    with transaction.atomic():
        payment_transaction = PaymentTransaction.objects.create(
            user=request.user,
            profile_type='service_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['service_partner_payment_transaction_id'] = payment_transaction.id
    request.session['service_partner_checkout_selected_ids'] = [
        item.id for item in payable_items
    ]
    request.session['service_partner_checkout_total'] = str(amount_to_charge)
    request.session['service_partner_checkout_profile_type'] = 'service_partner'
    request.session['service_partner_use_wallet'] = use_wallet
    request.session['service_partner_wallet_deduction'] = str(wallet_deduction)

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

    if payment_method == 'paypal':
        return redirect('service_partner_app:start_service_partner_paypal_checkout')

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

@login_required
def start_service_partner_stripe_checkout(request):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

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

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

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='service_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('service_partner_app:service_partner_payment_center')

    if payment_transaction.gateway_amount_usd <= Decimal('0.00'):
        messages.error(request, "Invalid Stripe payment amount.")
        return redirect('service_partner_app:service_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('service_partner_app:service_partner_payment_center')

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

    stripe.api_key = settings.STRIPE_SECRET_KEY

    try:
        line_items = []

        # If wallet is partially used, Stripe should charge only the remaining 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'Service 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 'Service partner payment item'
                            ),
                        },
                        'unit_amount': stripe_amount_cents,
                    },
                    'quantity': 1,
                })

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

        cancel_url = request.build_absolute_uri(
            reverse(
                'service_partner_app:service_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': 'service_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('service_partner_app:service_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('service_partner_app:service_partner_payment_center')

@login_required
def service_partner_stripe_payment_success(request, transaction_id):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

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

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

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

    # Prevent duplicate wallet deduction / duplicate item marking.
    if payment_transaction.status == 'paid':
        messages.success(request, "This payment has already been completed.")
        return redirect(
            'service_partner_app:service_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(
            'service_partner_app:service_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    if not settings.STRIPE_SECRET_KEY:
        messages.error(request, "Stripe payment is not configured.")
        return redirect(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
            'service_partner_app:service_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='service_partner',
            )

            if locked_transaction.status == 'paid':
                messages.success(request, "This payment has already been completed.")
                return redirect(
                    'service_partner_app:service_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='service_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(
                        'service_partner_app:service_partner_payment_failed',
                        transaction_id=locked_transaction.id
                    )

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

            # Mark selected Service Partner payable items as paid.
            # This must run for both full Stripe and mixed Stripe + wallet payments.
            mark_result = mark_service_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(
                    'service_partner_app:service_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(
            'service_partner_app:service_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 6. Clear checkout session data
    # ---------------------------------------------------------
    request.session.pop('service_partner_payment_transaction_id', None)
    request.session.pop('service_partner_checkout_selected_ids', None)
    request.session.pop('service_partner_checkout_total', None)
    request.session.pop('service_partner_checkout_profile_type', None)
    request.session.pop('service_partner_use_wallet', None)
    request.session.pop('service_partner_wallet_deduction', None)

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

    return redirect(
        'service_partner_app:service_partner_payment_success',
        transaction_id=payment_transaction.id
    )


#==================================
#Payment Success, Cancelled and Failed
#=========================================

@login_required
def service_partner_payment_success(request, transaction_id):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

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

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

@login_required
def service_partner_payment_cancelled(request, transaction_id):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='service_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, 'service_partner_app/payment_cancelled.html', {
        'partner': partner,
        'payment_transaction': payment_transaction,
        'page_title': 'Payment Cancelled',
    })

@login_required
def service_partner_payment_failed(request, transaction_id):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

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

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

#Paypal

def create_service_partner_paypal_order(payment_transaction, request):
    """
    Creates a PayPal order for Service 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(
            'service_partner_app:service_partner_paypal_payment_success',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    cancel_url = request.build_absolute_uri(
        reverse(
            'service_partner_app:service_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'Service 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 Hired 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'service-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 start_service_partner_paypal_checkout(request):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

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

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

    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='service_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('service_partner_app:service_partner_payment_center')

    if payment_transaction.gateway_amount_usd <= Decimal('0.00'):
        messages.error(request, "Invalid PayPal payment amount.")
        return redirect('service_partner_app:service_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('service_partner_app:service_partner_payment_center')

    try:
        order_data = create_service_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('service_partner_app:service_partner_payment_center')
    
@login_required
def service_partner_paypal_payment_success(request, transaction_id):
    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(request, "Service partner profile not found.")
        return redirect('expat_life:home')

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

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

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

    if payment_transaction.status == 'paid':
        messages.success(request, "This payment has already been completed.")
        return redirect(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
                'service_partner_app:service_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(
            'service_partner_app:service_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='service_partner',
            )

            if locked_transaction.status == 'paid':
                messages.success(request, "This payment has already been completed.")
                return redirect(
                    'service_partner_app:service_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='service_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(
                        'service_partner_app:service_partner_payment_failed',
                        transaction_id=locked_transaction.id
                    )

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

            mark_result = mark_service_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(
                    'service_partner_app:service_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(
            'service_partner_app:service_partner_payment_failed',
            transaction_id=payment_transaction.id
        )

    request.session.pop('service_partner_payment_transaction_id', None)
    request.session.pop('service_partner_checkout_selected_ids', None)
    request.session.pop('service_partner_checkout_total', None)
    request.session.pop('service_partner_checkout_profile_type', None)
    request.session.pop('service_partner_use_wallet', None)
    request.session.pop('service_partner_wallet_deduction', None)

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

    return redirect(
        'service_partner_app:service_partner_payment_success',
        transaction_id=payment_transaction.id
    )

def service_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 = ServicePartnerGuidanceResource.objects.filter(
        is_active=True
    ).order_by('language')

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

    # If requested language is not available, fallback safely.
    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,
        'service_partner_app/service_partner_information_center.html',
        context
    )

# wallet Top up

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

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

    partner = getattr(request.user, 'service_partner_profile', None)

    if not partner:
        messages.error(
            request,
            "Service Partner wallet top-up is available only for registered Service Partner accounts."
        )
        return redirect('service_partner_app:home_service_partner')

    profile_type = 'service_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['service_partner_wallet_topup_profile_type'] = profile_type
            request.session['service_partner_wallet_topup_amount_usd'] = str(amount_usd)
            request.session['service_partner_wallet_topup_return_url'] = 'service_partner_app:service_partner_wallet_topup'

            if payment_method == 'stripe':
                return redirect('service_partner_app:start_service_partner_wallet_topup_stripe_checkout')

            if payment_method == 'paypal':
                return redirect('service_partner_app:start_service_partner_wallet_topup_paypal_checkout')

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

    return render(request, 'service_partner_app/service_partner_wallet_topup.html', {
        'form': form,
        'wallet': wallet,
        'partner': partner,
        'profile': partner,
        'profile_type': profile_type,
        'page_title': 'Service Partner Wallet Top-up',
        'account_label': 'Service Partner Wallet',
    })

@login_required
def start_service_partner_wallet_topup_stripe_checkout(request):
    profile_type = request.session.get('service_partner_wallet_topup_profile_type')
    amount_usd = request.session.get('service_partner_wallet_topup_amount_usd')
    return_url = request.session.get(
        'service_partner_wallet_topup_return_url',
        'service_partner_app:service_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 != 'service_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 Service 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='service_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(
                'service_partner_app:service_partner_wallet_topup_stripe_success',
                kwargs={'transaction_id': payment_transaction.id}
            )
        ) + '?session_id={CHECKOUT_SESSION_ID}'

        cancel_url = request.build_absolute_uri(
            reverse(
                'service_partner_app:service_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': 'Service Partner Wallet Top-up',
                            'description': (
                                f'Wallet top-up for Service 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': 'service_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['service_partner_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 service_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(
            'service_partner_app:service_partner_wallet_topup_failed',
            transaction_id=transaction_id
        )

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

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

    if payment_transaction.payment_method != 'stripe':
        messages.error(request, "Invalid payment method for Stripe wallet top-up.")
        return redirect(
            'service_partner_app:service_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(
            'service_partner_app:service_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)

        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.")

        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}"
            )

        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
        )

        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(
            'service_partner_app:service_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    request.session.pop('service_partner_wallet_topup_profile_type', None)
    request.session.pop('service_partner_wallet_topup_amount_usd', None)
    request.session.pop('service_partner_wallet_topup_return_url', None)
    request.session.pop('service_partner_wallet_topup_transaction_id', None)

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

    return redirect('service_partner_app:service_partner_wallet_topup')

def create_service_partner_wallet_topup_paypal_order(payment_transaction, request):
    """
    Creates a PayPal order for Service 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(
            'service_partner_app:service_partner_wallet_topup_paypal_success',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    cancel_url = request.build_absolute_uri(
        reverse(
            'service_partner_app:service_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'Service 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 Hired 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'service-partner-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_service_partner_wallet_topup_paypal_checkout(request):
    profile_type = request.session.get('service_partner_wallet_topup_profile_type')
    amount_usd = request.session.get('service_partner_wallet_topup_amount_usd')
    return_url = request.session.get(
        'service_partner_wallet_topup_return_url',
        'service_partner_app:service_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 != 'service_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 Service 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='service_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_service_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['service_partner_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 service_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(
            'service_partner_app:service_partner_wallet_topup_failed',
            transaction_id=transaction_id
        )

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

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

    if payment_transaction.payment_method != 'paypal':
        messages.error(request, "Invalid payment method for PayPal wallet top-up.")
        return redirect(
            'service_partner_app:service_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(
            'service_partner_app:service_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(
            'service_partner_app:service_partner_wallet_topup_failed',
            transaction_id=payment_transaction.id
        )

    request.session.pop('service_partner_wallet_topup_profile_type', None)
    request.session.pop('service_partner_wallet_topup_amount_usd', None)
    request.session.pop('service_partner_wallet_topup_return_url', None)
    request.session.pop('service_partner_wallet_topup_transaction_id', None)

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

    return redirect('service_partner_app:service_partner_wallet_topup')

@login_required
def service_partner_wallet_topup_cancelled(request, transaction_id):
    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='service_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('service_partner_wallet_topup_profile_type', None)
    request.session.pop('service_partner_wallet_topup_amount_usd', None)
    request.session.pop('service_partner_wallet_topup_return_url', None)
    request.session.pop('service_partner_wallet_topup_transaction_id', None)

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

    return redirect('service_partner_app:service_partner_wallet_topup')


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

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

    return redirect('service_partner_app:service_partner_wallet_topup')

