<?php

declare(strict_types=1);

// Load Composer dependencies (Twig, Dompdf, etc.) when available.
$autoloadCandidates = [
    dirname(__DIR__) . '/vendor/autoload.php',       // Preferred: packaged/deployed plugin-local vendor
    dirname(__DIR__, 2) . '/vendor/autoload.php',    // Backward-compatible: workspace/shared vendor
];
foreach ($autoloadCandidates as $composerAutoload) {
    if (is_file($composerAutoload) && feca_mailshots_composer_autoload_is_usable($composerAutoload)) {
        try {
            require_once $composerAutoload;
        } catch (\Throwable $e) {
            error_log('FECA Mailshots skipped unusable Composer autoload: ' . $e->getMessage());
            continue;
        }
        break;
    }
}

function feca_mailshots_composer_autoload_is_usable(string $composerAutoload): bool
{
    $vendorDir = dirname($composerAutoload);
    $autoloadFiles = $vendorDir . '/composer/autoload_files.php';
    if (!is_file($autoloadFiles)) {
        return true;
    }

    $files = require $autoloadFiles;
    if (!is_array($files)) {
        error_log('FECA Mailshots Composer autoload_files.php did not return an array.');
        return false;
    }

    foreach ($files as $file) {
        if (!is_string($file) || !is_file($file)) {
            error_log('FECA Mailshots Composer dependency file is missing: ' . (is_scalar($file) ? (string) $file : 'unknown'));
            return false;
        }
    }

    return true;
}

spl_autoload_register(static function (string $class): void {
    $prefix = 'FecaMailshots\\';
    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;
    }

    $relative = substr($class, strlen($prefix));
    $path = __DIR__ . '/' . str_replace('\\', '/', $relative) . '.php';
    if (is_file($path)) {
        require_once $path;
    }
});
