from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.db.models import Q
import threading
from django.core.mail import send_mail, BadHeaderError, EmailMultiAlternatives
from django.core.mail import EmailMessage
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
from django.utils import timezone
import re
from django.http import HttpResponse, JsonResponse, Http404
from datetime import datetime
import os
import logging
import socket

logger = logging.getLogger(__name__)


SERVICE_TEMPLATES = {
    'digital-marketing':  'services/digital_marketing.html',
    'digital-signature':  'services/digital_signature.html',
    'ict-support':        'services/ict_support.html',
    'web-development':    'services/web_development.html',
    'software-development':'services/software_development.html',
    'mobile-applications':'services/mobile_applications.html',
    'cloud-services':     'services/cloud_services.html',
    'data-entry':         'services/data_entry.html',
    # 'client-form':         'services/client_form.html',
}
 
SERVICE_TITLES = {
    'digital-marketing':   'Digital Marketing',
    'mis-solutions':       'MIS Solutions',
    'software-development':'Software Development',
    'ict-support':        'ICT Support',
    'digital-signature':   'Digital Signature',
    'web-development':     'Web Development',
    'mobile-applications': 'Mobile Applications',
    'cloud-services':      'Cloud Services',
    'graphics-designing':  'Graphics Designing',
    'data-entry':          'Data Entry',
    # 'client-form':          'Client form'
}
current_year = datetime.now().year
years_of_experience = current_year - 2003 # ========== PRODUCTS CONFIGURATION ==========

PRODUCT_TEMPLATES = {
    'dsigner-component-tool':           'products/dsigner_component_tool.html',
    'real-time-signing-tool':           'products/real_time_signing_tool.html',
    'signing-verification-component':   'products/signing_verification_component.html',
    'dsigner-crypto-token':             'products/dsigner_crypto_token.html',
    'encryption-signing-component':     'products/encryption_signing_component.html',
    'electronic-management-system':     'products/electronic_management_system.html',
    'bulk-signing-component':           'products/bulk_signing_component.html',
    'optical-character-recognition':    'products/optical_character_recognition.html',
    'lakshya-micro-banking':            'products/lakshya_micro_banking.html',
    'cms-tours-travels':                'products/cms_tours_travels.html',
    'ecommerce-websites':               'products/ecommerce_websites.html',
}

PRODUCT_TITLES = {
    'dsigner-component-tool':           'DSigner Component Tool',
    'real-time-signing-tool':           'Real Time Signing Tool for Insurance Online Policy',
    'signing-verification-component':   'Signing and Verification Component (Soft Token)',
    'dsigner-crypto-token':             'DSigner (Crypto-Token)',
    'encryption-signing-component':     'Encryption Signing Component Tools',
    'electronic-management-system':     'Electronic Management System',
    'bulk-signing-component':           'Bulk Signing Component Tool',
    'optical-character-recognition':    'Optical Character Recognition Tool',
    'lakshya-micro-banking':            'Lakshya Micro Banking Software',
    'cms-tours-travels':                'CMS for Tours and Travels',
    'ecommerce-websites':               'Ecommerce Websites',
}

PRODUCT_DESCRIPTIONS = {
    'dsigner-component-tool': 'Automates signing of PDF documents and embedded form data via API with support for dynamic form data input and field-level signing.',
    'real-time-signing-tool': 'Fulfills scope for signing documents/data on real time using digital signature certificates for insurance policies.',
    'signing-verification-component': 'Supports making any application PKI enabled for using DSc issued in Soft Token with secure digital identity verification.',
    'dsigner-crypto-token': 'Supports making any application PKI enabled for using DSc issued in Crypto Token with blockchain integration.',
    'encryption-signing-component': 'Makes application and business process compatible for using digital signature certificates with encryption/decryption.',
    'electronic-management-system': 'Centralized storage and management of digital documents with version control and audit trails.',
    'bulk-signing-component': 'Supports management of document flow and archival of documents with batch signing capabilities.',
    'optical-character-recognition': 'Accurately converts scanned documents and images into editable text with AI-based algorithms.',
    'lakshya-micro-banking': 'Comprehensive management of microfinance operations and customer accounts for loans, deposits, and reports.',
    'cms-tours-travels': 'Complete control over tour packages, reservations, and customer records with integrated CRM.',
    'ecommerce-websites': 'Advanced product management, seamless checkout, inventory management, and secure transactions.',
}

