<?php

declare(strict_types=1);

/**
 * Load FPDF/FPDI only when generating PDFs — login/admin works without full vendor upload.
 */
function karvi_resolve_vendor_dir(): string
{
    static $resolved = null;
    if ($resolved !== null) {
        return $resolved;
    }

    $seen = [];
    $dirs = [dirname(__DIR__) . '/vendor'];
    $cursor = dirname(__DIR__);

    for ($i = 0; $i < 5; $i++) {
        $parent = dirname($cursor);
        if ($parent === $cursor) {
            break;
        }
        $cursor = $parent;
        $dirs[] = $cursor . '/vendor';
    }

    foreach ($dirs as $dir) {
        $real = realpath($dir);
        if ($real === false || isset($seen[$real])) {
            continue;
        }
        $seen[$real] = true;
        if (is_file($real . '/setasign/fpdf/fpdf.php')) {
            $resolved = $real;
            return $resolved;
        }
    }

    $resolved = dirname(__DIR__) . '/vendor';
    return $resolved;
}

function karvi_load_vendor(bool $required = true): bool
{
    static $loaded = false;
    if ($loaded) {
        return true;
    }

    $vendorDir = karvi_resolve_vendor_dir();
    $fpdfFile = $vendorDir . '/setasign/fpdf/fpdf.php';

    if (!is_file($fpdfFile)) {
        if ($required) {
            throw new RuntimeException(
                'PDF library missing. Upload vendor/ folder from Karvi-VENDOR-FIX.zip to: '
                . $vendorDir
            );
        }
        return false;
    }

    require_once $fpdfFile;

    spl_autoload_register(static function (string $class) use ($vendorDir): void {
        $prefix = 'setasign\\Fpdi\\';
        $baseDir = $vendorDir . '/setasign/fpdi/src/';
        if (strncmp($prefix, $class, strlen($prefix)) !== 0) {
            return;
        }
        $relativeClass = substr($class, strlen($prefix));
        $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
        if (is_file($file)) {
            require $file;
        }
    });

    $loaded = true;
    return true;
}
