@login_required
def send_invoice_whatsapp(request):
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Method not allowed'})
    
    try:
        # Handle JSON payload
        data = json.loads(request.body)
        sale_id = data.get('sale_id')
        phone = data.get('phone')
        pdf_data = data.get('pdf_data') # Base64 string
    except json.JSONDecodeError:
        # Fallback to Form Data
        sale_id = request.POST.get('sale_id')
        phone = request.POST.get('phone')
        pdf_data = None
    
    if not sale_id:
        return JsonResponse({'success': False, 'error': 'Sale ID missing'})
    
    sale = get_object_or_404(Sale, pk=sale_id)
    
    if not phone:
        if sale.customer and sale.customer.phone:
            phone = sale.customer.phone
        else:
             return JsonResponse({'success': False, 'error': 'Phone number missing'})
    
    try:
        # If PDF data is present, save and send document
        if pdf_data:
            # Remove header if present (data:application/pdf;base64,)
            if ',' in pdf_data:
                pdf_data = pdf_data.split(',')[1]
            
            file_data = base64.b64decode(pdf_data)
            dir_path = os.path.join(django_settings.MEDIA_ROOT, 'temp_invoices')
            os.makedirs(dir_path, exist_ok=True)
            
            filename = f"invoice_{sale.id}_{int(timezone.now().timestamp())}.pdf"
            file_path = os.path.join(dir_path, filename)
            
            with open(file_path, 'wb') as f:
                f.write(file_data)
                
            # Construct URL
            file_url = request.build_absolute_uri(django_settings.MEDIA_URL + 'temp_invoices/' + filename)
            
            success, response_msg = send_whatsapp_document(phone, file_url, caption=f"Invoice #{sale.invoice_number or sale.id}")
            
        else:
            # Fallback to Text Link
            receipt_url = request.build_absolute_uri(reverse('sale_receipt', args=[sale.pk]))
            
            message = (
                f"Hello {sale.customer.name if sale.customer else 'Guest'},
"
                f"Here is your invoice #{sale.invoice_number or sale.id}.
"
                f"Total: {sale.total_amount}
"
                f"View Invoice: {receipt_url}
"
                f"Thank you for your business!"
            )
            
            success, response_msg = send_whatsapp_message(phone, message)
        
        if success:
             return JsonResponse({'success': True, 'message': response_msg})
        else:
             return JsonResponse({'success': False, 'error': response_msg})
             
    except Exception as e:
        logger.error(f"WhatsApp Error: {e}")
        return JsonResponse({'success': False, 'error': str(e)}) # Changed to str(e) for clarity