PRODUCT_FEATURES = {
    'dsigner-component-tool': [
        'Supports dynamic form data input and field-level signing within PDFs',
        'Allows bulk signing of multiple documents in a single operation',
        'Real-time status and feedback via API response',
        'Securely integrates with external APIs',
        'Handles static and interactive PDF forms efficiently',
        'Configurable signature placement and appearance',
        'Seamless integration with Windows environment',
    ],
    'real-time-signing-tool': [
        'Automates signing of insurance documents and policy forms via API',
        'Ensures compliance with regulatory standards',
        'Supports dynamic form data input and field-level signing within insurance PDFs',
        'Handles static and interactive insurance forms, including claims and policy documents',
        'Allows bulk signing of multiple insurance documents',
        'Customizable signature placement and appearance',
        'Real-time status updates and feedback via API',
        'Integrates with Windows and insurance management systems',
        'Document validation and verification for authenticity',
    ],
    'signing-verification-component': [
        'Streamlined online company registration with soft-token authentication',
        'Secure digital identity verification and document signing',
        'Easy integration with registration authorities and compliance systems',
        'Supports digital signing of registration forms',
        'Real-time validation and submission',
        'Secure storage of digital certificates and soft-token credentials',
        'Customizable workflows',
        'User-friendly interface',
    ],
    'dsigner-crypto-token': [
        'Online company registration with crypto-token-based authentication',
        'Secure and decentralized identity verification',
        'Integrates with blockchain technology',
        'Supports digital signing of registration forms and compliance documents',
        'Real-time application validation and submission using blockchain ledger',
        'Secure management of crypto-tokens and digital assets',
        'Customizable registration workflows',
        'Advanced tracking and reporting features',
    ],
    'encryption-signing-component': [
        'Encrypt and decrypt PDF files with advanced cryptography algorithms',
        'Bulk processing of multiple PDFs',
        'Supports AES-256 and RSA encryption standards',
        'Easy integration with command-line or API-based operations',
        'Enables digital signing of PDFs with secure key pairs',
        'Seamless decryption of password-protected PDF files',
        'Verify authenticity of signed documents',
        'Detailed logs for tracking',
        'Configurable signing position and encryption settings',
    ],
    'electronic-management-system': [
        'Centralized storage and management of digital documents',
        'Organizes files with metadata, tagging, and categories',
        'Supports wide range of file formats (PDFs, Word documents, images)',
        'Version control to track document changes',
        'Compliance and audit trails',
        'Access control and user permissions',
        'Efficient search and filtering',
        'Seamless integration with external systems and APIs',
        'Automated backup and recovery',
        'Document workflows for review, approval, and archiving',
    ],
    'bulk-signing-component': [
        'Batch sign multiple PDF files simultaneously',
        'Option to overlay signatures or watermark',
        'Supports large PDF files up to 100MB',
        'Detailed logging of signed documents',
        'Integrates with digital certificates',
        'Customizable signing position on each page',
        'Fast processing times',
        'User-friendly interface',
    ],
    'optical-character-recognition': [
        'Supports PNG, JPEG, TIFF',
        'Extracts text from complex documents, including multi-page PDFs',
        'Recognizes multiple languages and scripts',
        'Batch processing for OCR on multiple files',
        'Configurable output formats (plain text, Word, searchable PDF)',
        'Seamless integration with document management systems',
        'Post-OCR editing and verification',
        'Advanced AI-based algorithms for handwritten text recognition',
    ],
    'lakshya-micro-banking': [
        'Supports loans, savings, and deposits',
        'Automated loan disbursement, collection, and repayment tracking',
        'Real-time reporting and analytics',
        'Customizable workflow management for loan processing',
        'Integrated customer management system',
        'Supports branch-level operations with multi-user access and role-based permissions',
        'Handles regulatory compliance and reporting',
        'Seamless integration with third-party systems (mobile wallets, payment gateways)',
        'Secure, cloud-based access for remote management',
    ],
    'cms-tours-travels': [
        'Offers flights, hotels, and vacation packages',
        'Automated booking confirmations, payment handling, itinerary updates',
        'Live reporting and insights',
        'Integrated CRM for client preferences and travel history',
        'Supports multi-location operations with user-specific roles',
        'Integration with payment systems and travel APIs',
        'Customizable workflows',
        'Cloud-based, secure platform',
        'Ensures compliance with industry regulations',
        'Responsive design on all platforms',
        'No device detection needed (faster loading)',
        'Manage content in one CMS',
        'Accessible for users with disabilities',
        'High performance technologies',
    ],
    'ecommerce-websites': [
        'Advanced product management with categories, attributes, variants',
        'Seamless checkout with multiple payment gateways',
        'Real-time order tracking and customer notification',
        'Customizable product catalogs and promotional campaigns',
        'Robust inventory management with automated stock updates',
        'Detailed sales analytics',
        'Customer account management with order history and wish lists',
        'Data encryption and secure transactions',
        'Integration with shipping providers and third-party services',
        'Scalable and customizable design',
        'Flexible product management',
        'Insightful sales reports and customer behavior analytics',
        'Integrated shopping cart',
        'Comprehensive order management',
        'High-level security',
        'Customizable user roles and permissions',
        'Integration with external APIs',
        'Advanced search functionality',
        'Responsive and adaptive design',
    ],
}


def home(request):
    
    context = {
        'title': 'Home - Radiant Infotech',
        'description': 'Welcome to Radiant Infotech, your trusted partner for software development and digital signature solutions.',
        'keywords': 'home, radiant infotech, software development, digital signature, web development, mobile apps, e-signature',
    }
    return render(request, 'pages/home.html', context)

def about_us(request):
    
    context = {
        'title': 'About Us',
        'description': 'Welcome to Radiant Infotech, your trusted partner for software development and digital signature solutions.',
        'keywords': 'home, radiant infotech, software development, digital signature, web development, mobile apps, e-signature',
    }
    return render(request, 'pages/about_us.html', context)

def services(request):
    
    context = {
        'title': 'Services - Radiant Infotech',
        'description': 'Welcome to Radiant Infotech, your trusted partner for software development and digital signature solutions.',
        'keywords': 'home, radiant infotech, software development, digital signature, web development, mobile apps, e-signature',
    }
    return render(request, 'pages/services.html', context)

def service_detail(request, slug):
    template = SERVICE_TEMPLATES.get(slug)
    if not template:
        raise Http404("Service not found.")
 
    context = {
        'service_slug':  slug,
        'service_title': SERVICE_TITLES.get(slug, 'Service'),
    }
    return render(request, template, context)

# def Client_form(request):
#     return render(request,'services/client_from.html')

def products(request):
    """
    Products listing page showing all products
    """
    products_list = []
    for slug, title in PRODUCT_TITLES.items():
        products_list.append({
            'slug': slug,
            'title': title,
            'description': PRODUCT_DESCRIPTIONS.get(slug, ''),
            'features': PRODUCT_FEATURES.get(slug, [])[:3],  
        })
    
    context = {
        'title': 'Products - Radiant Infotech',
        'description': 'Explore our comprehensive range of digital products including digital signature tools, document management systems, banking software, and more.',
        'keywords': 'digital signature, document signing, OCR, micro banking, ecommerce, CMS, software products, Nepal',
        'products': products_list,
    }
    return render(request, 'pages/products.html', context)

def product_detail(request, slug):
    """
    Individual product detail page
    """
    template = PRODUCT_TEMPLATES.get(slug)
    if not template:
        raise Http404("Product not found.")
    
    context = {
        'product_slug': slug,
        'product_title': PRODUCT_TITLES.get(slug, 'Product'),
        'product_description': PRODUCT_DESCRIPTIONS.get(slug, ''),
        'product_features': PRODUCT_FEATURES.get(slug, []),
        'product_name': PRODUCT_TITLES.get(slug, 'Product'),
    }
    return render(request, template, context)


