<?php

/**
 * Test Forms Loading and Submission
 * This script tests if edit forms actually load and submit data correctly
 */

echo "🧪 TESTING FORMS LOADING AND SUBMISSION\n";
echo "=" . str_repeat("=", 60) . "\n\n";

// Test database connection first
try {
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=schoolapp', 'root', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "✅ Database connection successful\n\n";
} catch (PDOException $e) {
    echo "❌ Database connection failed: " . $e->getMessage() . "\n";
    exit(1);
}

// Test if server is running
$serverRunning = false;
$context = stream_context_create([
    'http' => [
        'timeout' => 5,
        'ignore_errors' => true
    ]
]);

$response = @file_get_contents('http://localhost:8000/login', false, $context);
if ($response !== false) {
    echo "✅ Server is running on localhost:8000\n\n";
    $serverRunning = true;
} else {
    echo "❌ Server is not running on localhost:8000\n";
    echo "Please start the server with: php artisan serve\n\n";
}

// Test each module's edit functionality
$modules = [
    'students' => [
        'table' => 'students',
        'name_field' => 'first_name',
        'test_data' => ['first_name' => 'TestEdit', 'last_name' => 'Student']
    ],
    'teachers' => [
        'table' => 'teachers', 
        'name_field' => 'first_name',
        'test_data' => ['first_name' => 'TestEdit', 'last_name' => 'Teacher']
    ],
    'guardians' => [
        'table' => 'guardians',
        'name_field' => 'first_name', 
        'test_data' => ['first_name' => 'TestEdit', 'last_name' => 'Guardian']
    ],
    'academic-years' => [
        'table' => 'academic_years',
        'name_field' => 'name',
        'test_data' => ['name' => 'Test Academic Year 2024-2025']
    ],
    'subjects' => [
        'table' => 'subjects',
        'name_field' => 'name',
        'test_data' => ['name' => 'Test Subject', 'code' => 'TEST']
    ],
    'classrooms' => [
        'table' => 'classrooms',
        'name_field' => 'name',
        'test_data' => ['name' => 'Test Classroom']
    ],
    'exam-types' => [
        'table' => 'exam_types',
        'name_field' => 'name',
        'test_data' => ['name' => 'Test Exam Type']
    ],
    'results' => [
        'table' => 'results',
        'name_field' => 'marks',
        'test_data' => ['marks' => 95]
    ]
];

echo "🔍 TESTING FORM LOADING AND DATA RETRIEVAL\n";
echo "-" . str_repeat("-", 50) . "\n";

foreach ($modules as $module => $config) {
    echo "\n📝 Testing $module module:\n";
    
    // 1. Check if records exist
    try {
        $stmt = $pdo->query("SELECT * FROM {$config['table']} LIMIT 1");
        $record = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($record) {
            echo "   ✅ Sample record found (ID: {$record['id']})\n";
            
            // 2. Test if edit route is accessible
            if ($serverRunning) {
                $editUrl = "http://localhost:8000/$module/{$record['id']}/edit";
                $editResponse = @file_get_contents($editUrl, false, $context);
                
                if ($editResponse !== false) {
                    echo "   ✅ Edit page loads successfully\n";
                    
                    // Check if the response contains form elements
                    if (strpos($editResponse, '<form') !== false || strpos($editResponse, 'useForm') !== false) {
                        echo "   ✅ Form elements detected in response\n";
                    } else {
                        echo "   ⚠️  No form elements detected\n";
                    }
                    
                    // Check if data is pre-populated (look for existing values)
                    $nameValue = $record[$config['name_field']] ?? '';
                    if ($nameValue && strpos($editResponse, $nameValue) !== false) {
                        echo "   ✅ Existing data appears to be pre-populated\n";
                    } else {
                        echo "   ⚠️  Existing data may not be pre-populated\n";
                    }
                } else {
                    echo "   ❌ Edit page failed to load\n";
                }
                
                // 3. Test show page
                $showUrl = "http://localhost:8000/$module/{$record['id']}";
                $showResponse = @file_get_contents($showUrl, false, $context);
                
                if ($showResponse !== false) {
                    echo "   ✅ Show page loads successfully\n";
                } else {
                    echo "   ❌ Show page failed to load\n";
                }
            }
            
        } else {
            echo "   ❌ No sample records found\n";
        }
        
    } catch (PDOException $e) {
        echo "   ❌ Database error: " . $e->getMessage() . "\n";
    }
}

