<?php
/**
 * Test Workflow Script
 * Tests the complete GAD system workflow
 */

require_once 'config/config.php';

echo "=== PSAU GAD SYSTEM TEST WORKFLOW ===\n\n";

$db = getDB();
$testResults = [];

// Test 1: Database Connection
echo "Test 1: Database Connection\n";
try {
    $stmt = $db->query("SELECT 1");
    $testResults['database'] = '✅ PASS';
    echo "✅ Database connection successful\n\n";
} catch (Exception $e) {
    $testResults['database'] = '❌ FAIL';
    echo "❌ Database connection failed: " . $e->getMessage() . "\n\n";
}

// Test 2: User Authentication
echo "Test 2: User Authentication\n";
try {
    $auth = new Auth();
    
    // Test admin login
    $result = $auth->login('admin@psau.edu.ph', 'password');
    if ($result['success']) {
        $testResults['admin_login'] = '✅ PASS';
        echo "✅ Admin login successful\n";
        
        // Get admin info
        $adminInfo = $auth->getUserById($result['user_id']);
        echo "   - User ID: {$adminInfo['user_id']}\n";
        echo "   - Email: {$adminInfo['email']}\n";
        echo "   - Role: {$adminInfo['role']}\n";
    } else {
        $testResults['admin_login'] = '❌ FAIL';
        echo "❌ Admin login failed\n";
    }
    
    // Logout
    $auth->logout();
    
    // Test employee login
    $result = $auth->login('john.doe@psau.edu.ph', 'password');
    if ($result['success']) {
        $testResults['employee_login'] = '✅ PASS';
        echo "✅ Employee login successful\n";
        
        $empInfo = $auth->getUserById($result['user_id']);
        echo "   - User ID: {$empInfo['user_id']}\n";
        echo "   - Email: {$empInfo['email']}\n";
        echo "   - Role: {$empInfo['role']}\n";
    } else {
        $testResults['employee_login'] = '❌ FAIL';
        echo "❌ Employee login failed\n";
    }
    
    $auth->logout();
    echo "\n";
} catch (Exception $e) {
    $testResults['admin_login'] = '❌ FAIL';
    $testResults['employee_login'] = '❌ FAIL';
    echo "❌ Authentication test failed: " . $e->getMessage() . "\n\n";
}

