<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', '0');

require_once dirname(__DIR__) . '/config/koneksi.php';

$jwtPath = dirname(__DIR__) . '/config/jwt.php';
if (is_file($jwtPath)) {
    require_once $jwtPath;
}

if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Koneksi database tidak tersedia.',
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$conn->set_charset('utf8mb4');

require_once __DIR__ . '/repository.php';

function sync_json_input(): array
{
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') {
        sync_fail('Body JSON wajib diisi.', 400);
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        sync_fail('JSON request tidak valid.', 400);
    }

    return $decoded;
}

function sync_response(array $payload, int $statusCode = 200): void
{
    http_response_code($statusCode);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function sync_fail(string $message, int $statusCode = 400, array $extra = []): void
{
    sync_response([
        'success' => false,
        'message' => $message,
    ] + $extra, $statusCode);
}

function sync_get_bearer_token(): ?string
{
    $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['Authorization'] ?? '';
    if (preg_match('/Bearer\s+(.+)$/i', $header, $matches) !== 1) {
        return null;
    }

    $token = trim($matches[1]);
    return $token === '' ? null : $token;
}

function sync_try_validate_identity(): ?array
{
    static $identityResolved = false;
    static $identity = null;

    if ($identityResolved) {
        return $identity;
    }

    $identityResolved = true;
    $token = sync_get_bearer_token();
    if ($token === null) {
        return null;
    }

    $candidates = [
        'validate_jwt',
        'validateJWT',
        'jwt_validate',
        'verifyJWT',
        'decode_jwt',
    ];

    foreach ($candidates as $functionName) {
        if (!function_exists($functionName)) {
            continue;
        }

        try {
            $result = $functionName($token);
            if (is_array($result)) {
                $identity = $result;
                return $identity;
            }
        } catch (Throwable $exception) {
            sync_fail('Token autentikasi tidak valid.', 401);
        }
    }

    return null;
}

function sync_assert_company_access(string $companyId): void
{
    $identity = sync_try_validate_identity();
    if (!is_array($identity)) {
        return;
    }

    $tokenCompanyId = trim((string)($identity['company_id'] ?? $identity['store_id'] ?? ''));
    if ($tokenCompanyId !== '' && $tokenCompanyId !== $companyId) {
        sync_fail('company_id tidak cocok dengan token login.', 403);
    }
}