echo "\n\n🔧 TESTING FORM VALIDATION AND STRUCTURE\n";
echo "-" . str_repeat("-", 50) . "\n";

// Test Vue component structure
$vueComponents = [
    'resources/js/pages/Students/Edit.vue' => 'Students',
    'resources/js/pages/Teachers/Edit.vue' => 'Teachers',
    'resources/js/pages/Guardians/Edit.vue' => 'Guardians',
    'resources/js/pages/Academic/AcademicYears/Edit.vue' => 'Academic Years',
    'resources/js/pages/Academic/Subjects/Edit.vue' => 'Subjects',
    'resources/js/pages/Academic/Classrooms/Edit.vue' => 'Classrooms',
    'resources/js/pages/Academic/ExamTypes/Edit.vue' => 'Exam Types',
    'resources/js/pages/Results/Edit.vue' => 'Results',
];

foreach ($vueComponents as $file => $name) {
    echo "\n📄 Testing $name Edit Component:\n";
    
    if (file_exists($file)) {
        $content = file_get_contents($file);
        
        // Check for essential form elements
        $checks = [
            'useForm' => strpos($content, 'useForm') !== false,
            'template' => strpos($content, '<template>') !== false,
            'form_tag' => strpos($content, '@submit.prevent="submit"') !== false,
            'input_fields' => strpos($content, '<Input') !== false,
            'submit_button' => strpos($content, 'type="submit"') !== false,
            'validation' => strpos($content, 'form.errors') !== false,
            'props' => strpos($content, 'defineProps') !== false,
        ];
        
        foreach ($checks as $check => $passed) {
            if ($passed) {
                echo "   ✅ " . ucfirst(str_replace('_', ' ', $check)) . "\n";
            } else {
                echo "   ❌ Missing " . str_replace('_', ' ', $check) . "\n";
            }
        }
        
        // Check for specific form fields based on module
        if ($name === 'Students') {
            $studentFields = ['first_name', 'last_name', 'email', 'student_id'];
            foreach ($studentFields as $field) {
                if (strpos($content, "v-model=\"form.$field\"") !== false) {
                    echo "   ✅ $field field properly bound\n";
                } else {
                    echo "   ⚠️  $field field may not be properly bound\n";
                }
            }
        }
        
    } else {
        echo "   ❌ Component file not found\n";
    }
}

echo "\n\n🎯 MANUAL TESTING INSTRUCTIONS\n";
echo "=" . str_repeat("=", 60) . "\n";

if ($serverRunning) {
    echo "Server is running! You can now test manually:\n\n";
    
    foreach ($modules as $module => $config) {
        echo "🔗 $module Module:\n";
        echo "   Index: http://localhost:8000/$module\n";
        echo "   Edit:  http://localhost:8000/$module/1/edit\n";
        echo "   Show:  http://localhost:8000/$module/1\n\n";
    }
    
    echo "📋 TESTING STEPS:\n";
    echo "1. Open each edit URL above\n";
    echo "2. Verify form loads with existing data\n";
    echo "3. Make a small change (e.g., add 'Test' to a name)\n";
    echo "4. Submit the form\n";
    echo "5. Verify the change was saved\n";
    echo "6. Check browser console for any JavaScript errors\n\n";
    
} else {
    echo "❌ Server not running. Start with: php artisan serve\n\n";
}

echo "🔍 WHAT TO LOOK FOR:\n";
echo "- Forms load without errors\n";
echo "- Existing data appears in form fields\n";
echo "- Form validation works (try submitting empty required fields)\n";
echo "- Success messages appear after submission\n";
echo "- Data actually updates in the database\n";
echo "- No JavaScript console errors\n";
echo "- Proper redirects after form submission\n\n";

echo "⚠️  COMMON ISSUES TO CHECK:\n";
echo "- 404 errors when accessing edit pages\n";
echo "- Blank forms (data not pre-populating)\n";
echo "- Form submission errors\n";
echo "- Validation not working\n";
echo "- JavaScript errors in browser console\n";
echo "- Database connection issues\n\n";

echo "✨ Form functionality test completed!\n";
echo "Please run manual tests using the URLs above.\n";
