<?php
/**
 * PHPUnit Bootstrap File for Desk-Moloni v3.0
 * 
 * This file is executed before any tests run.
 * Sets up the testing environment, autoloading, and test fixtures.
 */

declare(strict_types=1);

// Error reporting for tests
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Set timezone for consistent test results
date_default_timezone_set('UTC');

// Define test constants
define('DESK_MOLONI_TEST_MODE', true);
define('DESK_MOLONI_TEST_DIR', __DIR__);
define('DESK_MOLONI_ROOT_DIR', dirname(__DIR__));

// Load Composer autoloader if available
$autoloaderPaths = [
    __DIR__ . '/../vendor/autoload.php',
    __DIR__ . '/../../vendor/autoload.php',
    __DIR__ . '/../../../vendor/autoload.php',
];

$autoloaderLoaded = false;
foreach ($autoloaderPaths as $autoloader) {
    if (file_exists($autoloader)) {
        require_once $autoloader;
        $autoloaderLoaded = true;
        break;
    }
}

if (!$autoloaderLoaded) {
    // Manual autoloading for basic testing
    spl_autoload_register(function ($class) {
        $prefix = 'DeskMoloni\\';
        $base_dir = __DIR__ . '/../';
        
        $len = strlen($prefix);
        if (strncmp($prefix, $class, $len) !== 0) {
            return;
        }
        
        $relative_class = substr($class, $len);
        
        // Map namespaces to directories
        $mappings = [
            'Tests\\' => 'tests/',
            'Models\\' => 'models/',
            'Controllers\\' => 'controllers/',
            '' => 'libraries/',
        ];
        
        foreach ($mappings as $namespace => $directory) {
            if (strpos($relative_class, $namespace) === 0) {
                $file = $base_dir . $directory . str_replace('\\', '/', substr($relative_class, strlen($namespace))) . '.php';
                if (file_exists($file)) {
                    require_once $file;
                    return;
                }
            }
        }
    });
}

// Test environment configuration
$_ENV['APP_ENV'] = 'testing';
$_ENV['APP_DEBUG'] = 'true';
$_ENV['DESK_MOLONI_TEST_MODE'] = 'true';

// Mock database setup for tests
if (!defined('DB_TYPE')) {
    define('DB_TYPE', 'sqlite');
    define('DB_HOSTNAME', ':memory:');
    define('DB_USERNAME', '');
    define('DB_PASSWORD', '');
    define('DB_DATABASE', 'desk_moloni_test');
}

// Test utility functions
if (!function_exists('test_log')) {
    function test_log(string $message, array $context = []): void {
        if (getenv('DESK_MOLONI_DEBUG') === 'true') {
            echo "[TEST LOG] " . $message;
            if (!empty($context)) {
                echo " Context: " . json_encode($context, JSON_PRETTY_PRINT);
            }
            echo PHP_EOL;
        }
    }
}

// Initialize test database if needed
if (class_exists('PDO') && DB_TYPE === 'sqlite') {
    try {
        $pdo = new PDO('sqlite::memory:');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        // Basic test tables will be created by individual tests as needed
    } catch (Exception $e) {
        test_log("Warning: Could not initialize test database: " . $e->getMessage());
    }
}

test_log("PHPUnit bootstrap completed successfully");