<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use App\Services\AiDataService;
use App\Traits\AiPromptTrait;
use App\Http\Controllers\Traits\HelperTrait;

class AiDataController extends Controller
{
    use AiPromptTrait, HelperTrait;

    protected $aiService;

    public function __construct(AiDataService $aiService)
    {
        $this->aiService = $aiService;
    }

    /**
     * Unified AI data generation method for all types of data
     */
    public function generateUnifiedAiData(Request $request)
    {
        $settingsName = '';
        try {
            $validator = Validator::make($request->all(), [
                'settings_name' => 'required|string|in:injury_classifications,notifiable_classifications,incident_risk_categories,training_data,injury_type_data,incident_report_questions,incident_risk_category_data,whs_report_settings,swms_hazard_risk_settings,swms_safety_planning_questions,swms_general_notes,swms_protection_tools',
                'count' => 'nullable|integer|min:1|max:20',
                'industry' => 'nullable|string|in:construction,manufacturing,mining,healthcare,retail,transport,agriculture,general',
                'setting_type' => 'nullable|string',
                'swms_type' => 'nullable|string|in:hazard,risk', // Specific for SWMS settings
                'include_descriptions' => 'nullable|boolean', // Control whether descriptions are included
                'parent_id' => 'nullable|integer|min:0' // For injury types with parent categories
            ]);

            if ($validator->fails()) {
                return $this->errorWithData($validator->errors(), $validator->errors()->first(), 422);
            }

            $settingsName = $request->input('settings_name');
            $count = $request->input('count', 10);
            $industry = $request->input('industry', 'construction');
            $settingType = $request->input('setting_type', 'construction');
            $includeDescriptions = $request->input('include_descriptions', true);
            $parentId = $request->input('parent_id', 0);

            $userTable = $this->getUserTable();
            $userContext = $this->aiService->getUserContext($userTable);
            $customerId = $userContext['customer_id'];
            $workspaceId = $userContext['workspace_id'];
            $swmsType = $request->input('swms_type', 'general'); // For SWMS hazard/risk filtering


            // Get system prompt and build user prompt based on settings_name
            $systemPrompt = $this->getSystemPromptBySettingsName($settingsName);
            $userPrompt = $this->buildUserPromptBySettingsName($settingsName, $count, $industry, $settingType, $swmsType, $includeDescriptions, $parentId);

            // Generate AI data
            $generatedContent = $this->aiService->generateAiData($systemPrompt, $userPrompt, $settingsName, $count);

            if (empty($generatedContent)) {
                return $this->error("Failed to generate {$settingsName} data", 500);
            }

            // Parse AI response based on settings_name
            $expectedStructure = $this->getExpectedStructureBySettingsName($settingsName);
            $parsedData = $this->aiService->parseAiResponse($generatedContent, $expectedStructure);

            if (!$parsedData) {
                return $this->error("Failed to parse AI response for {$settingsName}", 500);
            }

            // Store data based on settings_name
            $storedData = $this->storeDataBySettingsName($settingsName, $parsedData, $customerId, $workspaceId);

            return $this->success([
                'data' => $storedData,
                'count' => count($storedData),
                'settings_name' => $settingsName,
                'industry' => $industry,
                'setting_type' => $settingType,
                'swms_type' => $swmsType,
                'include_descriptions' => $includeDescriptions,
                'parent_id' => $parentId
            ], "AI {$settingsName} data generated successfully according to Australian standards");
        } catch (\Exception $e) {
            Log::error("AI unified data generation error for {$settingsName}", [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->error('An error occurred while generating AI data: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get system prompt based on settings_name
     */
    private function getSystemPromptBySettingsName($settingsName)
    {
        switch ($settingsName) {
            case 'injury_classifications':
                return $this->getInjuryClassificationSystemPrompt();
            case 'notifiable_classifications':
                return $this->getNotifiableClassificationSystemPrompt();
            case 'incident_risk_categories':
                return $this->getIncidentRiskCategorySystemPrompt();
            case 'training_data':
                return $this->getTrainingSystemPrompt();
            case 'injury_type_data':
                return $this->getInjuryTypeSystemPrompt();
            case 'incident_report_questions':
                return $this->getIncidentReportQuestionSystemPrompt();
            case 'incident_risk_category_data':
                return $this->getIncidentRiskCategorySystemPrompt();
            case 'whs_report_settings':
                return $this->getWhsReportSettingsSystemPrompt();
            case 'swms_hazard_risk_settings':
                return $this->getSwmsSettingsSystemPrompt();
            case 'swms_safety_planning_questions':
                return $this->getSwmsSafetyPlanningQuestionSystemPrompt();
            case 'swms_general_notes':
                return $this->getSwmsGeneralNoteSystemPrompt();
            case 'swms_protection_tools':
                return $this->getSwmsProtectionToolsSystemPrompt();
            default:
                throw new \Exception("Unknown settings name: {$settingsName}");
        }
    }

    /**
     * Build user prompt based on settings_name
     */
    private function buildUserPromptBySettingsName($settingsName, $count, $industry, $settingType, $swmsType, $includeDescriptions, $parentId)
    {
        switch ($settingsName) {
            case 'injury_classifications':
                return $this->buildInjuryClassificationPrompt($count, $industry, $includeDescriptions);
            case 'notifiable_classifications':
                return $this->buildNotifiableClassificationPrompt($count, $industry, $includeDescriptions);
            case 'incident_risk_categories':
                return $this->buildIncidentRiskCategoryPrompt($count, $industry, 'general', $includeDescriptions);
            case 'training_data':
                return $this->buildTrainingPrompt($count, $industry, $includeDescriptions);
            case 'injury_type_data':
                return $this->buildInjuryTypePrompt($count, $industry, $parentId, $includeDescriptions);
            case 'incident_report_questions':
                return $this->buildIncidentReportQuestionPrompt($count, $industry, $includeDescriptions);
            case 'incident_risk_category_data':
                return $this->buildIncidentRiskCategoryPrompt($count, $industry, 'general', $includeDescriptions);
            case 'whs_report_settings':
                return $this->buildWhsReportSettingsPrompt($count, $industry, $settingType, $includeDescriptions);
            case 'swms_hazard_risk_settings':
                return $this->buildSwmsSettingsPrompt($count, $industry, $settingType, $swmsType, $includeDescriptions);
            case 'swms_safety_planning_questions':
                return $this->buildSwmsSafetyPlanningQuestionPrompt($count, $industry, $settingType, $swmsType, $includeDescriptions);
            case 'swms_general_notes':
                return $this->buildSwmsGeneralNotePrompt($count, $industry, $settingType, $swmsType, $includeDescriptions);
            case 'swms_protection_tools':
                return $this->buildSwmsProtectionToolsPrompt($count, $industry, $settingType, $swmsType, $includeDescriptions);
            default:
                throw new \Exception("Unknown settings name: {$settingsName}");
        }
    }

    /**
     * Get expected structure based on settings_name
     */
    private function getExpectedStructureBySettingsName($settingsName)
    {
        switch ($settingsName) {
            case 'injury_classifications':
            case 'notifiable_classifications':
                return ['classifications' => true];
            case 'incident_risk_categories':
            case 'incident_risk_category_data':
                return ['risk_categories' => true];
            case 'training_data':
                return ['trainings' => true];
            case 'injury_type_data':
                return ['injury_types' => true];
            case 'incident_report_questions':
                return ['questions' => true];
            case 'whs_report_settings':
                return ['whs_items' => true];
            case 'swms_hazard_risk_settings':
                return ['hazard_risks' => true];
            case 'swms_safety_planning_questions':
                return ['safety_planning_questions' => true];
            case 'swms_general_notes':
                return ['general_notes' => true];
            case 'swms_protection_tools':
                return ['protection_tools' => true];
            default:
                throw new \Exception("Unknown settings name: {$settingsName}");
        }
    }

    /**
     * Store data based on settings_name
     */
    private function storeDataBySettingsName($settingsName, $parsedData, $customerId, $workspaceId)
    {
        switch ($settingsName) {
            case 'injury_classifications':
                return $this->aiService->storeInjuryClassifications($parsedData, $customerId, $workspaceId);
            case 'notifiable_classifications':
                return $this->aiService->storeNotifiableClassifications($parsedData, $customerId, $workspaceId);
            case 'incident_risk_categories':
            case 'incident_risk_category_data':
                return $this->aiService->storeIncidentRiskCategories($parsedData, $customerId, $workspaceId);
            case 'training_data':
                return $this->aiService->storeTrainings($parsedData, $customerId, $workspaceId);
            case 'injury_type_data':
                return $this->aiService->storeInjuryTypes($parsedData, $customerId, $workspaceId);
            case 'incident_report_questions':
                return $this->aiService->storeIncidentReportQuestions($parsedData, $customerId, $workspaceId);
            case 'whs_report_settings':
                return $this->aiService->storeWhsReportSettings($parsedData, $customerId, $workspaceId);
            case 'swms_hazard_risk_settings':
                return $this->aiService->storeSwmsSettings($parsedData, $customerId, $workspaceId);
            case 'swms_safety_planning_questions':
                return $this->aiService->storeSwmsSafetyPlanningQuestions($parsedData, $customerId, $workspaceId);
            case 'swms_general_notes':
                return $this->aiService->storeSwmsGeneralNotes($parsedData, $customerId, $workspaceId);
            case 'swms_protection_tools':
                return $this->aiService->storeSwmsProtectionTools($parsedData, $customerId, $workspaceId);
            default:
                throw new \Exception("Unknown settings name: {$settingsName}");
        }
    }

    /**
     * Test Australian standards validation
     */
    public function testAustralianStandardsValidation(Request $request)
    {
        try {
            $testData = [
                'company_name' => 'Test Company Pty Ltd',
                'address' => '123 Test Street, Sydney NSW 2000',
                'email' => 'test@company.com.au',
                'document_number' => 'WHS2024001',
                'issue_date' => '2024-01-15',
                'revision_date' => '2024-02-15'
            ];

            $results = [
                'company_name' => $this->checkCriticalAustralianTerminology($testData['company_name'], 'company_name'),
                'address' => $this->isReasonableAustralianAddress($testData['address']),
                'email' => $this->isReasonableEmail($testData['email']),
                'document_number' => $this->isValidDocumentNumber($testData['document_number']),
                'issue_date' => $this->isValidIssueDate($testData['issue_date']),
                'revision_date' => $this->isValidRevisionDate($testData['revision_date'], $testData['issue_date'])
            ];

            return $this->success($results, 'Australian standards validation test completed');
        } catch (\Exception $e) {
            Log::error('Australian standards validation test error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->error('An error occurred during validation test: ' . $e->getMessage(), 500);
        }
    }
    /**
     * Generate AI data for report forms based on report type and step
     */



    /**
     * Get system prompt for report generation
     */


    /**
     * Build prompt for report generation
     */
    private function buildReportPrompt($requestData)
    {
        $reportType = $requestData['report_type'];
        $step = $requestData['step'];

        return "Generate realistic data for a {$reportType} report at step {$step} in Australia.

CRITICAL REQUIREMENTS:
- Generate appropriate values for each field based on the field type
- Use realistic Australian workplace safety data
- Follow Australian WHS terminology and compliance language
- Ensure all data is contextually appropriate for {$reportType} reports
- Use current Australian workplace safety best practices
- Generate data that meets Australian compliance requirements
- Use current (search for the current date) or future dates for issue and revision dates
- Ensure revision date is after issue date
- The revision date must be after or equal to the issue date
- The issue date must be after or equal to the current date (search for the current date)
Return the data in this exact JSON format:
{
    \"document_number\": \"YYYY-XXXX\",
    \"document_title\": \"Appropriate Document Title\",
    \"issue_date\": \"YYYY-MM-DD\",
    \"revision_date\": \"YYYY-MM-DD\"
}

Only return valid JSON, no additional text or explanations. Ensure all data is contextually appropriate for Australian {$reportType} workplaces and follows Australian WHS standards.";
    }


    /**
     * Parse report response from AI
     */

    public function generateReportData(Request $request)
    {
        try {
            // Validate the request
            $validator = Validator::make($request->all(), [
                'report_type' => 'required|string|in:whs_report,swms_report,inspection_report,incident_report,whsq_report',
                'step' => 'required|integer|min:1|max:10',
                'form_fields' => 'required|array',
                'form_fields.*.name' => 'required|string',
                'form_fields.*.type' => 'required|string|in:text,number,date,email,textarea,time',
                'form_fields.*.label' => 'required|string',
                'form_fields.*.required' => 'boolean',
                'form_fields.*.placeholder' => 'nullable|string'
            ]);

            if ($validator->fails()) {
                return $this->errorWithData($validator->errors(), $validator->errors()->first(), 422);
            }

            // Prepare the prompt for AI based on report type and step
            $prompt = $this->buildGenericPrompt($request->all());

            // Call AI service
            $generatedContent = $this->aiService->generateAiData(
                $this->getSystemPrompt($request->report_type, $request->step),
                $prompt,
                'report_data'
            );

            // Parse the AI response
            $parsedData = $this->parseAiResponse($generatedContent, $request->form_fields, $request->report_type);

            if (!$parsedData) {
                return $this->error('Failed to parse AI response', 500);
            }

            return $this->success($parsedData, 'AI data generated successfully');

        } catch (\Exception $e) {
            Log::error('AI data generation error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->error('An error occurred while generating AI data: ' . $e->getMessage(), 500);
        }
    }

    public function generateInjuryTypes(Request $request)
    {
        try {
            // Validate the request
            $validator = Validator::make($request->all(), [
                'count' => 'nullable|integer|min:1|max:20',
                'industry' => 'nullable|string|in:construction,manufacturing,mining,healthcare,retail,transport,agriculture,general',
                'parent_id' => 'nullable|integer|min:0'
            ]);

            if ($validator->fails()) {
                return $this->errorWithData($validator->errors(), $validator->errors()->first(), 422);
            }

            $count = $request->input('count', 10);
            $industry = $request->input('industry', 'general');
            $parentId = $request->input('parent_id', 0);

            // Call AI service
            $generatedContent = $this->aiService->generateAiData(
                $this->getInjuryTypeSystemPrompt(),
                $this->buildInjuryTypePrompt($count, $industry, $parentId),
                'injury_types'
            );

            // Parse the AI response
            $parsedData = $this->aiService->parseAiResponse($generatedContent, ['injury_types' => true]);

            if (!$parsedData) {
                return $this->error('Failed to parse AI response for injury types', 500);
            }

            // Get user context and store data
            $userContext = $this->aiService->getUserContext($this->getUserTable());
            $storedInjuryTypes = $this->aiService->storeInjuryTypes(
                $parsedData, 
                $userContext['customer_id'], 
                $userContext['workspace_id']
            );

            return $this->success([
                'generated' => $parsedData,
                'stored' => $storedInjuryTypes
            ], 'Injury types generated and stored successfully');

        } catch (\Exception $e) {
            Log::error('AI injury type generation error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->error('An error occurred while generating injury types: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Generate incident risk categories using AI according to Australian WHS legislation
     */


    /**
     * Get system prompt based on report type and step
     */
    private function getSystemPrompt($reportType, $step)
    {
        $basePrompt = config('ai.prompts.default.system');
        
        $reportTypeContext = config('ai.report_type_context.' . $reportType);
        $stepDescriptions = config('ai.step_descriptions.' . $reportType);
        
        $reportTypeName = config('ai.supported_report_types.' . $reportType) ?? 'Workplace Safety';
        $stepDescription = $stepDescriptions[$step] ?? '';
        
        $contextInfo = '';
        if ($reportTypeContext) {
            $contextInfo = " Context: {$reportTypeContext['description']} This report typically includes {$reportTypeContext['typical_fields']} and is used in {$reportTypeContext['industry_context']}.";
        }
        
        return "{$basePrompt} You are generating data for a {$reportTypeName} report.{$contextInfo} {$stepDescription}";
    }

    /**
     * Build generic prompt for any report type and step
     */
    private function buildGenericPrompt($requestData)
    {
        $reportType = $requestData['report_type'];
        $step = $requestData['step'];
        $formFields = $requestData['form_fields'];

        $fieldDescriptions = [];
        foreach ($formFields as $field) {
            $required = $field['required'] ? ' (required)' : ' (optional)';
            $placeholder = $field['placeholder'] ? " - Suggested: {$field['placeholder']}" : '';
            $fieldDescriptions[] = "- {$field['name']}: {$field['label']} - Type: {$field['type']}{$required}{$placeholder}";
        }

        $fieldsList = implode("\n", $fieldDescriptions);

        // Get report type specific context for better prompt generation
        $reportTypeContext = config('ai.report_type_context.' . $reportType);
        $contextInfo = '';
        if ($reportTypeContext) {
            $contextInfo = " This {$reportTypeContext['description']}";
        }

        return "Generate realistic, professional data for a {$reportType} report Step {$step} form.{$contextInfo}

CRITICAL AUSTRALIAN STANDARDS REQUIREMENTS:
- ALL data MUST comply with Australian WHS legislation and Australian Standards (AS)
- ALL dates MUST be in Australian format ( YYYY-MM-DD)
- Issue dates MUST be current dates (today) or future dates - NEVER use past dates
- Revision dates MUST occur AFTER the issue date (typically 1-30 days after issue date)
- Use current Australian workplace safety terminology and compliance language
- ALL measurements MUST use Australian metric system (metres, kilograms, etc.)
- ALL currency values MUST be in Australian Dollars (AUD)
- ALL addresses and locations MUST be Australian locations
- ALL company names and personnel MUST use realistic Australian business names
- ALL regulatory references MUST be to Australian WHS legislation and Australian Standards

The form contains the following fields:

{$fieldsList}

SPECIFIC DATE HANDLING REQUIREMENTS:
- For 'issue_date' fields: Use current Australian date (today) or future date, NEVER past dates
- For 'revision_date' fields: Use date that is AFTER the issue date (typically 1-30 days later)
- For incident dates: Use recent dates (within last 30 days) or current date
- All dates must be in YYYY-MM-DD format for consistency

Requirements:
- Generate appropriate data for each field based on its type, label, and the specific context of a {$reportType} report at step {$step}
- Text fields should contain realistic, relevant content appropriate for Australian workplace safety and compliance
- Number fields should contain appropriate numeric values (IDs, quantities, measurements in Australian metric system, etc.)
- Date fields should contain logical dates following the specific date handling requirements above
- Email fields should contain realistic Australian business email addresses (preferably .com.au domains)
- Textarea fields should contain detailed, relevant content with proper Australian workplace safety terminology
- Time fields should contain appropriate time values in 24-hour format (Australian timezone)
- All data should be contextually appropriate for a {$reportType} report at step {$step}
- Data should be realistic, professional, and reflect actual Australian workplace safety practices
- Use appropriate Australian industry terminology and compliance language
- Ensure all required fields have meaningful values
- Generate data that would be typical for Australian construction or workplace safety context
- All company names should be realistic Australian business names (e.g., 'Brisbane Construction Pty Ltd', 'Sydney Safety Solutions Ltd')
- All addresses should be realistic Australian addresses (e.g., '123 George Street, Sydney NSW 2000', '456 Collins Street, Melbourne VIC 3000')

Return the data in this exact JSON format where each field name maps to its generated value:
{
    \"field_name\": \"generated_value\",
    ...
}

Only return valid JSON, no additional text or explanations. Ensure all required fields have values and the data is contextually appropriate for the specified report type and step while strictly following Australian standards.";
    }

    /**
     * Parse the AI response and validate the data
     */
    private function parseAiResponse($content, $formFields, $reportType = 'whs_report')
    {
        try {
            // Clean the content to extract only JSON
            $jsonStart = strpos($content, '{');
            $jsonEnd = strrpos($content, '}');
            
            if ($jsonStart === false || $jsonEnd === false) {
                return null;
            }
            
            $jsonContent = substr($content, $jsonStart, $jsonEnd - $jsonStart + 1);
            $data = json_decode($jsonContent, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                return null;
            }

            // Validate that all required fields have values
            foreach ($formFields as $field) {
                if ($field['required'] && !isset($data[$field['name']])) {
                    return null;
                }
            }

            // Validate data types
            foreach ($formFields as $field) {
                if (isset($data[$field['name']])) {
                    if (!$this->validateFieldType($data[$field['name']], $field['type'])) {
                        return null;
                    }
                }
            }

            // Validate and correct dates according to Australian standards
            $data = $this->validateAndCorrectDates($data, $formFields);

            // Validate Australian standards compliance
            $australianStandardsIssues = $this->validateAustralianStandards($data, $formFields);
            if (!empty($australianStandardsIssues)) {
                Log::warning('Australian standards compliance issues detected', [
                    'issues' => $australianStandardsIssues,
                    'data' => $data
                ]);
            }

            return $data;

        } catch (\Exception $e) {
            Log::error('Failed to parse AI response', [
                'content' => $content,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * Validate field data type
     */
    private function validateFieldType($value, $type)
    {
        switch ($type) {
            case 'text':
            case 'textarea':
                return is_string($value) && strlen($value) > 0;
            
            case 'number':
                return is_numeric($value);
            
            case 'date':
                return $this->isValidDate($value);
            
            case 'email':
                return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
            
            case 'time':
                return $this->isValidTime($value);
            
            default:
                return true;
        }
    }

    /**
     * Check if value is a valid date
     */
    private function isValidDate($value)
    {
        if (!is_string($value)) {
            return false;
        }
        
        $date = \DateTime::createFromFormat('Y-m-d', $value);
        return $date && $date->format('Y-m-d') === $value;
    }

    /**
     * Check if value is a valid time
     */
    private function isValidTime($value)
    {
        if (!is_string($value)) {
            return false;
        }
        
        $time = \DateTime::createFromFormat('H:i', $value);
        return $time && $time->format('H:i') === $value;
    }

    /**
     * Validate and correct dates according to Australian standards
     */
    private function validateAndCorrectDates($data, $formFields)
    {
        $issueDate = null;
        $revisionDate = null;
        
        // First pass: find issue and revision dates
        foreach ($formFields as $field) {
            if ($field['type'] === 'date') {
                if (stripos($field['name'], 'issue') !== false || stripos($field['label'], 'issue') !== false) {
                    $issueDate = $data[$field['name']] ?? null;
                }
                if (stripos($field['name'], 'revision') !== false || stripos($field['label'], 'revision') !== false) {
                    $revisionDate = $data[$field['name']] ?? null;
                }
            }
        }
        
        // Second pass: correct dates if needed
        foreach ($formFields as $field) {
            if ($field['type'] === 'date' && isset($data[$field['name']])) {
                $fieldName = $field['name'];
                $currentDate = $data[$fieldName];
                
                // Check if this is an issue date field
                if (stripos($fieldName, 'issue') !== false || stripos($field['label'], 'issue') !== false) {
                    $data[$fieldName] = $this->correctIssueDate($currentDate);
                    $issueDate = $data[$fieldName];
                }
                
                // Check if this is a revision date field
                if (stripos($fieldName, 'revision') !== false || stripos($field['label'], 'revision') !== false) {
                    $data[$fieldName] = $this->correctRevisionDate($currentDate, $issueDate);
                    $revisionDate = $data[$fieldName];
                }
                
                // For other date fields, ensure they're not too old
                if (stripos($fieldName, 'issue') === false && stripos($field['label'], 'issue') === false &&
                    stripos($fieldName, 'revision') === false && stripos($field['label'], 'revision') === false) {
                    $data[$fieldName] = $this->correctGeneralDate($currentDate);
                }
            }
        }
        
        return $data;
    }

    private function correctIssueDate($date)
    {
        if (!$this->isValidDate($date)) {
            return date('Y-m-d'); // Use today's date if invalid
        }
        
        $issueDate = new \DateTime($date);
        $today = new \DateTime();
        
        // If issue date is in the past, use today's date
        if ($issueDate < $today) {
            return $today->format('Y-m-d');
        }
        
        return $date;
    }

    private function correctRevisionDate($date, $issueDate)
    {
        if (!$this->isValidDate($date)) {
            // Generate a revision date 1-30 days after issue date
            if ($issueDate) {
                $issueDateTime = new \DateTime($issueDate);
                $revisionDateTime = clone $issueDateTime;
                $revisionDateTime->add(new \DateInterval('P' . rand(1, 30) . 'D'));
                return $revisionDateTime->format('Y-m-d');
            }
            return date('Y-m-d', strtotime('+7 days')); // Default to 7 days from today
        }
        
        if ($issueDate) {
            $revisionDateTime = new \DateTime($date);
            $issueDateTime = new \DateTime($issueDate);
            
            // If revision date is before or equal to issue date, adjust it
            if ($revisionDateTime <= $issueDateTime) {
                $revisionDateTime = clone $issueDateTime;
                $revisionDateTime->add(new \DateInterval('P' . rand(1, 30) . 'D'));
                return $revisionDateTime->format('Y-m-d');
            }
        }
        
        return $date;
    }

    private function correctGeneralDate($date)
    {
        if (!$this->isValidDate($date)) {
            return date('Y-m-d'); // Use today's date if invalid
        }
        
        $dateTime = new \DateTime($date);
        $today = new \DateTime();
        $minDate = new \DateTime('2024-01-01'); // Minimum date from config
        
        // If date is too old, use a recent date
        if ($dateTime < $minDate) {
            $recentDate = clone $today;
            $recentDate->sub(new \DateInterval('P' . rand(1, 90) . 'D')); // 1-90 days ago
            return $recentDate->format('Y-m-d');
        }
        
        return $date;
    }

    /**
     * Validate Australian standards compliance - Practical approach
     */
    private function validateAustralianStandards($data, $formFields)
    {
        $issues = [];
        
        foreach ($formFields as $field) {
            if (isset($data[$field['name']])) {
                $value = $data[$field['name']];
                
                // Check for critical non-Australian terminology (only the most important ones)
                if ($field['type'] === 'text' || $field['type'] === 'textarea') {
                    $issues = array_merge($issues, $this->checkCriticalAustralianTerminology($value, $field['name']));
                }
                
                // Check for Australian addresses (more flexible approach)
                if (stripos($field['name'], 'address') !== false || stripos($field['label'], 'address') !== false) {
                    if (!$this->isReasonableAustralianAddress($value)) {
                        $issues[] = "Field '{$field['name']}' should contain an Australian address format";
                    }
                }
                
                // Check for company names (more flexible approach)
                if (stripos($field['name'], 'company') !== false || stripos($field['label'], 'company') !== false) {
                    if (!$this->isReasonableCompanyName($value)) {
                        $issues[] = "Field '{$field['name']}' should contain a realistic company name";
                    }
                }
                
                // Check for email domains (more flexible approach)
                if ($field['type'] === 'email') {
                    if (!$this->isReasonableEmail($value)) {
                        $issues[] = "Field '{$field['name']}' should contain a valid email address";
                    }
                }
            }
        }
        
        return $issues;
    }

    /**
     * Check for critical non-Australian terminology (only the most important ones)
     */
    private function checkCriticalAustralianTerminology($text, $fieldName)
    {
        $issues = [];
        $lowerText = strtolower($text);
        
        // Only check for the most critical non-Australian terms that would be problematic
        $criticalNonAustralianTerms = [
            'osha' => 'Should use Australian WHS instead of OSHA',
            'federal' => 'Consider using Commonwealth or Australian instead of Federal for clarity'
        ];
        
        foreach ($criticalNonAustralianTerms as $term => $message) {
            if (strpos($lowerText, $term) !== false) {
                $issues[] = "Field '{$fieldName}': {$message}";
            }
        }
        
        // Check for Australian standards references (encourage but don't require)
        $australianStandards = [
            'as ', 'as/nzs ', 'whs ', 'work health and safety', 'safework australia',
            'comcare', 'nsw workcover', 'vic worksafe', 'qld workplace health and safety'
        ];
        
        $hasAustralianReference = false;
        foreach ($australianStandards as $standard) {
            if (strpos($lowerText, $standard) !== false) {
                $hasAustralianReference = true;
                break;
            }
        }
        
        // Only suggest Australian standards for fields that explicitly mention standards/compliance
        if (!$hasAustralianReference && (stripos($fieldName, 'standard') !== false || stripos($fieldName, 'compliance') !== false)) {
            $issues[] = "Field '{$fieldName}': Consider referencing Australian standards or WHS legislation for better compliance";
        }
        
        return $issues;
    }

    /**
     * Check if value contains a reasonable Australian address format (more flexible)
     */
    private function isReasonableAustralianAddress($value)
    {
        if (empty($value) || strlen($value) < 10) {
            return false; // Too short to be a valid address
        }
        
        $lowerValue = strtolower($value);
        
        // Check for Australian state abbreviations (at least one)
        $australianStates = ['nsw', 'vic', 'qld', 'wa', 'sa', 'tas', 'nt', 'act'];
        $hasState = false;
        foreach ($australianStates as $state) {
            if (strpos($lowerValue, $state) !== false) {
                $hasState = true;
                break;
            }
        }
        
        // Check for Australian postal codes (4 digits) - optional but encouraged
        $hasPostalCode = preg_match('/\b\d{4}\b/', $value);
        
        // Check for common street types - optional but encouraged
        $streetTypes = ['street', 'road', 'avenue', 'drive', 'court', 'place', 'lane', 'crescent', 'way', 'close'];
        $hasStreetType = false;
        foreach ($streetTypes as $type) {
            if (strpos($lowerValue, $type) !== false) {
                $hasStreetType = true;
                break;
            }
        }
        
        // More flexible validation: require state + either postal code OR street type
        return $hasState && ($hasPostalCode || $hasStreetType);
    }

}
