<?php
/**
 * license-php/api/tenant-bootstrap.php
 * GET /api/tenant/bootstrap (PHP Native)
 * Resolves authoritative tenant context in cPanel / PHP environments.
 */

require_once __DIR__ . '/../lib/Response.php';
require_once __DIR__ . '/../lib/LicenseCrypto.php';

Response::handleCors();

$host = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? $_SERVER['HTTP_HOST'] ?? '';
$domain = LicenseCrypto::cleanDomain($host);

// Read tenants from data/tenants.json
$tenantsFile = dirname(__DIR__, 2) . '/data/tenants.json';
$tenants = [];
if (file_exists($tenantsFile)) {
    $tenants = json_decode(file_get_contents($tenantsFile), true) ?: [];
}

$matchedTenant = null;
foreach ($tenants as $tid => $t) {
    if (!$t) continue;
    $tDomain = LicenseCrypto::cleanDomain($t['domain'] ?? '');
    if ($tDomain && $tDomain === $domain) {
        $matchedTenant = $t;
        break;
    }
    if (!empty($t['aliases']) && is_array($t['aliases'])) {
        foreach ($t['aliases'] as $alias) {
            $cleanAlias = LicenseCrypto::cleanDomain($alias);
            if ($cleanAlias && $cleanAlias === $domain) {
                $matchedTenant = $t;
                break 2;
            }
        }
    }
}

// Fallback to autonomous client_local if unresolved
if (!$matchedTenant) {
    $matchedTenant = $tenants['client_local'] ?? [
        'client_id' => 'client_local',
        'name'      => 'Sistem Presensi Digital',
        'domain'    => $domain ?: 'localhost',
        'status'    => 'active'
    ];
}

Response::json(200, [
    'success' => true,
    'status'  => 'READY',
    'tenant'  => [
        'tenant_id' => $matchedTenant['client_id'] ?? 'client_local',
        'name'      => $matchedTenant['name'] ?? 'Sistem Presensi Digital',
        'domain'    => $matchedTenant['domain'] ?? ($domain ?: 'localhost'),
        'status'    => $matchedTenant['status'] ?? 'active'
    ]
]);
