public with sharing class PropertyTemplateController {
    
    @AuraEnabled(cacheable=true)
    public static List<Property_Template__c> getPropertyTemplates() {
        try {
            return [SELECT Id, Name, Description__c, Preview_Image_URL__c, Tags__c, 
                           Is_Active__c, Template_Definition__c 
                    FROM Property_Template__c 
                    WHERE Is_Active__c = true 
                    ORDER BY Name];
        } catch (Exception e) {
            throw new AuraHandledException('Error fetching templates: ' + e.getMessage());
        }
    }
    
    @AuraEnabled(cacheable=true)
    public static Property_Template__c getPropertyTemplateById(String templateId) {
        try {
            return [SELECT Id, Name, Description__c, Preview_Image_URL__c, Tags__c, 
                           Is_Active__c, Template_Definition__c 
                    FROM Property_Template__c 
                    WHERE Id = :templateId AND Is_Active__c = true 
                    LIMIT 1];
        } catch (Exception e) {
            throw new AuraHandledException('Error fetching template: ' + e.getMessage());
        }
    }
    
    @AuraEnabled(cacheable=true)
    public static List<pcrm__Property__c> getPropertyData() {
        try {
            return [SELECT Id, Name, pcrm__Property_Type__c, pcrm__Sub_Locality_Bayut_Dubizzle__c, 
                           pcrm__Sale_Price_max__c, pcrm__Rent_Price_max__c, pcrm__Bedrooms__c, 
                           pcrm__Bathrooms__c, pcrm__Size__c, pcrm__Description_English__c, 
                           pcrm__Title_English__c, pcrm__Unit_Number__c, pcrm__Completion_Status__c,
                           pcrm__Furnished__c, pcrm__Tower_Bayut_Dubizzle__c,
                           pcrm__Community_Propertyfinder__c, pcrm__Sub_Community_Propertyfinder__c,
                           pcrm__City_Propertyfinder__c, pcrm__City_Bayut_Dubizzle__c
                    FROM pcrm__Property__c 
                    ORDER BY Name];
        } catch (Exception e) {
            throw new AuraHandledException('Error fetching properties: ' + e.getMessage());
        }
    }
    
    @AuraEnabled(cacheable=true)
    public static pcrm__Property__c getPropertyById(String propertyId) {
        try {
            return [SELECT Id, Name, pcrm__Property_Type__c, pcrm__Sub_Locality_Bayut_Dubizzle__c, 
                           pcrm__Sale_Price_max__c, pcrm__Rent_Price_max__c, pcrm__Bedrooms__c, 
                           pcrm__Bathrooms__c, pcrm__Size__c, pcrm__Description_English__c, 
                           pcrm__Title_English__c, pcrm__Unit_Number__c, pcrm__Completion_Status__c,
                           pcrm__Furnished__c, pcrm__Tower_Bayut_Dubizzle__c,
                           pcrm__Community_Propertyfinder__c, pcrm__Sub_Community_Propertyfinder__c,
                           pcrm__City_Propertyfinder__c, pcrm__City_Bayut_Dubizzle__c
                    FROM pcrm__Property__c 
                    WHERE Id = :propertyId 
                    LIMIT 1];
        } catch (Exception e) {
            throw new AuraHandledException('Error fetching property: ' + e.getMessage());
        }
    }
    
    @AuraEnabled(cacheable=true)
    public static Map<String, Object> getMarketData() {
        try {
            // For now, return default market data since you might not have Market_Analytics__c
            Map<String, Object> result = new Map<String, Object>();
            
            // Default Dubai market data
            result.put('marketTrend', 'Rising');
            result.put('roiPotential', '8.5');
            result.put('avgPricePerSqft', '1200');
            result.put('marketDemand', 'High');
            result.put('investmentType', 'Buy-to-Rent');
            result.put('rentalYield', '6.2');
            result.put('investmentHighlights', 'Prime location with high rental demand and capital appreciation potential');
            result.put('locationAdvantages', 'Excellent connectivity, premium amenities, and strong infrastructure');
            List<String> contentModules = new List<String>{'Market Analysis', 'Investment Overview', 'Location Highlights'};
            result.put('contentModules', contentModules);
            result.put('additionalContent', 'Dubai real estate market shows strong growth potential with government initiatives and Expo 2020 legacy');
            
            return result;
        } catch (Exception e) {
            throw new AuraHandledException('Error fetching market data: ' + e.getMessage());
        }
    }
    
    @AuraEnabled
    public static Map<String, Object> generatePropertyPDF(String propertyData, String templateName, Boolean generatePDF) {
        try {
            // Parse property data
            Map<String, Object> propertyMap = (Map<String, Object>) JSON.deserializeUntyped(propertyData);
            
            // Call external Python API for PDF generation
            String apiEndpoint = 'http://160.187.166.67:8000/api/generate-pdf'; // Production PDF Generator API
            
            // Prepare request body
            Map<String, Object> requestBody = new Map<String, Object>();
            requestBody.put('property_data', propertyMap);
            requestBody.put('template_name', templateName);
            
            // Make HTTP callout to Python API
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint(apiEndpoint);
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/json');
            request.setBody(JSON.serialize(requestBody));
            
            HttpResponse response = http.send(request);
            
            if (response.getStatusCode() == 200) {
                Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                
                Map<String, Object> result = new Map<String, Object>();
                result.put('success', true);
                result.put('pdfUrl', responseMap.get('pdf_url'));
                result.put('message', 'PDF generated successfully');
                
                return result;
            } else {
                Map<String, Object> result = new Map<String, Object>();
                result.put('success', false);
                result.put('message', 'Failed to generate PDF: ' + response.getStatus());
                return result;
            }
            
        } catch (Exception e) {
            Map<String, Object> result = new Map<String, Object>();
            result.put('success', false);
            result.put('message', 'Error: ' + e.getMessage());
            return result;
        }
    }
    
    @AuraEnabled
    public static List<Property_Template__c> searchPropertyTemplates(String searchTerm) {
        try {
            String searchQuery = '%' + searchTerm + '%';
            return [SELECT Id, Name, Description__c, Preview_Image_URL__c, Tags__c, 
                           Is_Active__c, Template_Definition__c 
                    FROM Property_Template__c 
                    WHERE Is_Active__c = true 
                    AND (Name LIKE :searchQuery OR Tags__c LIKE :searchQuery)
                    ORDER BY Name];
        } catch (Exception e) {
            throw new AuraHandledException('Error searching templates: ' + e.getMessage());
        }
    }
} 