def gallery(request):
    
    context = {
        'title': 'Home - Radiant Infotech',
        'description': 'Welcome to Radiant Infotech, your trusted partner for software development and digital signature solutions.',
        'keywords': 'home, radiant infotech, software development, digital signature, web development, mobile apps, e-signature',
    }
    return render(request, 'pages/gallery.html', context)

def career(request):
    
    context = {
        'title': 'Career - Radiant Infotech',
        'description': 'Welcome to Radiant Infotech, your trusted partner for software development and digital signature solutions.',
        'keywords': 'home, radiant infotech, software development, digital signature, web development, mobile apps, e-signature',
    }
    return render(request, 'pages/career.html', context)

def contact_us(request):
    
    context = {
        'title': 'Home - Radiant Infotech',
        'description': 'Welcome to Radiant Infotech, your trusted partner for software development and digital signature solutions.',
        'keywords': 'home, radiant infotech, software development, digital signature, web development, mobile apps, e-signature',
    }
    return render(request, 'pages/contact_us.html', context)



def view_404(request, exception=None):
    return render(request, 'pages/404.html', status=404)

def send_contact_email(form_data, file_data=None):
    """
    Send emails to admin and user for Radiant Infotech Pvt. Ltd contact form with attachment support
    """
    try:
        # Prepare admin email with attachment
        admin_subject = f"New Contact Form Inquiry - Radiant Infotech Pvt. Ltd Website"
        admin_message = f"""
New Contact Form Submission from Radiant Infotech Pvt. Ltd Website:

Name: {form_data.get('name')}
Email: {form_data.get('email')}
Subject: {form_data.get('subject')}

Message:
{form_data.get('message')}

Submitted on: {form_data.get('timestamp', 'Now')}

This inquiry was submitted through the Radiant Infotech website.
        """
        
        # Create email with attachment for admin
        admin_email = EmailMessage(
            subject=admin_subject,
            body=admin_message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=[settings.ADMIN_EMAIL],
        )
        
        if file_data:
            admin_email.attach(
                file_data['filename'],
                file_data['content'],
                file_data['content_type']
            )
        
        admin_email.send(fail_silently=False)
        
        user_subject = "Thank You for Your Inquiry - Radiant Infotech Pvt. Ltd"
        user_message = f"""
Dear {form_data.get('name')},

Thank you for reaching out to Radiant Infotech Pvt. Ltd. We have received your inquiry and our team will get back to you within 24 hours on business days.

Here's a summary of your inquiry:
- Subject: {form_data.get('subject')}
- Submitted: {form_data.get('timestamp', 'Now')}

{'Attached file: ' + file_data['filename'] if file_data else ''}

For urgent inquiries, please contact us at:
Email: {settings.DEFAULT_FROM_EMAIL}
Phone: 01-4545765 , 01-4524311

Best regards,
Radiant Infotech Pvt. Ltd Team
Your Trusted Technology Partner
        """
        
        user_email_addr = form_data.get('email')
        if user_email_addr:
            user_email = EmailMessage(
                subject=user_subject,
                body=user_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[user_email_addr],
            )
            user_email.send(fail_silently=False)
            
    except BadHeaderError:
        print("Invalid header found.")
    except Exception as e:
        print(f"Error sending email: {e}")


@csrf_exempt
@require_POST
def contact_submit(request):
    """
    Handle contact form submission with file attachment and send emails for Radiant Infotech Pvt. Ltd
    """
    try:
        name = request.POST.get('name', '').strip()
        email = request.POST.get('email', '').strip()
        subject = request.POST.get('subject', '').strip()
        message = request.POST.get('message', '').strip()
        
        if not all([name, email, subject, message]):
            return JsonResponse({
                'success': False,
                'message': 'Please fill in all required fields.'
            }, status=400)
        
        email_regex = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
        if not re.match(email_regex, email):
            return JsonResponse({
                'success': False,
                'message': 'Please enter a valid email address.'
            }, status=400)
        
        form_data = {
            'name': name,
            'email': email,
            'subject': subject,
            'message': message,
            'timestamp': timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
            'company': "Radiant Infotech Pvt. Ltd"
        }
        
        file_data = None
        if 'attachment' in request.FILES:
            uploaded_file = request.FILES['attachment']
            
            if uploaded_file.size > 10 * 1024 * 1024:
                return JsonResponse({
                    'success': False,
                    'message': 'File size must be less than 10MB.'
                }, status=400)
            
            allowed_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.jpeg', '.png', '.txt', '.zip']
            file_ext = os.path.splitext(uploaded_file.name)[1].lower()
            
            if file_ext not in allowed_extensions:
                return JsonResponse({
                    'success': False,
                    'message': 'File type not allowed. Please upload PDF, DOC, DOCX, JPG, PNG, TXT, or ZIP files.'
                }, status=400)
            
            file_data = {
                'filename': uploaded_file.name,
                'content': uploaded_file.read(),
                'content_type': uploaded_file.content_type or 'application/octet-stream'
            }
        
        email_thread = threading.Thread(
            target=send_contact_email,
            args=(form_data, file_data)
        )
        email_thread.daemon = True
        email_thread.start()
        
        return JsonResponse({
            'success': True,
            'message': 'Thank you for contacting Radiant Infotech Pvt. Ltd! We have received your inquiry and will get back to you within 24 hours. A confirmation email has been sent to your email address.'
        })
        
    except Exception as e:
        print(f"Error in contact_submit: {e}")
        return JsonResponse({
            'success': False,
            'message': f'An error occurred: {str(e)}'
        }, status=500)
from django.shortcuts import render
from django.http import JsonResponse
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from .forms import DigitalSignatureApplicationForm
import re
import datetime


