<?php
// Test script for authentication system
require_once 'api/config/database.php';
require_once 'api/models/User.php';
require_once 'api/utils/JWT.php';

echo "=== Testing SIF-GT Authentication System ===\n\n";

try {
    // Test database connection
    echo "1. Testing database connection...\n";
    $database = new Database();
    $db = $database->getConnection();
    echo "✓ Database connection successful\n\n";

    // Test User model
    echo "2. Testing User model...\n";
    $user = new User($db);
    
    // Test user creation
    $user->nombre = "Test Admin";
    $user->email = "admin@test.com";
    $user->password_hash = "password123";
    $user->rol = "Administrador";
    $user->activo = 1;
    
    // Validate user data
    $errors = $user->validate();
    if (empty($errors)) {
        echo "✓ User validation passed\n";
    } else {
        echo "✗ User validation failed: " . implode(", ", $errors) . "\n";
    }

    // Test JWT token generation
    echo "\n3. Testing JWT token generation...\n";
    $payload = [
        'user_id' => 1,
        'email' => 'admin@test.com',
        'nombre' => 'Test Admin',
        'rol' => 'Administrador',
        'iat' => time(),
        'exp' => time() + 3600
    ];
    
    $token = JWT::encode($payload, JWT_SECRET, JWT_ALGORITHM);
    echo "✓ JWT token generated: " . substr($token, 0, 50) . "...\n";

    // Test JWT token decoding
    echo "\n4. Testing JWT token decoding...\n";
    $decoded = JWT::decode($token, JWT_SECRET, JWT_ALGORITHM);
    
    if ($decoded['user_id'] == 1 && $decoded['email'] == 'admin@test.com') {
        echo "✓ JWT token decoded successfully\n";
        echo "  - User ID: " . $decoded['user_id'] . "\n";
        echo "  - Email: " . $decoded['email'] . "\n";
        echo "  - Role: " . $decoded['rol'] . "\n";
    } else {
        echo "✗ JWT token decoding failed\n";
    }

    // Test password hashing
    echo "\n5. Testing password hashing...\n";
    $password = "testpassword123";
    $hash = password_hash($password, PASSWORD_BCRYPT);
    
    if (password_verify($password, $hash)) {
        echo "✓ Password hashing and verification working\n";
    } else {
        echo "✗ Password hashing failed\n";
    }

    echo "\n=== All authentication tests completed ===\n";

} catch (Exception $e) {
    echo "✗ Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n";
}
?>