<?php

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Modules\Academic\Models\ExamType;
use Modules\Academic\Models\AcademicYear;
use App\Models\User;

class ExamTypesEditDeleteTest extends DuskTestCase
{
    protected $admin;
    protected $academicYear;
    protected $examType;

    protected function setUp(): void
    {
        parent::setUp();
        
        // Try to find existing admin user or create one
        $this->admin = User::where('email', 'admin@test.com')->first();
        
        if (!$this->admin) {
            $this->admin = User::factory()->create([
                'email' => 'admin@test.com',
                'role' => 'admin'
            ]);
        }

        // Create or find academic year
        $this->academicYear = AcademicYear::where('name', '2024-2025')->first();
        
        if (!$this->academicYear) {
            $this->academicYear = AcademicYear::factory()->create([
                'name' => 'Test-2024-' . time(),
                'is_active' => true
            ]);
        }

        // Create a test exam type
        $this->examType = ExamType::factory()->create([
            'name' => 'Test Edit Delete Exam ' . time(),
            'academic_year_id' => $this->academicYear->id,
            'weight' => 25.00,
            'description' => 'Test exam type for edit/delete testing',
            'is_active' => true
        ]);
    }

    /**
     * Test that exam types page loads and shows data
     */
    public function test_exam_types_page_loads_with_data()
    {
        $this->browse(function (Browser $browser) {
            echo "\n TESTING EXAM TYPES PAGE WITH DATA\n";
            echo "===================================================\n";
            
            $browser->loginAs($this->admin)
                    ->visit('/exam-types')
                    ->pause(3000); // Wait for page to load

            // Check current URL
            $currentUrl = $browser->driver->getCurrentURL();
            echo "   Current URL: " . $currentUrl . "\n";

            // Check for JavaScript errors
            $logs = $browser->driver->manage()->getLog('browser');
            $jsErrors = array_filter($logs, function($log) {
                return $log['level'] === 'SEVERE';
            });

            if (empty($jsErrors)) {
                echo "✅ No JavaScript errors found\n";
            } else {
                echo "❌ JavaScript errors found:\n";
                foreach ($jsErrors as $error) {
                    echo "   - " . $error['message'] . "\n";
                }
            }

            // Try to find the exam type in the page
            $pageSource = $browser->driver->getPageSource();
            
            if (strpos($pageSource, $this->examType->name) !== false) {
                echo "✅ Found exam type '{$this->examType->name}' in page\n";
            } else {
                echo "❌ Exam type '{$this->examType->name}' not found in page\n";
            }

            // Look for dropdown menu or action buttons
            if (strpos($pageSource, 'Edit') !== false) {
                echo "✅ Found 'Edit' text in page\n";
            } else {
                echo "❌ 'Edit' text not found in page\n";
            }

            if (strpos($pageSource, 'Delete') !== false) {
                echo "✅ Found 'Delete' text in page\n";
            } else {
                echo "❌ 'Delete' text not found in page\n";
            }

            // Look for dropdown trigger (three dots or similar)
            if (strpos($pageSource, 'MoreHorizontal') !== false || 
                strpos($pageSource, 'dropdown') !== false ||
                strpos($pageSource, '⋮') !== false ||
                strpos($pageSource, '...') !== false) {
                echo "✅ Found dropdown trigger indicators\n";
            } else {
                echo "❌ No dropdown trigger indicators found\n";
            }
        });
    }

    /**
     * Test direct access to edit page
     */
    public function test_direct_edit_page_access()
    {
        $this->browse(function (Browser $browser) {
            echo "\n TESTING DIRECT EDIT PAGE ACCESS\n";
            echo "===================================================\n";
            
            $editUrl = "/exam-types/{$this->examType->id}/edit";
            echo "   Visiting: " . $editUrl . "\n";
            
            $browser->loginAs($this->admin)
                    ->visit($editUrl)
                    ->pause(3000);

            $currentUrl = $browser->driver->getCurrentURL();
            echo "   Current URL: " . $currentUrl . "\n";

            // Check for JavaScript errors
            $logs = $browser->driver->manage()->getLog('browser');
            $jsErrors = array_filter($logs, function($log) {
                return $log['level'] === 'SEVERE';
            });

            if (empty($jsErrors)) {
                echo "✅ No JavaScript errors on edit page\n";
            } else {
                echo "❌ JavaScript errors on edit page:\n";
                foreach ($jsErrors as $error) {
                    echo "   - " . $error['message'] . "\n";
                }
            }

            $pageSource = $browser->driver->getPageSource();
            
            // Check if we're on the edit page
            if (strpos($currentUrl, '/edit') !== false) {
                echo "✅ Successfully accessed edit page\n";
                
                // Look for form elements
                if (strpos($pageSource, 'name') !== false && 
                    (strpos($pageSource, 'input') !== false || strpos($pageSource, 'form') !== false)) {
                    echo "✅ Found form elements on edit page\n";
                } else {
                    echo "❌ No form elements found on edit page\n";
                }
                
                if (strpos($pageSource, $this->examType->name) !== false) {
                    echo "✅ Found exam type name in edit form\n";
                } else {
                    echo "❌ Exam type name not found in edit form\n";
                }
                
            } else {
                echo "❌ Failed to access edit page\n";
            }
        });
    }

    /**
     * Test the route exists
     */
    public function test_edit_route_exists()
    {
        echo "\n TESTING EDIT ROUTE EXISTS\n";
        echo "===================================================\n";
        
        // Test if the route exists by checking Laravel routes
        $routeExists = \Route::has('exam-types.edit');
        
        if ($routeExists) {
            echo "✅ exam-types.edit route exists\n";
        } else {
            echo "❌ exam-types.edit route does not exist\n";
        }
        
        // Test if the destroy route exists
        $destroyRouteExists = \Route::has('exam-types.destroy');
        
        if ($destroyRouteExists) {
            echo "✅ exam-types.destroy route exists\n";
        } else {
            echo "❌ exam-types.destroy route does not exist\n";
        }
        
        // Test route generation
        try {
            $editUrl = route('exam-types.edit', $this->examType->id);
            echo "✅ Edit URL generated: " . $editUrl . "\n";
        } catch (\Exception $e) {
            echo "❌ Failed to generate edit URL: " . $e->getMessage() . "\n";
        }
        
        try {
            $destroyUrl = route('exam-types.destroy', $this->examType->id);
            echo "✅ Destroy URL generated: " . $destroyUrl . "\n";
        } catch (\Exception $e) {
            echo "❌ Failed to generate destroy URL: " . $e->getMessage() . "\n";
        }
        
        $this->assertTrue(true); // Ensure test passes
    }

    /**
     * Test controller methods exist
     */
    public function test_controller_methods_exist()
    {
        echo "\n TESTING CONTROLLER METHODS\n";
        echo "===================================================\n";
        
        $controller = new \Modules\Academic\Http\Controllers\ExamTypeController();
        
        if (method_exists($controller, 'edit')) {
            echo "✅ ExamTypeController::edit method exists\n";
        } else {
            echo "❌ ExamTypeController::edit method does not exist\n";
        }
        
        if (method_exists($controller, 'update')) {
            echo "✅ ExamTypeController::update method exists\n";
        } else {
            echo "❌ ExamTypeController::update method does not exist\n";
        }
        
        if (method_exists($controller, 'destroy')) {
            echo "✅ ExamTypeController::destroy method exists\n";
        } else {
            echo "❌ ExamTypeController::destroy method does not exist\n";
        }
        
        $this->assertTrue(true); // Ensure test passes
    }
}