def digital_signature_apply(request):
    if request.method == 'POST':
        form = DigitalSignatureApplicationForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            subject = f"New Digital Signature Application — {data.get('full_name', 'Unknown')}"
            from_email = settings.EMAIL_HOST_USER
            to_email = settings.DSC_RECEIVER_EMAIL

            html_body = build_email_html(data, request.FILES.get('image'))
            plain_body = re.sub(r'<[^>]+>', '', html_body)

            msg = EmailMultiAlternatives(subject, plain_body, from_email, to_email)
            msg.attach_alternative(html_body, "text/html")

            photo = request.FILES.get('image')
            if photo:
                photo.seek(0)
                msg.attach(photo.name, photo.read(), photo.content_type)

            try:
                msg.send(fail_silently=False)
                return JsonResponse({'success': True, 'message': 'Application submitted successfully!'})
            except Exception as e:
              logger.exception("Email sending failed")
              return JsonResponse(
              {
            'success': False,
            'errors': str(e)
            },
        status=500
    )

        else:
            print("FORM ERRORS:", form.errors)
            return JsonResponse({'success': False, 'errors': form.errors}, status=400)

    return render(request, 'services/client_form.html')


def bool_badge(val):
    if val:
        return '<span style="background:#16a34a;color:#fff;padding:2px 8px;border-radius:4px;font-size:12px;">YES</span>'
    return '<span style="background:#e5e7eb;color:#6b7280;padding:2px 8px;border-radius:4px;font-size:12px;">NO</span>'


def row(label, value):
    if value in (None, '', False):
        value = '—'
    elif value is True:
        value = '✔'
    return f"""
        <tr>
          <td style="padding:8px 12px;font-weight:600;color:#374151;background:#f9fafb;width:40%;border-bottom:1px solid #e5e7eb;">{label}</td>
          <td style="padding:8px 12px;color:#111827;border-bottom:1px solid #e5e7eb;">{value}</td>
        </tr>"""


def section(title, rows_html):
    return f"""
    <div style="margin-bottom:28px;">
      <div style="background:#1e40af;color:#fff;padding:10px 16px;border-radius:8px 8px 0 0;font-size:15px;font-weight:700;">
        {title}
      </div>
      <table style="width:100%;border-collapse:collapse;border:1px solid #e5e7eb;border-top:none;">
        {rows_html}
      </table>
    </div>"""


