/**
 * Descomplicar® Crescimento Digital
 * https://descomplicar.pt
 */

<?php

/**
 * Integration Test: Invoice Sync Workflow
 * 
 * Tests the complete invoice synchronization workflow between Perfex CRM and Moloni
 * Verifies end-to-end invoice data synchronization functionality
 * 
 * @package    DeskMoloni
 * @subpackage Tests\Integration
 * @version    3.0.0
 * @author     Descomplicar®
 */

define('BASEPATH', true);
define('ENVIRONMENT', 'testing');

echo "\n" . str_repeat("=", 80) . "\n";
echo "INVOICE SYNC WORKFLOW INTEGRATION TESTS\n";
echo "Testing complete invoice synchronization between Perfex CRM and Moloni\n";
echo str_repeat("=", 80) . "\n\n";

$test_results = [];
$start_time = microtime(true);

// Test 1: Core Invoice Components
echo "1. 🧪 Testing Core Invoice Components...\n";

$invoice_components = [
    'invoice_sync_service' => __DIR__ . '/../../libraries/InvoiceSyncService.php',
    'moloni_api_client' => __DIR__ . '/../../libraries/MoloniApiClient.php',
    'invoice_model' => __DIR__ . '/../../models/Desk_moloni_invoice_model.php',
    'sync_queue_model' => __DIR__ . '/../../models/Desk_moloni_sync_queue_model.php',
    'sync_log_model' => __DIR__ . '/../../models/Desk_moloni_sync_log_model.php',
    'mapping_model' => __DIR__ . '/../../models/Desk_moloni_mapping_model.php'
];

$components_available = 0;

foreach ($invoice_components as $component => $path) {
    if (file_exists($path)) {
        echo "   ✅ {$component} available\n";
        $components_available++;
    } else {
        echo "   ❌ {$component} missing at {$path}\n";
    }
}

$test_results['invoice_components'] = ($components_available >= 4);

// Test 2: Invoice Data Mapping
echo "\n2. 🧪 Testing Invoice Data Mapping...\n";

$invoice_mapping = [
    'header_mapping' => 'Invoice header data mapping',
    'line_items_mapping' => 'Invoice line items mapping',
    'tax_mapping' => 'Tax calculation mapping',
    'payment_terms_mapping' => 'Payment terms mapping',
    'status_mapping' => 'Invoice status mapping'
];

$mapping_score = 0;

if (file_exists($invoice_components['mapping_model'])) {
    $content = file_get_contents($invoice_components['mapping_model']);
    
    foreach ($invoice_mapping as $feature => $description) {
        $patterns = [
            'header_mapping' => 'invoice.*header|header.*invoice',
            'line_items_mapping' => 'line.*item|item.*line|invoice.*item',
            'tax_mapping' => 'tax.*map|vat.*map|iva.*map',
            'payment_terms_mapping' => 'payment.*term|due.*date',
            'status_mapping' => 'status.*map|invoice.*status'
        ];
        
        if (isset($patterns[$feature]) && preg_match("/{$patterns[$feature]}/i", $content)) {
            echo "   ✅ {$description} found\n";
            $mapping_score++;
        } else {
            echo "   ❌ {$description} missing\n";
        }
    }
} else {
    echo "   ❌ Cannot test invoice mapping - mapping model missing\n";
}

$test_results['invoice_mapping'] = ($mapping_score >= 3);

// Test 3: Invoice Sync Directions
echo "\n3. 🧪 Testing Invoice Sync Directions...\n";

$sync_directions = [
    'perfex_to_moloni' => 'Perfex CRM → Moloni invoice sync',
    'moloni_to_perfex' => 'Moloni → Perfex CRM invoice sync',
    'status_sync' => 'Invoice status synchronization',
    'payment_sync' => 'Payment information sync',
    'partial_sync' => 'Partial invoice updates'
];

$direction_score = 0;

