from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.utils.text import slugify
from django.views.decorators.http import require_POST
from .models import (
    RentalOwner, RentalListing, RentalInterest, RentalListingImage, RentalOwnerBankingDetails,
    RentalPartnerGuidanceResource

)
from common.choices import SRI_LANKA_CITY_CHOICES
from django.contrib.auth import logout
from django.contrib.auth import get_user_model, login, update_session_auth_hash
from django.db import transaction
from decimal import Decimal, InvalidOperation
import re
import random
import string
from django.contrib import messages
from django.db.models import Prefetch

from expat_life.email_services import send_rental_owner_signup_welcome_email
from django.utils.text import slugify
from expat_life.utils import (
    get_platform_fee_settings, 
    update_rental_owner_payable_items,
    mark_rental_owner_transaction_items_paid,
    get_or_create_wallet_account,
    user_can_topup_wallet,
    complete_wallet_topup_transaction,
)
from common.payment_gateway_services import (
    get_paypal_access_token,
    get_paypal_base_url,
    get_paypal_approval_url,
    capture_paypal_order,
)
from datetime import date
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from expat_life.models import (
    UserPayableItem,
    WalletAccount,
    PaymentTransaction,
    PaymentTransactionItem,
)
from .forms import (
    RentalOwnerProfileForm,
    RentalOwnerProfileImageForm,
    RentalOwnerUsernameChangeForm,
    StyledRentalOwnerPasswordChangeForm,
    RentalOwnerSignupForm,
    RentalListingForm,
    RentalInquiryForm,
    RentalListingImageUploadForm,
    RentalOwnerBankingDetailsForm,
    RentalOwnerPasswordResetForm,
)
from django.contrib.auth.views import (
    LoginView,
    PasswordResetView,
    PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView,
)

from expat_life.forms import ContactMessageForm, WalletTopUpForm

from property_manager_app.models import PropertyManagerClientProfile
from affiliates_app.models import AffiliateProfile
import requests
from django.conf import settings
from django.utils import timezone
import stripe

User = get_user_model()

def about_us_rent(request):
    return render(request, 'rental_app/about_us_rent.html')

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

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

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

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

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

def cookie_policy_page(request):
    return render(request, 'rental_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('rental_app:success_page') +
                '?type=contact'
            )
    else:
        form = ContactMessageForm()
    return render(request, 'rental_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': 'rental_app:home_rental',
            'button_2_text': 'About Ensolanka',
            'button_2_url': 'rental_app:about_us_rent',
        },
        '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': 'rental_app:home_rental',
            'button_2_text': 'About Ensolanka',
            'button_2_url': 'rental_app:about_us_rent',
        },
        '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': 'rental_app:home_rental',
            'button_2_text': 'Contact Us',
            'button_2_url': 'rental_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': 'rental_app:home_rental',
            'button_2_text': 'Contact Us',
            'button_2_url': 'rental_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, 'rental_app/success_page.html', context)


class RentalOwnerPasswordResetView(PasswordResetView):
    template_name = 'registration/rental_password_reset.html'
    form_class = RentalOwnerPasswordResetForm
    email_template_name = 'emails/rental_app/password_reset_email.txt'
    html_email_template_name = 'emails/rental_app/password_reset_email.html'
    subject_template_name = 'emails/rental_app/password_reset_subject.txt'
    success_url = reverse_lazy('rental_app:rental_password_reset_done')
    from_email = "Rent 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_rental_owner = User.objects.filter(
            email__iexact=email,
            rental_owner_profile__isnull=False,
            is_active=True
        ).exists()

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

        return super().form_valid(form)


class RentalOwnerPasswordResetDoneView(PasswordResetDoneView):
    template_name = 'registration/rental_password_reset_done.html'


class RentalOwnerPasswordResetConfirmView(PasswordResetConfirmView):
    template_name = 'registration/rental_password_reset_confirm.html'
    success_url = reverse_lazy('rental_app:rental_password_reset_complete')


class RentalOwnerPasswordResetCompleteView(PasswordResetCompleteView):
    template_name = 'registration/rental_password_reset_complete.html'