// Test 3: Activity Queries
echo "Test 3: Activity Queries\n";
try {
    // Get all activities
    $stmt = $db->query("
        SELECT 
            a.*,
            COUNT(DISTINCT ar.registration_id) as registration_count
        FROM activities a
        LEFT JOIN activity_registrations ar ON a.activity_id = ar.activity_id
        WHERE a.is_active = 1
        GROUP BY a.activity_id
    ");
    $activities = $stmt->fetchAll();
    
    if (count($activities) > 0) {
        $testResults['activity_query'] = '✅ PASS';
        echo "✅ Found " . count($activities) . " activities\n";
        
        foreach ($activities as $activity) {
            echo "   - {$activity['title']} ({$activity['activity_date']})\n";
            echo "     Category: {$activity['category']}, Registrations: {$activity['registration_count']}\n";
        }
    } else {
        $testResults['activity_query'] = '⚠️  WARN';
        echo "⚠️  No activities found\n";
    }
    echo "\n";
} catch (Exception $e) {
    $testResults['activity_query'] = '❌ FAIL';
    echo "❌ Activity query failed: " . $e->getMessage() . "\n\n";
}

// Test 4: Employee Profiles
echo "Test 4: Employee Profiles\n";
try {
    $stmt = $db->query("
        SELECT 
            u.user_id,
            u.email,
            ep.first_name,
            ep.last_name,
            ep.gender,
            ep.category
        FROM users u
        JOIN employee_profiles ep ON u.user_id = ep.user_id
        WHERE u.role = 'employee'
    ");
    $employees = $stmt->fetchAll();
    
    if (count($employees) > 0) {
        $testResults['employee_profiles'] = '✅ PASS';
        echo "✅ Found " . count($employees) . " employee profiles\n";
        
        foreach ($employees as $emp) {
            echo "   - {$emp['first_name']} {$emp['last_name']} ({$emp['gender']}, {$emp['category']})\n";
        }
    } else {
        $testResults['employee_profiles'] = '⚠️  WARN';
        echo "⚠️  No employee profiles found\n";
    }
    echo "\n";
} catch (Exception $e) {
    $testResults['employee_profiles'] = '❌ FAIL';
    echo "❌ Employee profile query failed: " . $e->getMessage() . "\n\n";
}

// Test 5: Create Test Registration
echo "Test 5: Create Test Registration\n";
try {
    // Register employee (user_id=2) for activity (activity_id=1)
    $stmt = $db->prepare("
        INSERT INTO activity_registrations 
        (activity_id, user_id, registration_date, status, is_approved)
        VALUES (?, ?, NOW(), 'pending', 0)
    ");
    $stmt->execute([1, 2]);
    $registrationId = $db->lastInsertId();
    
    $testResults['create_registration'] = '✅ PASS';
    echo "✅ Created test registration (ID: {$registrationId})\n";
    echo "   - Activity: Gender Sensitivity Training\n";
    echo "   - Employee: John Doe\n";
    echo "   - Status: pending\n\n";
} catch (Exception $e) {
    if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
        $testResults['create_registration'] = '⚠️  SKIP';
        echo "⚠️  Registration already exists (skipped)\n\n";
    } else {
        $testResults['create_registration'] = '❌ FAIL';
        echo "❌ Registration creation failed: " . $e->getMessage() . "\n\n";
    }
}

// Test 6: QR Code Generation
echo "Test 6: QR Code Generation\n";
try {
    // Get a pending registration
    $stmt = $db->query("
        SELECT registration_id 
        FROM activity_registrations 
        WHERE status = 'pending' 
        LIMIT 1
    ");
    $registration = $stmt->fetch();
    
    if ($registration) {
        $qrCode = new QRCode();
        $result = $qrCode->generateForRegistration($registration['registration_id']);
        
        if ($result['success']) {
            $testResults['qr_generation'] = '✅ PASS';
            echo "✅ QR code generated successfully\n";
            echo "   - Registration ID: {$registration['registration_id']}\n";
            echo "   - QR Code URL: {$result['qr_code_url']}\n";
        } else {
            $testResults['qr_generation'] = '❌ FAIL';
            echo "❌ QR code generation failed\n";
        }
    } else {
        $testResults['qr_generation'] = '⚠️  SKIP';
        echo "⚠️  No pending registrations to test (skipped)\n";
    }
    echo "\n";
} catch (Exception $e) {
    $testResults['qr_generation'] = '❌ FAIL';
    echo "❌ QR code test failed: " . $e->getMessage() . "\n\n";
}

// Test 7: Directory Permissions
echo "Test 7: Directory Permissions\n";
$directories = [
    'uploads' => 'uploads',
    'uploads/profiles' => 'uploads/profiles',
    'uploads/certificates' => 'uploads/certificates',
    'uploads/qr_codes' => 'uploads/qr_codes',
    'logs' => 'logs'
];

$allWritable = true;
foreach ($directories as $name => $path) {
    if (is_writable($path)) {
        echo "✅ {$name} is writable\n";
    } else {
        echo "❌ {$name} is NOT writable\n";
        $allWritable = false;
    }
}

$testResults['permissions'] = $allWritable ? '✅ PASS' : '❌ FAIL';
echo "\n";

// Test 8: Email Class
echo "Test 8: Email Class\n";
try {
    $email = new Email();
    $testResults['email_class'] = '✅ PASS';
    echo "✅ Email class instantiated successfully\n";
    echo "   Note: SMTP not configured (emails won't send)\n\n";
} catch (Exception $e) {
    $testResults['email_class'] = '❌ FAIL';
    echo "❌ Email class failed: " . $e->getMessage() . "\n\n";
}

// Summary
echo "=== TEST SUMMARY ===\n\n";
$passed = 0;
$failed = 0;
$warnings = 0;

foreach ($testResults as $test => $result) {
    echo str_pad($test, 25) . " : " . $result . "\n";
    if (strpos($result, '✅') !== false) $passed++;
    elseif (strpos($result, '❌') !== false) $failed++;
    elseif (strpos($result, '⚠️') !== false) $warnings++;
}

echo "\n";
echo "Total Tests: " . count($testResults) . "\n";
echo "Passed: {$passed}\n";
echo "Failed: {$failed}\n";
echo "Warnings: {$warnings}\n";
echo "\n";

if ($failed === 0) {
    echo "🎉 All critical tests passed!\n";
} else {
    echo "⚠️  Some tests failed. Please review the errors above.\n";
}

echo "\n=== END OF TEST ===\n";

