<?php
/**
 * Test script to verify API endpoints work with the provided token
 * Run this from the Perfex CRM root directory
 */

// Define necessary constants
define('BASEPATH', true);
define('APPPATH', 'application/');
define('ENVIRONMENT', 'testing');

// Include necessary files
require_once 'index.php'; // Load Perfex CRM

// Test token provided by user
$test_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoib3BlbmNvZGUiLCJuYW1lIjoiT3BlbkNvZGUiLCJBUElfVElNRSI6MTc2MTczNDQ4Nn0.vjukCjNwBCElzP7iT_eWEHhxzL5KPDZ7e05DR1OZEbE';

echo "Testing API with token: " . substr($test_token, 0, 50) . "...\n\n";

// Test 1: Check if API module is active
echo "Test 1: Checking if API module is active...\n";
$CI =& get_instance();
if ($CI->app_modules->is_active('api')) {
    echo "✅ API module is active\n";
} else {
    echo "❌ API module is not active\n";
    exit(1);
}

// Test 2: Try to decode the JWT token
echo "\nTest 2: Testing JWT token decoding...\n";
try {
    require_once 'modules/api/third_party/node.php';
    require_once 'modules/api/vendor/autoload.php';

    use Firebase\JWT\JWT;
    use Firebase\JWT\Key;

    $config = require_once 'modules/api/config/jwt.php';
    $decoded = JWT::decode($test_token, new Key($config['jwt_key'], $config['jwt_algorithm']));

    echo "✅ Token decoded successfully\n";
    echo "   User: " . ($decoded->user ?? 'N/A') . "\n";
    echo "   Name: " . ($decoded->name ?? 'N/A') . "\n";
    echo "   API Time: " . ($decoded->API_TIME ?? 'N/A') . "\n";

} catch (Exception $e) {
    echo "❌ Token decoding failed: " . $e->getMessage() . "\n";
}

// Test 3: Try to access a basic API endpoint
echo "\nTest 3: Testing API endpoint access...\n";

// Simulate API request headers
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_AUTHTOKEN'] = $test_token;
$_SERVER['REQUEST_URI'] = '/api/customers';

// Try to load the API controller
try {
    // Load the API module
    require_once 'modules/api/api.php';

    // Try to instantiate the customers controller
    $CI->load->library('api_aeiou'); // Load any required libraries

    echo "✅ API module loaded successfully\n";
    echo "✅ Basic API functionality appears to be working\n";

} catch (Exception $e) {
    echo "❌ API loading failed: " . $e->getMessage() . "\n";
}

echo "\n=== API Test Summary ===\n";
echo "If all tests passed above, the API should be working with your token.\n";
echo "You can now test actual API endpoints using tools like:\n";
echo "- Postman\n";
echo "- curl commands\n";
echo "- The API playground at: /api/playground\n";
echo "\nExample curl command:\n";
echo "curl -H \"Authtoken: $test_token\" https://flexinit.nl/portal/api/customers\n";
?>