public with sharing class PdfApiController {
    
    @AuraEnabled
    public static Map<String, Object> generatePreview(String template, String propertyName, String propertyType, 
                                                    String location, String price, String bedrooms, String bathrooms, 
                                                    String area, String description) {
        
        try {
            // Prepare data for Python API with all required fields
            Map<String, Object> previewData = new Map<String, Object>{
                'template' => template,
                'propertyName' => propertyName,
                'propertyType' => propertyType,
                'location' => location,
                'price' => price,
                'bedrooms' => bedrooms,
                'bathrooms' => bathrooms,
                'area' => area,
                'description' => description
            };

            String jsonBody = JSON.serialize(previewData);

            // Call Python API for preview
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint('https://salesforce.tech4biz.io/api/preview');
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/json');
            request.setBody(jsonBody);
            request.setTimeout(120000); // 2 minutes timeout
            
            HttpResponse response = http.send(request);
            
            if (response.getStatusCode() == 200) {
                Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                
                if (result.containsKey('success') && (Boolean) result.get('success')) {
                    // Extract the preview data from the nested structure
                    Map<String, Object> preview = (Map<String, Object>) result.get('preview');
                    
                    return new Map<String, Object>{
                        'success' => true,
                        'preview_html' => preview.get('preview_html'),
                        'template_info' => preview.get('template_info'),
                        'property_data' => preview.get('property_data'),
                        'message' => 'Preview generated successfully'
                    };
                } else {
                    String errorMessage = result.get('message') != null ? (String) result.get('message') : 'Preview generation failed';
                    return new Map<String, Object>{
                        'success' => false,
                        'error' => errorMessage
                    };
                }
            } else {
                return new Map<String, Object>{
                    'success' => false,
                    'error' => 'HTTP ' + response.getStatusCode() + ': ' + response.getBody()
                };
            }
            
        } catch (Exception e) {
            return new Map<String, Object>{
                'success' => false,
                'error' => 'Exception: ' + e.getMessage()
            };
        }
    }
    
    @AuraEnabled
    public static Map<String, Object> generatePdf(String templateName, String propertyName, String propertyType, 
                                                 String location, String price, String bedrooms, String bathrooms, 
                                                 String area, String description) {
        try {
            Map<String, Object> propertyData = new Map<String, Object>{
                'template' => templateName,
                'propertyName' => propertyName,
                'propertyType' => propertyType,
                'location' => location,
                'price' => price,
                'bedrooms' => bedrooms,
                'bathrooms' => bathrooms,
                'area' => area,
                'description' => description
            };
            Map<String, Object> requestData = new Map<String, Object>{
                'template_name' => templateName,
                'property_data' => propertyData
            };
            String jsonBody = JSON.serialize(requestData);
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint('https://salesforce.tech4biz.io/api/generate-pdf');
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/json');
            request.setBody(jsonBody);
            request.setTimeout(120000);
            HttpResponse response = http.send(request);
            
            if (response.getStatusCode() == 200) {
                Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                if (result.containsKey('success') && (Boolean) result.get('success')) {
                    // Try to fetch the actual PDF content
                    if (result.containsKey('pdf_url')) {
                        String pdfUrl = (String) result.get('pdf_url');
                        System.debug('PDF URL received: ' + pdfUrl);
                        System.debug('Full API response: ' + JSON.serialize(result));
                        
                        // Make a GET request to fetch the actual PDF content
                        HttpRequest pdfRequest = new HttpRequest();
                        pdfRequest.setEndpoint('https://salesforce.tech4biz.io' + pdfUrl);
                        pdfRequest.setMethod('GET');
                        pdfRequest.setTimeout(120000);
                        HttpResponse pdfResponse = http.send(pdfRequest);
                        
                        System.debug('PDF fetch response status: ' + pdfResponse.getStatusCode());
                        System.debug('PDF fetch response headers: ' + pdfResponse.getHeaderKeys());
                        System.debug('PDF fetch response body length: ' + pdfResponse.getBody().length());
                        
                        if (pdfResponse.getStatusCode() == 200) {
                            // Successfully got PDF content
                            Blob pdfBlob = pdfResponse.getBodyAsBlob();
                            String base64Pdf = EncodingUtil.base64Encode(pdfBlob);
                            
                            System.debug('PDF blob size: ' + pdfBlob.size());
                            System.debug('Base64 PDF length: ' + base64Pdf.length());
                            
                            // Extract filename from URL or create one
                            String filename = 'property_report_' + propertyName + '_' + templateName + '.pdf';
                            if (pdfUrl.contains('/')) {
                                String[] urlParts = pdfUrl.split('/');
                                if (urlParts.size() > 0) {
                                    String lastPart = urlParts[urlParts.size() - 1];
                                    if (lastPart.endsWith('.pdf')) {
                                        filename = lastPart;
                                    }
                                }
                            }
                            
                            System.debug('Final filename: ' + filename);
                            
                            return new Map<String, Object>{
                                'success' => true,
                                'message' => 'PDF generated successfully',
                                'pdf_data' => base64Pdf,
                                'filename' => filename,
                                'content_type' => 'application/pdf'
                            };
                        } else {
                            System.debug('Failed to fetch PDF content: HTTP ' + pdfResponse.getStatusCode());
                            System.debug('PDF fetch error response: ' + pdfResponse.getBody());
                            // If PDF fetch fails, try to get preview content as fallback
                            return getPreviewContentAsFallback(templateName, propertyName, propertyType, 
                                                           location, price, bedrooms, bathrooms, area, description);
                        }
                    } else {
                        System.debug('No pdf_url in response, falling back to preview');
                        System.debug('Available keys in result: ' + result.keySet());
                        return getPreviewContentAsFallback(templateName, propertyName, propertyType, 
                                                       location, price, bedrooms, bathrooms, area, description);
                    }
                } else {
                    String errorMessage = result.get('message') != null ? (String) result.get('message') : 'PDF generation failed';
                    return new Map<String, Object>{
                        'success' => false,
                        'error' => errorMessage
                    };
                }
            } else {
                return new Map<String, Object>{
                    'success' => false,
                    'error' => 'HTTP ' + response.getStatusCode() + ': ' + response.getBody()
                };
            }
        } catch (Exception e) {
            return new Map<String, Object>{
                'success' => false,
                'error' => 'Exception: ' + e.getMessage()
            };
        }
    }
    
    // Helper method to get preview content as fallback
    private static Map<String, Object> getPreviewContentAsFallback(String templateName, String propertyName, 
                                                                 String propertyType, String location, String price, 
                                                                 String bedrooms, String bathrooms, String area, String description) {
        try {
            Map<String, Object> previewData = new Map<String, Object>{
                'template' => templateName,
                'propertyName' => propertyName,
                'propertyType' => propertyType,
                'location' => location,
                'price' => price,
                'bedrooms' => bedrooms,
                'bathrooms' => bathrooms,
                'area' => area,
                'description' => description
            };
            String previewJsonBody = JSON.serialize(previewData);
            Http http = new Http();
            HttpRequest previewRequest = new HttpRequest();
            previewRequest.setEndpoint('https://salesforce.tech4biz.io/api/preview-simple');
            previewRequest.setMethod('POST');
            previewRequest.setHeader('Content-Type', 'application/json');
            previewRequest.setBody(previewJsonBody);
            previewRequest.setTimeout(120000);
            HttpResponse previewResponse = http.send(previewRequest);
            
            if (previewResponse.getStatusCode() == 200) {
                Map<String, Object> previewResult = (Map<String, Object>) JSON.deserializeUntyped(previewResponse.getBody());
                Map<String, Object> preview = (Map<String, Object>) previewResult.get('preview');
                return new Map<String, Object>{
                    'success' => true,
                    'message' => 'PDF generation failed, but preview content is available. Use this to create your PDF manually.',
                    'preview_html' => preview.get('preview_html'),
                    'template_info' => preview.get('template_info'),
                    'property_data' => preview.get('property_data'),
                    'note' => 'The PDF download endpoint is currently unavailable. Use the preview content to create your PDF manually or contact support.',
                    'fallback' => true
                };
            } else {
                return new Map<String, Object>{
                    'success' => false,
                    'error' => 'Failed to get preview content: HTTP ' + previewResponse.getStatusCode()
                };
            }
        } catch (Exception e) {
            return new Map<String, Object>{
                'success' => false,
                'error' => 'Exception getting preview content: ' + e.getMessage()
            };
        }
    }
} 