if (file_exists($invoice_components['invoice_sync_service'])) {
    $content = file_get_contents($invoice_components['invoice_sync_service']);
    
    foreach ($sync_directions as $direction => $description) {
        $patterns = [
            'perfex_to_moloni' => 'push.*invoice|export.*invoice|create.*moloni',
            'moloni_to_perfex' => 'pull.*invoice|import.*invoice|fetch.*moloni',
            'status_sync' => 'sync.*status|status.*update',
            'payment_sync' => 'payment.*sync|sync.*payment',
            'partial_sync' => 'partial.*update|incremental.*sync'
        ];
        
        if (isset($patterns[$direction]) && preg_match("/{$patterns[$direction]}/i", $content)) {
            echo "   ✅ {$description} found\n";
            $direction_score++;
        } else {
            echo "   ❌ {$description} missing\n";
        }
    }
} else {
    echo "   ❌ Cannot test sync directions - InvoiceSyncService missing\n";
}

$test_results['sync_directions'] = ($direction_score >= 3);

// Test 4: Invoice Validation & Business Rules
echo "\n4. 🧪 Testing Invoice Validation & Business Rules...\n";

$validation_rules = [
    'invoice_data_validation' => 'Invoice data validation',
    'line_item_validation' => 'Line item validation',
    'tax_calculation_validation' => 'Tax calculation validation',
    'totals_validation' => 'Invoice totals validation',
    'business_rules_validation' => 'Business rules validation'
];

$validation_score = 0;

if (file_exists($invoice_components['invoice_sync_service'])) {
    $content = file_get_contents($invoice_components['invoice_sync_service']);
    
    foreach ($validation_rules as $rule => $description) {
        $patterns = [
            'invoice_data_validation' => 'validate.*invoice|invoice.*validation',
            'line_item_validation' => 'validate.*item|item.*validation',
            'tax_calculation_validation' => 'validate.*tax|tax.*calculation',
            'totals_validation' => 'validate.*total|total.*validation',
            'business_rules_validation' => 'business.*rule|rule.*validation'
        ];
        
        if (isset($patterns[$rule]) && preg_match("/{$patterns[$rule]}/i", $content)) {
            echo "   ✅ {$description} found\n";
            $validation_score++;
        } else {
            echo "   ❌ {$description} missing\n";
        }
    }
} else {
    echo "   ❌ Cannot test validation - InvoiceSyncService missing\n";
}

$test_results['validation_rules'] = ($validation_score >= 3);

// Test 5: PDF Generation & Document Handling
echo "\n5. 🧪 Testing PDF Generation & Document Handling...\n";

$document_features = [
    'pdf_generation' => 'PDF document generation',
    'pdf_download' => 'PDF download capability',
    'document_storage' => 'Document storage handling',
    'template_management' => 'Invoice template management',
    'multi_language_support' => 'Multi-language document support'
];

$document_score = 0;

$all_files = array_filter($invoice_components, 'file_exists');
$combined_content = '';

foreach ($all_files as $file) {
    $combined_content .= file_get_contents($file);
}

if (!empty($combined_content)) {
    foreach ($document_features as $feature => $description) {
        $patterns = [
            'pdf_generation' => 'pdf.*generate|generate.*pdf|tcpdf|fpdf',
            'pdf_download' => 'download.*pdf|pdf.*download',
            'document_storage' => 'document.*storage|store.*document',
            'template_management' => 'template|layout.*invoice',
            'multi_language_support' => 'language|locale|translation'
        ];
        
        if (isset($patterns[$feature]) && preg_match("/{$patterns[$feature]}/i", $combined_content)) {
            echo "   ✅ {$description} found\n";
            $document_score++;
        } else {
            echo "   ❌ {$description} missing\n";
        }
    }
} else {
    echo "   ❌ Cannot test document features - no invoice files available\n";
}

$test_results['document_handling'] = ($document_score >= 2);

// Test 6: Tax & Financial Calculations
echo "\n6. 🧪 Testing Tax & Financial Calculations...\n";

$tax_features = [
    'vat_calculation' => 'VAT/IVA calculation',
    'tax_exemption_handling' => 'Tax exemption handling',
    'multi_tax_rate_support' => 'Multiple tax rate support',
    'discount_calculation' => 'Discount calculation',
    'currency_conversion' => 'Currency conversion support'
];

$tax_score = 0;

