<?php
/**
 * KPI System Fixes Validation Script
 * Date: 2025-01-04
 * Description: Tests all KPI fixes to ensure they work correctly
 */

require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../app/bootstrap.php';

use App\Database\Connection;
use App\Repositories\KpiRepository;
use App\Utils\Logger;

$db = Connection::getInstance();
$kpiRepo = new KpiRepository($db);

echo "==========================================\n";
echo "KPI System Fixes Validation\n";
echo "==========================================\n\n";

$testsPassed = 0;
$testsFailed = 0;

/**
 * Test helper function
 */
function test($name, $condition, $expected = true) {
    global $testsPassed, $testsFailed;
    
    $result = $condition === $expected;
    if ($result) {
        echo "✅ PASS: {$name}\n";
        $testsPassed++;
    } else {
        echo "❌ FAIL: {$name}\n";
        echo "   Expected: " . ($expected ? 'true' : 'false') . ", Got: " . ($condition ? 'true' : 'false') . "\n";
        $testsFailed++;
    }
}

// Test 1: NULL payable_amount handling
echo "Test 1: NULL payable_amount handling\n";
echo "------------------------------------\n";
try {
    $filters = [
        'date_from' => '2025-01-01',
        'date_to' => '2025-01-31',
        'owner_didar_id' => 'test_agent_1'
    ];
    
    $settled = $kpiRepo->getSettledDeals($filters);
    $outstanding = $kpiRepo->getOutstandingBalance($filters);
    
    // Should not throw exception and should return valid arrays
    test("Settled deals query executes without error", is_array($settled), true);
    test("Outstanding balance query executes without error", is_array($outstanding), true);
    
    echo "\n";
} catch (\Exception $e) {
    test("NULL payable_amount handling", false, true);
    echo "   Error: " . $e->getMessage() . "\n\n";
}

// Test 2: Settlement date filter
echo "Test 2: Settlement date filter\n";
echo "------------------------------------\n";
try {
    // Create a deal with payments across multiple months
    // Filter for January should only count January payments
    $filters = [
        'date_from' => '2025-01-01',
        'date_to' => '2025-01-31',
        'owner_didar_id' => 'test_agent_1'
    ];
    
    $settled = $kpiRepo->getSettledDeals($filters);
    
    // Should return valid result
    test("Settlement date filter works", is_array($settled), true);
    
    echo "\n";
} catch (\Exception $e) {
    test("Settlement date filter", false, true);
    echo "   Error: " . $e->getMessage() . "\n\n";
}

// Test 3: Daily sales fallback date filters
echo "Test 3: Daily sales fallback date filters\n";
echo "------------------------------------\n";
try {
    $filters = [
        'date_from' => '2026-06-01',  // Future date with no data
        'date_to' => '2026-06-30',
        'owner_didar_id' => 'test_agent_1'
    ];
    
    $dailySales = $kpiRepo->getDailySales($filters);
    
    // Should return empty array or respect date filters
    test("Daily sales fallback respects date filters", is_array($dailySales), true);
    
    echo "\n";
} catch (\Exception $e) {
    test("Daily sales fallback date filters", false, true);
    echo "   Error: " . $e->getMessage() . "\n\n";
}

// Test 4: Time to conversion calculation
echo "Test 4: Time to conversion calculation\n";
echo "------------------------------------\n";
try {
    $filters = [
        'date_from' => '2025-01-01',
        'date_to' => '2025-01-31',
        'owner_didar_id' => 'test_agent_1'
    ];
    
    $timeToConversion = $kpiRepo->getTimeToConversion($filters);
    
    // Should return valid result with avg_conversion_days
    test("Time to conversion query executes", is_array($timeToConversion), true);
    test("Time to conversion has avg_conversion_days", isset($timeToConversion['avg_conversion_days']), true);
    
    echo "\n";
} catch (\Exception $e) {
    test("Time to conversion calculation", false, true);
    echo "   Error: " . $e->getMessage() . "\n\n";
}

// Test 5: Lead conversion logic
echo "Test 5: Lead conversion logic\n";
echo "------------------------------------\n";
try {
    $filters = [
        'date_from' => '2025-01-01',
        'date_to' => '2025-01-31',
        'owner_didar_id' => 'test_agent_1'
    ];
    
    $conversion = $kpiRepo->getNewLeadConversionRate($filters);
    
    // Should return valid result with all required fields
    test("Lead conversion query executes", is_array($conversion), true);
    test("Has total_new_leads", isset($conversion['total_new_leads']), true);
    test("Has converted_leads", isset($conversion['converted_leads']), true);
    test("Has conversion_rate", isset($conversion['conversion_rate']), true);
    
    echo "\n";
} catch (\Exception $e) {
    test("Lead conversion logic", false, true);
    echo "   Error: " . $e->getMessage() . "\n\n";
}

// Summary
echo "==========================================\n";
echo "Test Summary\n";
echo "==========================================\n";
echo "Tests Passed: {$testsPassed}\n";
echo "Tests Failed: {$testsFailed}\n";
echo "Total Tests: " . ($testsPassed + $testsFailed) . "\n";

if ($testsFailed === 0) {
    echo "\n✅ All tests passed!\n";
    exit(0);
} else {
    echo "\n❌ Some tests failed. Please review the errors above.\n";
    exit(1);
}