def build_email_html(data, photo_file):
    import base64
    import os
    from django.conf import settings
    from django.contrib.staticfiles import finders
    
    purposes = []
    if data.get('puropse_all'):           purposes.append('All types of transactions')
    if data.get('purpose_banking'):       purposes.append('Banking')
    if data.get('purpose_purchase'):      purposes.append('Purchase & Sale')
    if data.get('purpose_certification'): purposes.append('Certification of correspondence')
    purpose_str = ', '.join(purposes) if purposes else '—'

    usage = []
    if data.get('use_signature'):  usage.append('Signature')
    if data.get('use_encryption'): usage.append('Encryption')
    if data.get('use_both'):       usage.append('Both')
    usage_str = ', '.join(usage) if usage else '—'

    validity_map = {'1': '1 Year', '2': '2 Years'}
    validity_str = validity_map.get(data.get('validity_year', ''), '—')

    class_map = {'1': 'Class 1', '2': 'Class 2', '3': 'Class 3', 'GIOMS': 'Class GIOMS'}
    class_str = class_map.get(data.get('certificate_class', ''), '—')

    now = datetime.datetime.now().strftime('%B %d, %Y at %I:%M %p')

    # Handle logo image - try to find and embed it
    logo_base64 = ''
    try:
        logo_path = finders.find('img/radiant_logo.png')
        if logo_path:
            with open(logo_path, 'rb') as f:
                logo_data = f.read()
                logo_base64 = base64.b64encode(logo_data).decode('utf-8')
        else:
            static_logo_path = os.path.join(settings.BASE_DIR, 'static', 'img', 'radiant_logo.png')
            if os.path.exists(static_logo_path):
                with open(static_logo_path, 'rb') as f:
                    logo_data = f.read()
                    logo_base64 = base64.b64encode(logo_data).decode('utf-8')
    except Exception as e:
        print(f"Could not load logo: {e}")
        logo_base64 = ''

    logo_html = ''
    if logo_base64:
        logo_html = f'<img src="data:image/png;base64,{logo_base64}" alt="Radiant Infotech Nepal" style="width:120px;height:auto;" />'
    else:
        logo_html = '''
        <div style="width:120px;height:auto;background:#f1f5f9;padding:12px 8px;border-radius:4px;text-align:center;font-size:12px;color:#6b7280;border:1px solid #e5e7eb;">
            <span style="font-size:32px;display:block;margin-bottom:4px;">🏢</span>
            Radiant Infotech Nepal
        </div>
        '''

    # Handle photo attachment display
    photo_display = ''
    if photo_file:
        try:
            photo_file.seek(0)
            photo_data = photo_file.read()
            photo_base64 = base64.b64encode(photo_data).decode('utf-8')
            photo_type = photo_file.content_type or 'image/jpeg'
            photo_display = f'''
            <div style="position:absolute;top:0;right:0;width:128px;height:144px;border:2px dashed #d1d5db;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;overflow:hidden;background:#f9fafb;">
                <img src="data:{photo_type};base64,{photo_base64}" style="width:100%;height:100%;object-fit:cover;" alt="Applicant Photo" />
            </div>
            '''
        except Exception as e:
            print(f"Error processing photo: {e}")
            photo_display = '''
            <div style="position:absolute;top:0;right:0;width:128px;height:144px;border:2px dashed #d1d5db;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;overflow:hidden;background:#f9fafb;">
                <div style="text-align:center;padding:4px;">
                    <span style="font-size:24px;display:block;margin-bottom:4px;">📷</span>
                    <p style="font-size:10px;color:#9ca3af;margin:0;line-height:1.2;">Photo attached</p>
                </div>
            </div>
            '''
    else:
        photo_display = '''
        <div style="position:absolute;top:0;right:0;width:128px;height:144px;border:2px dashed #d1d5db;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;overflow:hidden;background:#f9fafb;">
            <div style="text-align:center;padding:4px;">
                <span style="font-size:24px;display:block;margin-bottom:4px;">📷</span>
                <p style="font-size:10px;color:#9ca3af;margin:0;line-height:1.2;">No photo uploaded</p>
            </div>
        </div>
        '''

    # Helper function to process file attachments
    def process_file(file_obj, field_name):
        if not file_obj:
            return '<p style="color:#9ca3af;font-size:13px;">No file uploaded</p>'
        try:
            file_obj.seek(0)
            file_data = file_obj.read()
            file_base64 = base64.b64encode(file_data).decode('utf-8')
            file_name = file_obj.name
            file_size = len(file_data) // 1024  # size in KB
            file_type = file_obj.content_type or 'application/octet-stream'
            
            # Determine file icon based on type
            icon = '📄'
            if 'pdf' in file_type:
                icon = '📕'
            elif 'image' in file_type:
                icon = '🖼️'
            elif 'word' in file_type or 'doc' in file_type:
                icon = '📘'
            elif 'excel' in file_type or 'sheet' in file_type:
                icon = '📊'
            
            return f'''
            <div style="border:1px solid #e5e7eb;border-radius:8px;padding:12px 16px;background:#f9fafb;display:flex;align-items:center;gap:12px;">
                <span style="font-size:24px;">{icon}</span>
                <div style="flex:1;">
                    <p style="margin:0;font-weight:500;font-size:14px;color:#1f2937;">{file_name}</p>
                    <p style="margin:0;font-size:12px;color:#6b7280;">{file_size} KB • {file_type}</p>
                </div>
                <a href="data:{file_type};base64,{file_base64}" download="{file_name}" 
                   style="background:#3b82f6;color:#fff;padding:6px 12px;border-radius:6px;text-decoration:none;font-size:13px;">
                    Download
                </a>
            </div>
            '''
        except Exception as e:
            print(f"Error processing {field_name}: {e}")
            return f'<p style="color:#ef4444;font-size:13px;">Error loading file: {str(e)}</p>'

    # Process all document files
    pan_vat_doc = process_file(data.get('pan_vat_document'), 'pan_vat_document')
    company_reg_doc = process_file(data.get('company_registration_document'), 'company_registration_document')
    engineering_council_doc = process_file(data.get('engineering_council_document'), 'engineering_council_document')
    citizenship_doc = process_file(data.get('citizenship_document'), 'citizenship_document')
    tax_clearance_doc = process_file(data.get('tax_clearance_document'), 'tax_clearance_document')

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .section-card {{ transition: box-shadow 0.2s ease; }}
    .section-card:hover {{ box-shadow: 0 8px 25px rgba(0,0,0,0.05); }}
    .photo-upload-box {{ transition: background 0.2s, border-color 0.2s; }}
    .photo-upload-box:hover {{ background: #f8fafc; border-color: #3b82f6; }}
  </style>
</head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:Arial,sans-serif;font-size:14px;">

<div style="max-width:900px;margin:30px auto;background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,0.08);padding:20px;">

  <!-- ============================================================ -->
  <!-- PART 1 — SCHEDULE 5                                          -->
  <!-- ============================================================ -->
  <div style="background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:24px 32px;margin-bottom:32px;">
    <div style="text-align:center;border-bottom:1px solid #e5e7eb;padding-bottom:16px;margin-bottom:24px;">
      <h2 style="font-weight:700;font-size:20px;margin:0 0 4px;">Schedule – 5</h2>
      <p style="font-size:13px;color:#6b7280;margin:0;">(Relating to Sub-rule (1) of Rule 31)</p>
      <div style="margin-top:8px;">
        <p style="font-weight:700;font-size:20px;color:#1f2937;margin:0;">The Radiant InfoTech Nepal Private Limited</p>
        <p style="font-size:15px;font-weight:600;color:#4338ca;margin:0;">(Issuing Certifying Authority)</p>
      </div>
      <p style="font-weight:600;margin-top:12px;font-size:15px;color:#374151;">Subject: Request for Issuance of the Digital Signature Certificate</p>
    </div>

    <p style="font-size:15px;color:#16a34a;margin:0 0 24px;background:#f8fafc;padding:12px 16px;border-radius:8px;border:1px solid #e5e7eb;">
      <span style="color:#3b82f6;margin-right:8px;">ℹ️</span>
      As the certified Digital signature is required to be obtained, I have filed this application attaching the following documents and details.
    </p>

    <div style="margin-bottom:24px;">
      <!-- Full Name -->
      <div style="margin-bottom:16px;">
        <label style="font-weight:600;color:#1f2937;display:block;margin-bottom:4px;display:flex;align-items:center;gap:8px;">
          <span style="background:#dbeafe;color:#1d4ed8;width:24px;height:24px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">1</span>
          Full Name and address of the subscriber
        </label>
        <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('full_name', '—')}</div>
      </div>

      <!-- Legal Status -->
      <div style="margin-bottom:16px;">
        <label style="font-weight:600;color:#1f2937;display:block;margin-bottom:4px;display:flex;align-items:center;gap:8px;">
          <span style="background:#dbeafe;color:#1d4ed8;width:24px;height:24px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">2</span>
          Legal status of subscriber
        </label>
        <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('legal_status', '—')}</div>
      </div>

      <!-- 3.1 Natural Person -->
      <div style="margin-bottom:16px;">
        <p style="font-weight:600;color:#1f2937;display:flex;align-items:center;gap:8px;margin:0 0 8px;">
          <span style="background:#dbeafe;color:#1d4ed8;width:24px;height:24px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">3</span>
          Certificate to identify the subscriber
        </p>
        <div style="margin-left:8px;padding-left:8px;border-left:2px solid #bfdbfe;">
          <p style="font-weight:500;color:#374151;margin:0 0 8px;font-size:14px;">3.1 In case of natural person:</p>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
            <div>
              <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">a) Citizenship/Passport No.</label>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('citizenship_no', '—')}</div>
            </div>
            <div>
              <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">b) Issuing office</label>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('issuing_office', '—')}</div>
            </div>
            <div>
              <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">c) Date of issue</label>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('issue_date', '—')}</div>
            </div>
            <div>
              <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">d) Duration of validity</label>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('duration_validity', '—')}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 3.2 Company -->
      <div style="margin-bottom:16px;">
        <div style="margin-left:8px;padding-left:8px;border-left:2px solid #bfdbfe;">
          <p style="font-weight:500;color:#374151;margin:0 0 8px;font-size:14px;">3.2 In case of a firm, Company, Corporate body or Agency</p>
          <div style="margin-bottom:12px;">
            <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">a) Registration Certificate</label>
            <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('registration_certificate', '—')}</div>
          </div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:12px;">
            <div>
              <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">b) Date of Issue</label>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('company_issue_date', '—')}</div>
            </div>
            <div>
              <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">c) Issuing office</label>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('company_issuing_office', '—')}</div>
            </div>
          </div>
          <div>
            <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">d) Objectives</label>
            <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('objectives', '—')}</div>
          </div>
        </div>
      </div>

      <!-- Purpose -->
      <div style="margin-bottom:16px;">
        <p style="font-weight:600;color:#1f2937;display:flex;align-items:center;gap:8px;margin:0 0 8px;">
          <span style="background:#dbeafe;color:#1d4ed8;width:24px;height:24px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">4</span>
          For what purpose the digital signature is intended to obtain:
        </p>
        <div style="margin-left:8px;padding-left:8px;border-left:2px solid #bfdbfe;padding-top:4px;">
          <div style="display:flex;flex-direction:column;gap:8px;font-size:14px;">
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid #2563eb;border-radius:4px;text-align:center;background:{'#2563eb' if data.get('puropse_all') else '#fff'};color:{'#fff' if data.get('puropse_all') else '#6b7280'};font-size:12px;line-height:14px;">
                {'✓' if data.get('puropse_all') else ''}
              </span>
              <span style="color:{'#111827' if data.get('puropse_all') else '#6b7280'};">For all types of possible transaction</span>
            </div>
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid #2563eb;border-radius:4px;text-align:center;background:{'#2563eb' if data.get('purpose_banking') else '#fff'};color:{'#fff' if data.get('purpose_banking') else '#6b7280'};font-size:12px;line-height:14px;">
                {'✓' if data.get('purpose_banking') else ''}
              </span>
              <span style="color:{'#111827' if data.get('purpose_banking') else '#6b7280'};">For Banking Purposes</span>
            </div>
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid #2563eb;border-radius:4px;text-align:center;background:{'#2563eb' if data.get('purpose_purchase') else '#fff'};color:{'#fff' if data.get('purpose_purchase') else '#6b7280'};font-size:12px;line-height:14px;">
                {'✓' if data.get('purpose_purchase') else ''}
              </span>
              <span style="color:{'#111827' if data.get('purpose_purchase') else '#6b7280'};">For other transactions relating to purchase and sale</span>
            </div>
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid #2563eb;border-radius:4px;text-align:center;background:{'#2563eb' if data.get('purpose_certification') else '#fff'};color:{'#fff' if data.get('purpose_certification') else '#6b7280'};font-size:12px;line-height:14px;">
                {'✓' if data.get('purpose_certification') else ''}
              </span>
              <span style="color:{'#111827' if data.get('purpose_certification') else '#6b7280'};">For the certification that any correspondence is issued by oneself</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Threshold -->
      <div style="margin-bottom:16px;">
        <label style="font-weight:600;color:#1f2937;display:flex;align-items:center;gap:8px;margin-bottom:4px;">
          <span style="background:#dbeafe;color:#1d4ed8;width:24px;height:24px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">5</span>
          Maximum threshold of each transaction:
        </label>
        <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;max-width:320px;">{data.get('transaction_threshold', '—')}</div>
      </div>

      <!-- Declaration -->
      <div style="display:flex;align-items:flex-start;gap:8px;margin-bottom:16px;">
        <span style="display:inline-block;width:20px;height:20px;border:2px solid #16a34a;border-radius:4px;text-align:center;background:{'#16a34a' if data.get('declaration') else '#fff'};color:{'#fff' if data.get('declaration') else '#6b7280'};font-size:14px;line-height:18px;margin-top:2px;">
          {'✓' if data.get('declaration') else ''}
        </span>
        <span style="font-size:14px;">Details stated above are true and correct. I shall submit other details and proofs, as required by the Authority, at a time when so asked and I shall, upon the issuance of license, pay the fee therefor.</span>
      </div>

      <!-- Signature row -->
      <div style="display:flex;flex-wrap:wrap;justify-content:flex-end;gap:16px;padding-top:8px;border-top:1px solid #e5e7eb;">
        <div style="display:flex;align-items:center;gap:8px;">
          <span style="font-size:13px;color:#6b7280;font-weight:500;">Applicant's:</span>
          <span style="border:1px solid #d1d5db;padding:8px 12px;border-radius:8px;background:#f9fafb;font-size:14px;width:160px;display:inline-block;">{data.get('applicant_name', '—')}</span>
        </div>
        <div style="display:flex;align-items:center;gap:8px;">
          <span style="font-size:13px;color:#6b7280;font-weight:500;">Name:</span>
          <span style="border:1px solid #d1d5db;padding:8px 12px;border-radius:8px;background:#f9fafb;font-size:14px;width:160px;display:inline-block;">{data.get('final_name', '—')}</span>
        </div>
        <div style="display:flex;align-items:center;gap:8px;">
          <span style="font-size:13px;color:#6b7280;font-weight:500;">Signature:</span>
          <span style="border:1px solid #d1d5db;padding:8px 12px;border-radius:8px;background:#f9fafb;font-size:14px;width:160px;display:inline-block;">{data.get('signature', '—')}</span>
        </div>
      </div>
      <p style="font-size:12px;color:#6b7280;font-style:italic;margin:8px 0 0;">In the case of a corporate body, the seal of the office, signature, name, and designation of the person making the application on behalf of the body.</p>
    </div>
  </div>

  <!-- ============================================================ -->
  <!-- PART 2 — ADDITIONAL INFORMATION                               -->
  <!-- ============================================================ -->
  <div style="background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:24px 32px;position:relative;">

    <div style="position:relative;margin-bottom:32px;">
      <div style="text-align:center;border-bottom:1px solid #e5e7eb;padding-bottom:16px;">
        <h2 style="font-size:24px;font-weight:700;color:#1f2937;margin:0;">Additional Information</h2>
        <p style="font-size:13px;color:#6b7280;margin:0;">As mentioned Electronic Transactions Rules 2064 "Chapter -5" (3)</p>
        <div style="margin-top:8px;">
          <p style="font-weight:700;font-size:20px;color:#1f2937;margin:0;">The Radiant InfoTech Nepal Private Limited</p>
          <p style="font-size:15px;font-weight:600;color:#4338ca;margin:0;">(Issuing Certifying Authority)</p>
        </div>
      </div>

      <!-- Photo upload display with actual image -->
      {photo_display}
    </div>

    <div style="margin-bottom:32px;">

      <!-- Address -->
      <div style="margin-bottom:24px;">
        <p style="font-weight:700;color:#1f2937;font-size:18px;display:flex;align-items:center;gap:8px;margin:0 0 12px;">
          <span style="background:#e0e7ff;color:#4338ca;width:28px;height:28px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">1</span>
          Name, surname and address of the subscriber
        </p>
        <div style="margin-left:8px;padding-left:8px;border-left:2px solid #c7d2fe;">
          <p style="font-weight:500;color:#374151;font-size:14px;margin:0 0 12px;">1.1 In case of natural person</p>
          <div style="margin-bottom:12px;">
            <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">a) Address</label>
            <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('address', '—')}</div>
          </div>
          <div>
            <p style="color:#374151;font-weight:500;margin-bottom:4px;font-size:13px;">b) Permanent Address (Mailing)</p>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-bottom:12px;">
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_province', '—')}</div>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('district', '—')}</div>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('municipality', '—')}</div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px;">
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('city', '—')}</div>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('ward', '—')}</div>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('post_box', '—')}</div>
              <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('contact_number', '—')}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Contact -->
      <div style="margin-bottom:24px;">
        <p style="font-weight:700;color:#1f2937;font-size:18px;display:flex;align-items:center;gap:8px;margin:0 0 12px;">
          <span style="background:#e0e7ff;color:#4338ca;width:28px;height:28px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">2</span>
          Contact details of the subscriber
        </p>
        <div style="margin-left:8px;padding-left:8px;border-left:2px solid #c7d2fe;">
          <p style="font-weight:500;color:#374151;font-size:14px;margin:0 0 12px;">2.1 In case of natural person</p>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
            <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('email', '—')}</div>
            <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('alternate_email', '—')}</div>
            <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('cell_number', '—')}</div>
            <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('telephon_no', '—')}</div>
          </div>
        </div>
      </div>

      <!-- Organization -->
      <div style="margin-bottom:24px;">
        <div style="margin-left:8px;padding-left:8px;border-left:2px solid #c7d2fe;">
          <p style="font-weight:700;color:#1f2937;font-size:15px;margin:0 0 12px;">2.2 In case of Firm, Company, Corporate body or Agency</p>
          <div style="display:grid;grid-template-columns:1fr;gap:16px;">
            <div style="display:flex;flex-wrap:wrap;align-items:center;gap:8px;">
              <span style="font-size:13px;font-weight:500;width:160px;">a) Organization Name:</span>
              <span style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;flex:1;min-width:200px;">{data.get('organization_name', '—')}</span>
            </div>

            <div>
              <p style="font-size:13px;font-weight:500;margin:0 0 8px;">Type of Organization:</p>
              <div style="display:flex;flex-wrap:wrap;gap:16px;font-size:13px;">
                <span style="display:flex;align-items:center;gap:6px;{'color:#6b7280' if data.get('organization_type') != 'Proprietorship' else 'color:#111827'}">
                  <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('organization_type') == 'Proprietorship' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('organization_type') == 'Proprietorship' else '#fff')};"></span> Proprietorship
                </span>
                <span style="display:flex;align-items:center;gap:6px;{'color:#6b7280' if data.get('organization_type') != 'Partnership' else 'color:#111827'}">
                  <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('organization_type') == 'Partnership' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('organization_type') == 'Partnership' else '#fff')};"></span> Partnership
                </span>
                <span style="display:flex;align-items:center;gap:6px;{'color:#6b7280' if data.get('organization_type') != 'Public' else 'color:#111827'}">
                  <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('organization_type') == 'Public' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('organization_type') == 'Public' else '#fff')};"></span> Public
                </span>
                <span style="display:flex;align-items:center;gap:6px;{'color:#6b7280' if data.get('organization_type') != 'NGO/INGO' else 'color:#111827'}">
                  <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('organization_type') == 'NGO/INGO' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('organization_type') == 'NGO/INGO' else '#fff')};"></span> NGO/INGO
                </span>
                <span style="display:flex;align-items:center;gap:6px;{'color:#6b7280' if data.get('organization_type') != 'Government' else 'color:#111827'}">
                  <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('organization_type') == 'Government' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('organization_type') == 'Government' else '#fff')};"></span> Government
                </span>
                <span style="display:flex;align-items:center;gap:6px;{'color:#6b7280' if data.get('organization_type') != 'Others' else 'color:#111827'}">
                  <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('organization_type') == 'Others' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('organization_type') == 'Others' else '#fff')};"></span> Others
                </span>
              </div>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
              <div>
                <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">b) Address</label>
                <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_address', '—')}</div>
              </div>
              <div>
                <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">City</label>
                <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_city', '—')}</div>
              </div>
              <div>
                <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">Province</label>
                <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_province', '—')}</div>
              </div>
              <div>
                <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">District</label>
                <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_district', '—')}</div>
              </div>
              <div>
                <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">VDC/Municipality</label>
                <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_municipality', '—')}</div>
              </div>
              <div>
                <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">Ward No</label>
                <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_ward', '—')}</div>
              </div>
            </div>

            <div>
              <p style="font-weight:600;color:#1f2937;margin:8px 0 4px;">Registration Certificate</p>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:8px;">
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">a) PAN/VAT No</label>
                  <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('pan_vat', '—')}</div>
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">Tax Clearance Up to</label>
                  <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('tax_clearance', '—')}</div>
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">b) E-mail</label>
                  <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_email', '—')}</div>
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">Alternative E-mail</label>
                  <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('organization_alternate_email', '—')}</div>
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">c) Telephone/Fax</label>
                  <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('fax', '—')}</div>
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">Website (URL)</label>
                  <div style="border:1px solid #d1d5db;padding:10px 12px;border-radius:8px;background:#f9fafb;font-size:14px;">{data.get('website', '—')}</div>
                </div>
              </div>
            </div>

            <!-- NEW: Required Documents Section -->
            <div>
              <p style="font-weight:600;color:#1f2937;margin:8px 0 4px;">Required Documents</p>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:8px;">
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">a) PAN / VAT Certificate Copy</label>
                  {pan_vat_doc}
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">b) Company Registration Copy</label>
                  {company_reg_doc}
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">c) Engineering Council Certificate copy [If Applicable]</label>
                  {engineering_council_doc}
                </div>
                <div>
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">d) Citizenship copy</label>
                  {citizenship_doc}
                </div>
                <div style="grid-column: span 2;">
                  <label style="color:#374151;display:block;margin-bottom:4px;font-size:13px;font-weight:500;">e) Tax Clearance Copy (Latest)</label>
                  {tax_clearance_doc}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Certificate Class -->
      <div>
        <p style="font-weight:700;color:#1f2937;font-size:18px;display:flex;align-items:center;gap:8px;margin:0 0 12px;">
          <span style="background:#e0e7ff;color:#4338ca;width:28px;height:28px;border-radius:9999px;display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">3</span>
          Certificate class and purpose
        </p>
        <div style="margin-left:8px;padding-left:8px;border-left:2px solid #c7d2fe;">
          <div style="display:flex;flex-wrap:wrap;gap:20px;margin-bottom:12px;">
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('certificate_class') == '1' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('certificate_class') == '1' else '#fff')};"></span> Class 1
            </span>
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('certificate_class') == '2' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('certificate_class') == '2' else '#fff')};"></span> Class 2
            </span>
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('certificate_class') == '3' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('certificate_class') == '3' else '#fff')};"></span> Class 3
            </span>
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('certificate_class') == 'GIOMS' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('certificate_class') == 'GIOMS' else '#fff')};"></span> Class (GIOMS)
            </span>
          </div>
          <div style="display:flex;flex-wrap:wrap;gap:20px;margin-bottom:12px;">
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid #2563eb;border-radius:4px;text-align:center;background:{'#2563eb' if data.get('use_signature') else '#fff'};color:{'#fff' if data.get('use_signature') else '#6b7280'};font-size:12px;line-height:14px;">{'✓' if data.get('use_signature') else ''}</span> Signature
            </span>
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid #2563eb;border-radius:4px;text-align:center;background:{'#2563eb' if data.get('use_encryption') else '#fff'};color:{'#fff' if data.get('use_encryption') else '#6b7280'};font-size:12px;line-height:14px;">{'✓' if data.get('use_encryption') else ''}</span> Encryption
            </span>
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid #2563eb;border-radius:4px;text-align:center;background:{'#2563eb' if data.get('use_both') else '#fff'};color:{'#fff' if data.get('use_both') else '#6b7280'};font-size:12px;line-height:14px;">{'✓' if data.get('use_both') else ''}</span> Both (Signature and Encryption)
            </span>
          </div>
          <div style="display:flex;flex-wrap:wrap;gap:20px;">
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('validity_year') == '1' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('validity_year') == '1' else '#fff')};"></span> 1 Year
            </span>
            <span style="display:flex;align-items:center;gap:6px;font-size:14px;">
              <span style="display:inline-block;width:16px;height:16px;border:2px solid {('#2563eb' if data.get('validity_year') == '2' else '#d1d5db')};border-radius:9999px;background:{('#2563eb' if data.get('validity_year') == '2' else '#fff')};"></span> 2 Years
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- Footer -->
    <div style="margin-top:40px;border-top:1px solid #e5e7eb;padding-top:24px;display:flex;flex-wrap:wrap;justify-content:space-between;align-items:flex-end;gap:24px;">
      <div style="font-size:13px;color:#6b7280;line-height:1.8;">
        <p style="margin:0;">📍 Radiant Building, Naxal, Bhattbhateni, Kathmandu, Nepal</p>
        <p style="margin:0;">📞 Tel.: +977-01-4545765, 4524311</p>
        <p style="margin:0;">✉️ Email:
          <a href="mailto:dsc@radiantnepal.info" style="color:#2563eb;text-decoration:none;">dsc@radiantnepal.info</a>,
          <a href="mailto:admin@radiantnepal.com" style="color:#2563eb;text-decoration:none;">admin@radiantnepal.com</a>
        </p>
        <p style="margin:0;">🌐 Website:
          <a href="https://www.radiantca.com.np" target="_blank" style="color:#2563eb;text-decoration:none;">www.radiantca.com.np</a>
        </p>
      </div>
      <div style="text-align:center;">
        <div style="border-top:1px solid #d1d5db;width:256px;margin:0 auto 8px;"></div>
        <p style="font-weight:600;font-size:13px;color:#374151;margin:0;">Official Seal & Stamp (If Any) / Signature</p>
        <div style="margin-top:12px;display:flex;flex-direction:column;align-items:center;">
          {logo_html}
          <a href="https://www.radiantca.com.np" target="_blank" style="font-size:12px;margin-top:4px;color:#2563eb;text-decoration:none;">www.radiantca.com.np</a>
          <p style="font-size:12px;color:#374151;margin:0;">(Issuing Certifying Authority)</p>
        </div>
      </div>
    </div>
  </div>

  <!-- Timestamp footer -->
  <div style="text-align:center;padding-top:20px;font-size:12px;color:#9ca3af;border-top:1px solid #e5e7eb;margin-top:20px;">
    <p style="margin:0;">Application submitted on: {now}</p>
    <p style="margin:4px 0 0;">© Radiant InfoTech Nepal Private Limited — Issuing Certifying Authority</p>
  </div>
</div>
</body>
</html>"""