if (!empty($combined_content)) {
    foreach ($tax_features as $feature => $description) {
        $patterns = [
            'vat_calculation' => 'vat|iva|tax.*rate|calculate.*tax',
            'tax_exemption_handling' => 'exempt|exemption|tax.*free',
            'multi_tax_rate_support' => 'tax.*rate|multiple.*tax',
            'discount_calculation' => 'discount|desconto|calculate.*discount',
            'currency_conversion' => 'currency|exchange.*rate|convert.*currency'
        ];
        
        if (isset($patterns[$feature]) && preg_match("/{$patterns[$feature]}/i", $combined_content)) {
            echo "   ✅ {$description} found\n";
            $tax_score++;
        } else {
            echo "   ❌ {$description} missing\n";
        }
    }
} else {
    echo "   ❌ Cannot test tax features - no invoice files available\n";
}

$test_results['tax_calculations'] = ($tax_score >= 3);

// Test 7: Queue & Batch Processing
echo "\n7. 🧪 Testing Queue & Batch Processing...\n";

$queue_features = [
    'invoice_queue_processing' => 'Invoice queue processing',
    'bulk_invoice_sync' => 'Bulk invoice synchronization',
    'priority_processing' => 'Priority-based processing',
    'failed_invoice_retry' => 'Failed invoice retry mechanism',
    'queue_status_tracking' => 'Queue status tracking'
];

$queue_score = 0;

if (file_exists($invoice_components['sync_queue_model'])) {
    $content = file_get_contents($invoice_components['sync_queue_model']);
    
    foreach ($queue_features as $feature => $description) {
        $patterns = [
            'invoice_queue_processing' => 'invoice.*queue|queue.*invoice',
            'bulk_invoice_sync' => 'bulk.*invoice|batch.*invoice',
            'priority_processing' => 'priority|high.*priority',
            'failed_invoice_retry' => 'retry|failed.*retry|attempt',
            'queue_status_tracking' => 'status|progress|track'
        ];
        
        if (isset($patterns[$feature]) && preg_match("/{$patterns[$feature]}/i", $content)) {
            echo "   ✅ {$description} found\n";
            $queue_score++;
        } else {
            echo "   ❌ {$description} missing\n";
        }
    }
} else {
    echo "   ❌ Cannot test queue features - sync queue model missing\n";
}

$test_results['queue_processing'] = ($queue_score >= 3);

// Test 8: Error Handling & Data Integrity
echo "\n8. 🧪 Testing Error Handling & Data Integrity...\n";

$error_handling = [
    'api_error_handling' => 'API communication errors',
    'data_validation_errors' => 'Data validation error handling',
    'transaction_rollback' => 'Transaction rollback capability',
    'duplicate_prevention' => 'Duplicate invoice prevention',
    'data_integrity_checks' => 'Data integrity validation'
];

$error_score = 0;

if (!empty($combined_content)) {
    foreach ($error_handling as $feature => $description) {
        $patterns = [
            'api_error_handling' => 'api.*error|http.*error|moloni.*error',
            'data_validation_errors' => 'validation.*error|data.*error',
            'transaction_rollback' => 'rollback|transaction.*rollback|db.*rollback',
            'duplicate_prevention' => 'duplicate|unique|already.*exists',
            'data_integrity_checks' => 'integrity|validate.*data|check.*data'
        ];
        
        if (isset($patterns[$feature]) && preg_match("/{$patterns[$feature]}/i", $combined_content)) {
            echo "   ✅ {$description} found\n";
            $error_score++;
        } else {
            echo "   ❌ {$description} missing\n";
        }
    }
} else {
    echo "   ❌ Cannot test error handling - no invoice files available\n";
}

$test_results['error_handling'] = ($error_score >= 3);

// Generate Final Report
$execution_time = microtime(true) - $start_time;

echo "\n" . str_repeat("=", 80) . "\n";
echo "INVOICE SYNC WORKFLOW INTEGRATION TEST REPORT\n";
echo str_repeat("=", 80) . "\n";

$passed_tests = array_filter($test_results, function($result) {
    return $result === true;
});

$failed_tests = array_filter($test_results, function($result) {
    return $result === false;
});