@login_required
def rental_owner_profile_page(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    return render(request, 'rental_app/rental_owner_profile_page.html', {
        'owner': owner,
        'default_profile_image': 'expat_life/images/default-profile-neutral.png',
    })


@login_required
def edit_rental_owner_profile(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    if request.method == 'POST':
        form = RentalOwnerProfileForm(request.POST, instance=owner)
        if form.is_valid():
            # Split full name and save to User
            full_name = form.cleaned_data.get('full_name', '').strip()
            name_parts = full_name.split()
            request.user.first_name = name_parts[0] if name_parts else ''
            request.user.last_name = ' '.join(name_parts[1:]) if len(name_parts) > 1 else ''
            request.user.save()

            form.save()
            messages.success(request, "Your rental owner profile has been updated successfully.")
            return redirect('rental_app:rental_owner_profile_page')
    else:
        form = RentalOwnerProfileForm(instance=owner)

    return render(request, 'rental_app/edit_rental_owner_profile.html', {
        'form': form,
        'owner': owner,
    })


@login_required
@require_POST
def upload_rental_owner_profile_image(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return JsonResponse({
            'success': False,
            'error': 'You do not have a rental owner profile.'
        }, status=403)

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

    form = RentalOwnerProfileImageForm(request.POST, request.FILES, instance=owner)

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

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

    error_list = []
    for field_errors in form.errors.values():
        error_list.extend(field_errors)

    return JsonResponse({
        'success': False,
        'error': ' '.join(error_list) if error_list else 'Image upload failed.',
    }, status=400)


@login_required
def change_rental_owner_username(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    if request.method == 'POST':
        form = RentalOwnerUsernameChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "Your username has been updated successfully.")
            return redirect('rental_app:rental_owner_profile_page')
    else:
        form = RentalOwnerUsernameChangeForm(request.user)

    return render(request, 'rental_app/change_rental_owner_username.html', {
        'form': form,
    })


@login_required
def change_rental_owner_password(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    if request.method == 'POST':
        form = StyledRentalOwnerPasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, "Your password has been updated successfully.")
            return redirect('rental_app:rental_owner_profile_page')
    else:
        form = StyledRentalOwnerPasswordChangeForm(request.user)

    return render(request, 'rental_app/change_rental_owner_password.html', {
        'form': form,
    })



def generate_unique_listing_slug(title, instance_id=None):
    base_slug = slugify(title)
    slug = base_slug
    counter = 1

    qs = RentalListing.objects.all()
    if instance_id:
        qs = qs.exclude(id=instance_id)

    while qs.filter(slug=slug).exists():
        slug = f"{base_slug}-{counter}"
        counter += 1

    return slug

@login_required
def rental_listing_create(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    if not owner.is_approved or not owner.can_submit_listings:
        messages.warning(request, "Your account is not yet allowed to submit listings.")
        return redirect('rental_app:rental_owner_dashboard')

    if request.method == 'POST':
        form = RentalListingForm(request.POST)
        image_form = RentalListingImageUploadForm()

        if form.is_valid():
            listing = form.save(commit=False)
            listing.owner = owner
            listing.slug = generate_unique_listing_slug(form.cleaned_data['title'])
            listing.is_approved = False
            listing.is_featured = owner.is_featured
            listing.save()

            uploaded_images = request.FILES.getlist('images')
            for index, image in enumerate(uploaded_images):
                RentalListingImage.objects.create(
                    listing=listing,
                    image=image,
                    order=index
                )

            messages.success(request, "Your rental listing has been submitted successfully and is pending review.")
            return redirect('rental_app:rental_owner_dashboard')
    else:
        form = RentalListingForm()
        image_form = RentalListingImageUploadForm()

    return render(request, 'rental_app/rental_listing_form.html', {
        'form': form,
        'image_form': image_form,
        'page_title': 'Add New Rental Listing',
        'submit_label': 'Submit Listing',
        'is_edit': False,
        'listing': None,
    })

@login_required
def rental_listing_edit(request, slug):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    listing = get_object_or_404(RentalListing, slug=slug, owner=owner)

    if request.method == 'POST':
        old_title = listing.title
        form = RentalListingForm(request.POST, instance=listing)
        image_form = RentalListingImageUploadForm(request.POST, request.FILES)

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

            if updated_listing.title != old_title:
                updated_listing.slug = generate_unique_listing_slug(
                    updated_listing.title,
                    instance_id=listing.id
                )

            updated_listing.is_approved = False
            updated_listing.save()

            uploaded_images = request.FILES.getlist('images')
            current_max_order = listing.images.count()

            for index, image in enumerate(uploaded_images, start=current_max_order):
                RentalListingImage.objects.create(
                    listing=listing,
                    image=image,
                    order=index
                )

            messages.success(
                request,
                "Your rental listing has been updated successfully. The latest changes are visible to you and sent for review before public display."
            )
            return redirect('rental_app:rental_listing_edit', slug=listing.slug)

        messages.error(request, "Please correct the errors below and try again.")
    else:
        form = RentalListingForm(instance=listing)
        image_form = RentalListingImageUploadForm()

    return render(request, 'rental_app/rental_listing_form.html', {
        'form': form,
        'image_form': image_form,
        'page_title': 'Edit Rental Listing',
        'submit_label': 'Update Listing',
        'is_edit': True,
        'listing': listing,
    })

def home_rental(request):
    rental_owner_profile = None

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

    return render(request, 'rental_app/home_rental.html', {
        'rental_owner_profile': rental_owner_profile,
    })

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

    show_all_featured_listings = 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_listings = (
            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_listings:
        base_listings = RentalListing.objects.filter(
            is_approved=True,
            is_active=True,
            is_available=True,
            is_featured=True
        )
    else:
        base_listings = RentalListing.objects.filter(
            is_approved=True,
            is_active=True,
            is_available=True,
            visibility='public',
            is_featured=True
        )

    featured_properties = base_listings.prefetch_related('images').order_by('-created_at')[:6]
    latest_properties = base_listings.prefetch_related('images').order_by('-created_at')[:8]

    return render(request, 'rental_app/rental_home.html', {
        'featured_properties': featured_properties,
        'latest_properties': latest_properties,
    })
"""

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

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

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

    return username


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


@transaction.atomic
def rental_owner_signup(request):
    if request.method == 'POST':
        form = RentalOwnerSignupForm(request.POST, request.FILES)
        if form.is_valid():
            owner = 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_rental_owner_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
                )

                owner.user = user
                owner.email = email
                owner.is_approved = True
                owner.can_submit_listings = True
                owner.save()

                update_rental_owner_payable_items(user)

                transaction.on_commit(
                    lambda: send_rental_owner_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'] = 'Rental Owner'
                request.session['just_signed_up'] = True

                messages.success(request, "Your rental owner account has been created successfully.")
                return redirect('rental_app:rental_owner_dashboard')
        else:
            messages.error(request, "Please correct the errors below and try again.")
    else:
        form = RentalOwnerSignupForm()

    return render(request, 'rental_app/rental_owner_signup.html', {'form': form})


@login_required
def rental_owner_dashboard(request):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    listings = owner.listings.prefetch_related('images').all()

    total_listings = listings.count()
    approved_listings = listings.filter(is_approved=True).count()
    pending_listings = listings.filter(is_approved=False).count()
    active_listings = listings.filter(is_active=True).count()

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

    has_property_manager_profile = hasattr(
        request.user,
        'property_manager_client_profile'
    )
    has_affiliate_profile = hasattr(
        request.user,
        'affiliate_profile'
    )

    return render(request, 'rental_app/rental_owner_dashboard.html', {
        'owner': owner,
        'listings': listings,
        'total_listings': total_listings,
        'approved_listings': approved_listings,
        'pending_listings': pending_listings,
        'active_listings': active_listings,
        'default_profile_image': default_profile_image,
        'has_property_manager_profile': has_property_manager_profile,
        'has_affiliate_profile': has_affiliate_profile,
        'just_signed_up': request.session.pop('just_signed_up', False),
        'username': request.session.pop('new_account_username', None),
        'password': request.session.pop('new_account_password', None),
        'new_account_email': request.session.pop('new_account_email', None),
        'account_role': request.session.pop('account_role', None),
    })


class RentalOwnerLoginView(LoginView):
    template_name = 'registration/rental_owner_login.html'

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

        owner = getattr(user, 'rental_owner_profile', None)

        # ✅ If valid rental owner → proceed normally
        if owner:
            return response

        # ❌ Not a rental owner → logout + stay on same page
        messages.error(
            self.request,
            "This login is only for rental owners. Please use the correct login page."
        )

        logout(self.request)

        return redirect('rental_app:rental_owner_login')

    def get_success_url(self):
        return self.get_redirect_url() or reverse_lazy('rental_app:rental_owner_dashboard')



def public_rental_list(request):
    rental_owner_profile = None
    is_rental_owner_authenticated = False
    can_view_owner_listing_preview = False

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

        if rental_owner_profile:
            is_rental_owner_authenticated = True
            can_view_owner_listing_preview = True

    # -------------------------------------------------
    # Listing visibility logic
    # -------------------------------------------------
    # Rental owners can see approved public listings.
    # Public visitors can only see limited featured public examples.
    if can_view_owner_listing_preview:
        listings = RentalListing.objects.filter(
            is_approved=True,
            is_active=True,
            is_available=True,
            visibility='public',
        )
    else:
        listings = RentalListing.objects.filter(
            is_approved=True,
            is_active=True,
            is_available=True,
            visibility='public',
            is_featured=True,
        )

    # -------------------------------------------------
    # Filters
    # -------------------------------------------------
    city = request.GET.get('city', '').strip()
    property_type = request.GET.get('property_type', '').strip()
    furnishing = request.GET.get('furnishing', '').strip()
    bedrooms = request.GET.get('bedrooms', '').strip()

    # Only signed-up rental owners can use price filters.
    min_rent = request.GET.get('min_rent', '').strip() if can_view_owner_listing_preview else ''
    max_rent = request.GET.get('max_rent', '').strip() if can_view_owner_listing_preview else ''

    has_wifi = request.GET.get('has_wifi')
    has_ac = request.GET.get('has_ac')
    has_kitchen = request.GET.get('has_kitchen')
    has_parking = request.GET.get('has_parking')
    near_beach = request.GET.get('near_beach')
    suitable_for_remote_work = request.GET.get('suitable_for_remote_work')

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

    if property_type:
        listings = listings.filter(property_type=property_type)

    if furnishing:
        listings = listings.filter(furnishing=furnishing)

    if bedrooms:
        try:
            listings = listings.filter(bedrooms__gte=int(bedrooms))
        except ValueError:
            pass

    if can_view_owner_listing_preview:
        if min_rent:
            try:
                listings = listings.filter(monthly_rent_usd__gte=min_rent)
            except ValueError:
                pass

        if max_rent:
            try:
                listings = listings.filter(monthly_rent_usd__lte=max_rent)
            except ValueError:
                pass

    if has_wifi:
        listings = listings.filter(has_wifi=True)

    if has_ac:
        listings = listings.filter(has_ac=True)

    if has_kitchen:
        listings = listings.filter(has_kitchen=True)

    if has_parking:
        listings = listings.filter(has_parking=True)

    if near_beach:
        listings = listings.filter(near_beach=True)

    if suitable_for_remote_work:
        listings = listings.filter(suitable_for_remote_work=True)

    listings = listings.prefetch_related('images').order_by(
        '-is_featured',
        '-created_at'
    )

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

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

    # Keep current filters in pagination links, but remove "page"
    query_params = request.GET.copy()

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

    # Public visitors should not keep rent filters in URL pagination.
    if not can_view_owner_listing_preview:
        query_params.pop('min_rent', None)
        query_params.pop('max_rent', None)

    query_string = query_params.urlencode()

    context = {
        'listings': page_obj,
        'page_obj': page_obj,
        'paginator': paginator,

        'rental_owner_profile': rental_owner_profile,
        'is_rental_owner_authenticated': is_rental_owner_authenticated,
        'can_view_owner_listing_preview': can_view_owner_listing_preview,

        # This is useful in the template to hide pricing for public users.
        'show_pricing': can_view_owner_listing_preview,

        # This is useful in the template to show owner CTA messages.
        'is_public_limited_preview': not can_view_owner_listing_preview,

        'selected_city': city,
        'selected_property_type': property_type,
        'selected_furnishing': furnishing,
        'selected_bedrooms': bedrooms,
        'selected_min_rent': min_rent,
        'selected_max_rent': max_rent,

        'property_type_choices': RentalListing.PROPERTY_TYPE_CHOICES,
        'furnishing_choices': RentalListing.FURNISHING_CHOICES,
        'city_choices': SRI_LANKA_CITY_CHOICES,

        'query_string': query_string,
        'total_results': paginator.count,
    }

    return render(request, 'rental_app/public_rental_list.html', context)


def rental_detail(request, slug):
    rental_owner_profile = None
    is_rental_owner_authenticated = False
    can_view_owner_detail_preview = False
    is_public_limited_preview = True

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

        if rental_owner_profile:
            is_rental_owner_authenticated = True
            can_view_owner_detail_preview = True
            is_public_limited_preview = False

    # -------------------------------------------------
    # Listing access logic
    # -------------------------------------------------
    if can_view_owner_detail_preview:
        # Signed-up rental owners can preview approved active available listings.
        listing = get_object_or_404(
            RentalListing.objects.prefetch_related('images'),
            slug=slug,
            is_approved=True,
            is_active=True,
            is_available=True,
        )
    else:
        # Public users can only preview public + featured listings.
        listing = get_object_or_404(
            RentalListing.objects.prefetch_related('images'),
            slug=slug,
            is_approved=True,
            is_active=True,
            is_available=True,
            visibility='public',
            is_featured=True,
        )

    context = {
        'listing': listing,
        'all_images': listing.images.all(),

        'rental_owner_profile': rental_owner_profile,
        'is_rental_owner_authenticated': is_rental_owner_authenticated,
        'can_view_owner_detail_preview': can_view_owner_detail_preview,
        'is_public_limited_preview': is_public_limited_preview,

        # Public users should not see pricing/full detail.
        'show_pricing': can_view_owner_detail_preview,
        'show_full_details': can_view_owner_detail_preview,
    }

    return render(request, 'rental_app/rental_detail.html', context)


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

    if not foreigner_profile:
        messages.warning(request, "This area is available only to registered foreigners.")
        return redirect('expat_life:foreigner_signup')

    if not foreigner_profile.is_confirmed:
        messages.warning(request, "You need confirmed foreigner status to access this area.")
        return redirect('rental_app:public_rental_list')

    if not foreigner_profile.can_view_private_listings:
        messages.warning(request, "Your account does not yet have access to private rental listings.")
        return redirect('rental_app:public_rental_list')

    listings = RentalListing.objects.filter(
        is_approved=True,
        is_active=True,
        is_available=True,
        visibility='private'
    ).prefetch_related('images')

    return render(request, 'rental_app/private_rental_list.html', {
        'listings': listings,
        'is_confirmed_foreigner': True,
        'can_view_private_listings': True,
        'can_notify_interest': foreigner_profile.can_book_arrangements,
    })

@login_required
def notify_rental_interest(request, slug):
    if request.method != 'POST':
        return redirect('expat_life:rental_detail', slug=slug)

    listing = get_object_or_404(
        RentalListing,
        slug=slug,
        is_approved=True,
        is_active=True,
        is_available=True
    )

    foreigner_profile = getattr(request.user, 'foreigner_profile', None)

    if not foreigner_profile:
        messages.warning(request, "Only registered foreigners can use this feature.")
        return redirect('expat_life:foreigner_signup')

    if listing.visibility == 'private' and not (
        foreigner_profile.is_confirmed and foreigner_profile.can_view_private_listings
    ):
        messages.warning(request, "You do not have access to this private property.")
        return redirect('rental_app:public_rental_list')

    if not foreigner_profile.is_confirmed:
        messages.warning(
            request,
            "You need to complete the $100 confirmation process before selecting a property and starting pre-booking or negotiation."
        )
        return redirect('expat_life:rental_detail', slug=listing.slug)

    if not foreigner_profile.can_book_arrangements:
        messages.warning(
            request,
            "Your account is not yet enabled for property arrangement requests."
        )
        return redirect('expat_life:rental_detail', slug=listing.slug)

    interest, created = RentalInterest.objects.get_or_create(
        foreigner=foreigner_profile,
        listing=listing
    )

    if created:
        messages.success(
            request,
            "Your interest in this property has been recorded. Our team can now begin the next step of review and negotiation with the rental owner."
        )
    else:
        messages.info(
            request,
            "You have already expressed interest in this property."
        )

    return redirect('expat_life:rental_detail', slug=listing.slug)

@login_required
def rental_owner_listing_detail(request, slug):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    listing = get_object_or_404(
        RentalListing.objects.prefetch_related('images'),
        slug=slug,
        owner=owner
    )

    return render(request, 'rental_app/rental_owner_listing_detail.html', {
        'owner': owner,
        'listing': listing,
        'all_images': listing.images.all(),
    })

@login_required
def delete_rental_listing_image(request, image_id):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if owner is None:
        return HttpResponseForbidden("You do not have a rental owner profile.")

    image = get_object_or_404(
        RentalListingImage.objects.select_related('listing'),
        id=image_id,
        listing__owner=owner
    )

    listing = image.listing

    if request.method == 'POST':
        image.delete()

        remaining_images = listing.images.order_by('order', 'id')
        for index, img in enumerate(remaining_images):
            if img.order != index:
                img.order = index
                img.save(update_fields=['order'])

        listing.is_approved = False
        listing.save(update_fields=['is_approved'])

        messages.success(
            request,
            "Image deleted successfully. The listing has been marked for review again."
        )

    return redirect('rental_app:rental_listing_edit', slug=listing.slug)

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):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "This account is not registered as a rental owner.")
        return redirect('rental_app:home_rental')

    interests = (
        RentalInterest.objects
        .filter(listing__owner=owner)
        .select_related(
            'foreigner',
            'foreigner__lead',
            'foreigner__user',
            'listing'
        )
        .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)

        first_image = interest.listing.images.first()

        foreigner_cards.append({
            'interest': interest,
            'foreigner': foreigner,
            'lead': lead,
            'listing': interest.listing,
            'listing_image': first_image.image.url if first_image and first_image.image else '',
            'name': lead.full_name if lead and lead.full_name else foreigner.user.username,
            'country': lead.country if lead and lead.country else '',
            'nationality': lead.get_nationality_display() if lead and lead.nationality else '',
            'age': age,
            'profile_image': foreigner.profile_image.url if foreigner.profile_image else '',
        })

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

def sync_rental_owner_listings_featured_status(owner):
    """
    Update all listings for a rental owner to match the owner's
    current featured status.
    """
    if owner is None:
        return 0

    updated_count = RentalListing.objects.filter(owner=owner).update(
        is_featured=owner.is_featured
    )
    return updated_count


@login_required
def rental_owner_payment_center(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

    # Ensure rental owner payable items exist / refresh unpaid ones
    update_rental_owner_payable_items(request.user)

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


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

    payment_order = {
        'rental_owner_featured': 1,
        'rental_owner_commission': 2,
        'other': 99,
    }

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

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

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

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

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

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

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

    total_listings = owner.listings.count()
    featured_listings_count = owner.listings.filter(is_featured=True).count()
    approved_listings_count = owner.listings.filter(is_approved=True).count()

    context = {
        'owner': owner,
        '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,
        'total_listings': total_listings,
        'featured_listings_count': featured_listings_count,
        'approved_listings_count': approved_listings_count,
    }
    return render(request, 'rental_app/payment_center.html', context)

@login_required
def rental_owner_payment_checkout(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

    if request.method != 'POST':
        messages.error(request, "Please select at least one payment item first.")
        return redirect('rental_app:rental_owner_payment_center')
    
    # --- NEW: get or create the foreigner wallet ---
    wallet, created = WalletAccount.objects.get_or_create(
        user=request.user,
        profile_type='rental_owner',
        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('rental_app:rental_owner_payment_center')

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

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

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


@login_required
def rental_owner_payment_checkout_pay(request):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

    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('rental_app:rental_owner_payment_center')

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

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

    wallet, created = WalletAccount.objects.get_or_create(
        user=request.user,
        profile_type='rental_owner',
        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'))

    # ---------------------------------------------------------
    # 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('rental_app:rental_owner_payment_center')

            payment_transaction = PaymentTransaction.objects.create(
                user=request.user,
                profile_type='rental_owner',
                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_rental_owner_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(
                    'rental_app:rental_owner_payment_failed',
                    transaction_id=payment_transaction.id
                )

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

        request.session.pop('rental_owner_payment_transaction_id', None)
        request.session.pop('rental_owner_checkout_selected_ids', None)
        request.session.pop('rental_owner_checkout_total', None)
        request.session.pop('rental_owner_checkout_profile_type', None)
        request.session.pop('rental_owner_use_wallet', None)
        request.session.pop('rental_owner_wallet_deduction', None)

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

        return redirect(
            'rental_app:rental_owner_payment_success',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # Gateway payment
    # ---------------------------------------------------------
    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('rental_app:rental_owner_payment_center')

    with transaction.atomic():
        payment_transaction = PaymentTransaction.objects.create(
            user=request.user,
            profile_type='rental_owner',
            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,
            )

    request.session['rental_owner_payment_transaction_id'] = payment_transaction.id
    request.session['rental_owner_checkout_selected_ids'] = [
        item.id for item in payable_items
    ]
    request.session['rental_owner_checkout_total'] = str(amount_to_charge)
    request.session['rental_owner_checkout_profile_type'] = 'rental_owner'
    request.session['rental_owner_use_wallet'] = use_wallet
    request.session['rental_owner_wallet_deduction'] = str(wallet_deduction)

    if payment_method == 'stripe':
        return redirect('rental_app:start_rental_owner_stripe_checkout')

    if payment_method == 'paypal':
        return redirect('rental_app:start_rental_owner_paypal_checkout')

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

@login_required
def start_rental_owner_stripe_checkout(request):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

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

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

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

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

    if not settings.STRIPE_SECRET_KEY:
        messages.error(request, "Stripe payment is not configured.")
        return redirect('rental_app:rental_owner_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'Rental Owner 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 'Rental owner payment item'
                            ),
                        },
                        'unit_amount': stripe_amount_cents,
                    },
                    'quantity': 1,
                })

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

        cancel_url = request.build_absolute_uri(
            reverse(
                'rental_app:rental_owner_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': 'rental_owner',
                '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('rental_app:rental_owner_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('rental_app:rental_owner_payment_center')

@login_required
def rental_owner_stripe_payment_success(request, transaction_id):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

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

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

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

    if not settings.STRIPE_SECRET_KEY:
        messages.error(request, "Stripe payment is not configured.")
        return redirect(
            'rental_app:rental_owner_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(
            'rental_app:rental_owner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 2. Verify Stripe 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(
            'rental_app:rental_owner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 3. Verify Stripe 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(
            'rental_app:rental_owner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 4. Verify Stripe 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(
            'rental_app:rental_owner_payment_failed',
            transaction_id=payment_transaction.id
        )

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

            if locked_transaction.status == 'paid':
                messages.success(request, "This payment has already been completed.")
                return redirect(
                    'rental_app:rental_owner_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='rental_owner',
                )

                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(
                        'rental_app:rental_owner_payment_failed',
                        transaction_id=locked_transaction.id
                    )

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

            # Mark selected rental owner payable items as paid.
            mark_result = mark_rental_owner_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(
                    'rental_app:rental_owner_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(
            'rental_app:rental_owner_payment_failed',
            transaction_id=payment_transaction.id
        )

    # ---------------------------------------------------------
    # 6. Clear checkout session data
    # ---------------------------------------------------------
    request.session.pop('rental_owner_payment_transaction_id', None)
    request.session.pop('rental_owner_checkout_selected_ids', None)
    request.session.pop('rental_owner_checkout_total', None)
    request.session.pop('rental_owner_checkout_profile_type', None)
    request.session.pop('rental_owner_use_wallet', None)
    request.session.pop('rental_owner_wallet_deduction', None)

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

    return redirect(
        'rental_app:rental_owner_payment_success',
        transaction_id=payment_transaction.id
    )

@login_required
def start_rental_owner_stripe_checkout(request):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

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

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

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

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

    if not settings.STRIPE_SECRET_KEY:
        messages.error(request, "Stripe payment is not configured.")
        return redirect('rental_app:rental_owner_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'Rental Owner 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 'Rental owner payment item'
                            ),
                        },
                        'unit_amount': stripe_amount_cents,
                    },
                    'quantity': 1,
                })

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

        cancel_url = request.build_absolute_uri(
            reverse(
                'rental_app:rental_owner_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': 'rental_owner',
                '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('rental_app:rental_owner_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('rental_app:rental_owner_payment_center')
@login_required
def rental_owner_payment_success(request, transaction_id):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

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

@login_required
def rental_owner_payment_cancelled(request, transaction_id):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

    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, 'rental_app/payment_cancelled.html', {
        'owner': owner,
        'payment_transaction': payment_transaction,
        'page_title': 'Payment Cancelled',
    })

@login_required
def rental_owner_payment_failed(request, transaction_id):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

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

#Paypal

@login_required
def start_rental_owner_paypal_checkout(request):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

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

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

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

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

    try:
        order_data = create_rental_owner_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('rental_app:rental_owner_payment_center')

def create_rental_owner_paypal_order(payment_transaction, request):
    """
    Creates a PayPal order for Rental Owner / Property 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(
            'rental_app:rental_owner_paypal_payment_success',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    cancel_url = request.build_absolute_uri(
        reverse(
            'rental_app:rental_owner_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'Rental Owner Payment - Transaction #{payment_transaction.id}',
                'custom_id': str(payment_transaction.id),
                'amount': {
                    'currency_code': 'USD',
                    'value': str(amount_value),
                },
            }
        ],
        'application_context': {
            'brand_name': 'Ensolanka Rent 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'rental-owner-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 rental_owner_paypal_payment_success(request, transaction_id):
    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

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

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

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

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

            if locked_transaction.status == 'paid':
                messages.success(request, "This payment has already been completed.")
                return redirect(
                    'rental_app:rental_owner_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='rental_owner',
                )

                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(
                        'rental_app:rental_owner_payment_failed',
                        transaction_id=locked_transaction.id
                    )

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

            mark_result = mark_rental_owner_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(
                    'rental_app:rental_owner_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(
            'rental_app:rental_owner_payment_failed',
            transaction_id=payment_transaction.id
        )

    request.session.pop('rental_owner_payment_transaction_id', None)
    request.session.pop('rental_owner_checkout_selected_ids', None)
    request.session.pop('rental_owner_checkout_total', None)
    request.session.pop('rental_owner_checkout_profile_type', None)
    request.session.pop('rental_owner_use_wallet', None)
    request.session.pop('rental_owner_wallet_deduction', None)

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

    return redirect(
        'rental_app:rental_owner_payment_success',
        transaction_id=payment_transaction.id
    )

#============================================================

@login_required
def rental_owner_banking_details(request):
    owner = getattr(request.user, 'rental_owner_profile', None)
    if not owner:
        messages.error(request, "Rental owner profile not found.")
        return redirect('rental_app:home_rental')

    banking_details, created = RentalOwnerBankingDetails.objects.get_or_create(
        owner=owner,
        defaults={
            'account_holder_name': owner.full_name or '',
            'bank_name': '',
            'branch_name': '',
            'account_number': '',
            'iban': '',
            'swift_code': '',
            'bank_country': '',
            'bank_address': '',
            'payment_notes': '',
        }
    )

    if request.method == 'POST':
        form = RentalOwnerBankingDetailsForm(request.POST, instance=banking_details)
        if form.is_valid():
            form.save()
            messages.success(request, "Banking details updated successfully.")
            return redirect('rental_app:rental_owner_banking_details')
    else:
        form = RentalOwnerBankingDetailsForm(instance=banking_details)

    context = {
        'owner': owner,
        'banking_details': banking_details,
        'form': form,
    }
    return render(request, 'rental_app/rental_owner_banking_details.html', context)

@login_required
@require_POST
@transaction.atomic
def activate_property_manager_from_rental_owner(request):
    """
    Creates a Property Care client profile for the currently logged-in
    Rental Owner, using available rental owner profile details,
    then redirects to the Property Care Dashboard.

    If the Property Care profile already exists,
    simply redirect to the dashboard.
    """

    user = request.user

    # ---------------------------------------------------------
    # 1. Confirm this user has a Rental Owner profile
    # ---------------------------------------------------------
    rental_owner = getattr(
        user,
        'rental_owner_profile',
        None
    )

    if rental_owner is None:
        messages.warning(
            request,
            "Please activate Rental Owner access first before creating a Property Care profile."
        )
        return redirect(
            'rental_app:rental_owner_dashboard'
        )

    # ---------------------------------------------------------
    # 2. If Property Care profile already exists, just redirect
    # ---------------------------------------------------------
    existing_property_manager_profile = getattr(
        user,
        'property_manager_client_profile',
        None
    )

    if existing_property_manager_profile is not None:
        messages.info(
            request,
            "Your Property Care access is already active."
        )
        return redirect(
            'property_manager_app:property_manager_dashboard'
        )

    # ---------------------------------------------------------
    # 3. Map Rental Owner type to Property Care client type
    # ---------------------------------------------------------
    if rental_owner.owner_type == 'company':
        client_type = 'company'
    else:
        client_type = 'individual'

    # ---------------------------------------------------------
    # 4. Create Property Care client profile
    # ---------------------------------------------------------
    PropertyManagerClientProfile.objects.create(
        user=user,
        client_type=client_type,

        # We do not assume overseas/local residence from rental owner data.
        residency_status='other',

        full_name=rental_owner.full_name,
        email=rental_owner.email or user.email,
        whatsapp_number=rental_owner.whatsapp_number,
        phone_number=rental_owner.phone_number,

        current_country='',
        current_city='',

        emergency_contact_name='',
        emergency_contact_phone='',

        short_note=(
            "Property Care access was activated from the existing Rental Owner account."
        ),

        is_identity_verified=rental_owner.is_identity_verified,
        is_approved=True,
        can_submit_properties=True,
    )

    # ---------------------------------------------------------
    # 5. Success and redirect
    # ---------------------------------------------------------
    messages.success(
        request,
        "Property Care access has been activated successfully. You can now register properties for care and maintenance."
    )

    return redirect(
        'property_manager_app:property_manager_dashboard'
    )

@login_required
@require_POST
@transaction.atomic
def activate_affiliate_from_rental_owner(request):
    """
    Creates an Affiliate Profile for the currently logged-in
    Rental Owner using available existing profile details,
    then redirects to the Affiliate Dashboard.

    If an Affiliate Profile already exists,
    simply redirect to the dashboard.
    """

    user = request.user

    # ---------------------------------------------------------
    # 1. Confirm this user has a Rental Owner profile
    # ---------------------------------------------------------
    rental_owner = getattr(
        user,
        'rental_owner_profile',
        None
    )

    if rental_owner is None:
        messages.warning(
            request,
            "Please activate Rental Owner access first before creating an Affiliate profile."
        )
        return redirect(
            'rental_app:rental_owner_dashboard'
        )

    # ---------------------------------------------------------
    # 2. If Affiliate profile already exists, just redirect
    # ---------------------------------------------------------
    existing_affiliate_profile = getattr(
        user,
        'affiliate_profile',
        None
    )

    if existing_affiliate_profile is not None:
        messages.info(
            request,
            "Your Affiliate access is already active."
        )
        return redirect(
            'affiliates_app:affiliate_dashboard'
        )

    # ---------------------------------------------------------
    # 3. Create Affiliate Profile
    #    affiliate_code auto-generates in AffiliateProfile.save()
    # ---------------------------------------------------------
    AffiliateProfile.objects.create(
        user=user,
        full_name=rental_owner.full_name,
        phone=rental_owner.phone_number,
        whatsapp=rental_owner.whatsapp_number,
        country='',
        status='approved',
        is_active=True,
    )

    # ---------------------------------------------------------
    # 4. Success and redirect
    # ---------------------------------------------------------
    messages.success(
        request,
        "Affiliate access has been activated successfully. You can now open your Affiliate Dashboard and use your Global Ambassador tools."
    )

    return redirect(
        'affiliates_app:affiliate_dashboard'
    )

def rental_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 = RentalPartnerGuidanceResource.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,
        'rental_app/rental_partner_information_center.html',
        context
    )

@login_required
def rental_owner_wallet_topup(request):
    """
    Rental Owner direct wallet top-up page.

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

    owner = getattr(request.user, 'rental_owner_profile', None)

    if not owner:
        messages.error(
            request,
            "Rental Owner wallet top-up is available only for registered Rental Owner accounts."
        )
        return redirect('rental_app:home_rental')

    profile_type = 'rental_owner'
    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['rental_wallet_topup_profile_type'] = profile_type
            request.session['rental_wallet_topup_amount_usd'] = str(amount_usd)
            request.session['rental_wallet_topup_return_url'] = 'rental_app:rental_owner_wallet_topup'

            if payment_method == 'stripe':
                return redirect('rental_app:start_rental_owner_wallet_topup_stripe_checkout')

            if payment_method == 'paypal':
                return redirect('rental_app:start_rental_owner_wallet_topup_paypal_checkout')

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

    return render(request, 'rental_app/rental_owner_wallet_topup.html', {
        'form': form,
        'wallet': wallet,
        'owner': owner,
        'profile': owner,
        'profile_type': profile_type,
        'page_title': 'Rental Owner Wallet Top-up',
        'account_label': 'Rental Owner Wallet',
    })

@login_required
def start_rental_owner_wallet_topup_stripe_checkout(request):
    profile_type = request.session.get('rental_wallet_topup_profile_type')
    amount_usd = request.session.get('rental_wallet_topup_amount_usd')
    return_url = request.session.get(
        'rental_wallet_topup_return_url',
        'rental_app:rental_owner_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 != 'rental_owner':
        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 Rental Owner 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='rental_owner',
            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(
                'rental_app:rental_owner_wallet_topup_stripe_success',
                kwargs={'transaction_id': payment_transaction.id}
            )
        ) + '?session_id={CHECKOUT_SESSION_ID}'

        cancel_url = request.build_absolute_uri(
            reverse(
                'rental_app:rental_owner_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': 'Rental Owner Wallet Top-up',
                            'description': (
                                f'Wallet top-up for Rental Owner 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': 'rental_owner',
                '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['rental_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 rental_owner_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(
            'rental_app:rental_owner_wallet_topup_failed',
            transaction_id=transaction_id
        )

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

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

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

    request.session.pop('rental_wallet_topup_profile_type', None)
    request.session.pop('rental_wallet_topup_amount_usd', None)
    request.session.pop('rental_wallet_topup_return_url', None)
    request.session.pop('rental_wallet_topup_transaction_id', None)

    messages.success(
        request,
        "Your Rental Owner wallet has been topped up successfully."
    )

    return redirect('rental_app:rental_owner_wallet_topup')

def create_rental_owner_wallet_topup_paypal_order(payment_transaction, request):
    """
    Creates a PayPal order for Rental Owner 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(
            'rental_app:rental_owner_wallet_topup_paypal_success',
            kwargs={'transaction_id': payment_transaction.id}
        )
    )

    cancel_url = request.build_absolute_uri(
        reverse(
            'rental_app:rental_owner_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'Rental Owner 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 Rent 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'rental-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_rental_owner_wallet_topup_paypal_checkout(request):
    profile_type = request.session.get('rental_wallet_topup_profile_type')
    amount_usd = request.session.get('rental_wallet_topup_amount_usd')
    return_url = request.session.get(
        'rental_wallet_topup_return_url',
        'rental_app:rental_owner_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 != 'rental_owner':
        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 Rental Owner 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='rental_owner',
            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_rental_owner_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['rental_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 rental_owner_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(
            'rental_app:rental_owner_wallet_topup_failed',
            transaction_id=transaction_id
        )

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

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

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

    request.session.pop('rental_wallet_topup_profile_type', None)
    request.session.pop('rental_wallet_topup_amount_usd', None)
    request.session.pop('rental_wallet_topup_return_url', None)
    request.session.pop('rental_wallet_topup_transaction_id', None)

    messages.success(
        request,
        "Your Rental Owner wallet has been topped up successfully."
    )

    return redirect('rental_app:rental_owner_wallet_topup')

@login_required
def rental_owner_wallet_topup_cancelled(request, transaction_id):
    payment_transaction = get_object_or_404(
        PaymentTransaction,
        id=transaction_id,
        user=request.user,
        profile_type='rental_owner',
        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('rental_wallet_topup_profile_type', None)
    request.session.pop('rental_wallet_topup_amount_usd', None)
    request.session.pop('rental_wallet_topup_return_url', None)
    request.session.pop('rental_wallet_topup_transaction_id', None)

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

    return redirect('rental_app:rental_owner_wallet_topup')

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

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

    return redirect('rental_app:rental_owner_wallet_topup')