echo "Execution Time: " . number_format($execution_time, 2) . "s\n";
echo "Tests Passed: " . count($passed_tests) . "\n";
echo "Tests Failed: " . count($failed_tests) . "\n";

if (count($failed_tests) > 0) {
    echo "\n🔴 INVOICE SYNC INTEGRATION TESTS FAILING\n";
    echo "Invoice synchronization workflow needs implementation\n";
    
    echo "\nFailed Integration Areas:\n";
    foreach ($test_results as $test => $result) {
        if ($result === false) {
            echo "   ❌ " . ucwords(str_replace('_', ' ', $test)) . "\n";
        }
    }
} else {
    echo "\n🟢 ALL INVOICE SYNC INTEGRATION TESTS PASSING\n";
    echo "Invoice synchronization workflow is complete and functional\n";
}

echo "\n📋 INVOICE SYNC WORKFLOW REQUIREMENTS:\n";
echo "   1. Implement InvoiceSyncService with complete invoice mapping\n";
echo "   2. Support bidirectional invoice synchronization\n";
echo "   3. Implement robust tax calculation and validation\n";
echo "   4. Add PDF generation and document handling\n";
echo "   5. Implement error handling and data integrity checks\n";
echo "   6. Add queue-based batch processing\n";
echo "   7. Support multi-currency and tax exemptions\n";
echo "   8. Implement duplicate prevention mechanisms\n";

echo "\n🎯 INVOICE SYNC SUCCESS CRITERIA:\n";
echo "   - Complete invoice data synchronization\n";
echo "   - Accurate tax calculations\n";
echo "   - PDF generation capability\n";
echo "   - Robust error handling\n";
echo "   - Data integrity validation\n";
echo "   - Queue-based processing\n";
echo "   - Multi-currency support\n";

echo "\n🔄 INVOICE SYNC WORKFLOW STEPS:\n";
echo "   1. Detection → Identify invoices needing synchronization\n";
echo "   2. Validation → Validate invoice data and business rules\n";
echo "   3. Mapping → Map invoice fields between systems\n";
echo "   4. Calculation → Calculate taxes, totals, and discounts\n";
echo "   5. Queue → Add invoice sync tasks to queue\n";
echo "   6. Processing → Execute synchronization operations\n";
echo "   7. Generation → Generate PDF documents if needed\n";
echo "   8. Verification → Verify sync completion and data integrity\n";
echo "   9. Logging → Record sync events and audit trail\n";

echo "\n📄 INVOICE DATA SYNCHRONIZATION:\n";
echo "   • Header: Client, date, due date, currency, status\n";
echo "   • Line Items: Products/services, quantities, prices\n";
echo "   • Taxes: VAT/IVA rates, exemptions, calculations\n";
echo "   • Totals: Subtotal, tax total, discount, final total\n";
echo "   • Payments: Payment terms, status, transactions\n";
echo "   • Documents: PDF generation, storage, download\n";

echo "\n💰 FINANCIAL COMPLIANCE:\n";
echo "   • Tax Calculations: Accurate VAT/IVA calculations\n";
echo "   • Legal Requirements: Compliance with local tax laws\n";
echo "   • Audit Trail: Complete transaction history\n";
echo "   • Data Integrity: Consistent financial data\n";

// Save results
$reports_dir = __DIR__ . '/../reports';
if (!is_dir($reports_dir)) {
    mkdir($reports_dir, 0755, true);
}

$report_file = $reports_dir . '/invoice_sync_workflow_test_' . date('Y-m-d_H-i-s') . '.json';
file_put_contents($report_file, json_encode([
    'timestamp' => date('Y-m-d H:i:s'),
    'test_type' => 'invoice_sync_workflow_integration',
    'status' => count($failed_tests) > 0 ? 'failing' : 'passing',
    'results' => $test_results,
    'execution_time' => $execution_time,
    'workflow_steps' => 9,
    'components_tested' => count($invoice_components)
], JSON_PRETTY_PRINT));

echo "\n📄 Integration test results saved to: {$report_file}\n";
echo str_repeat("=", 80) . "\n";