<?php
/**
 * license-php/api/auth-me.php
 * GET /api/auth/me (PHP Native)
 * Returns current authenticated user profile with live MySQL attributes.
 */

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

Response::handleCors();

$config = require __DIR__ . '/../config/config.php';
$pubKeyPath = $config['keys']['public'];
if (!file_exists($pubKeyPath)) {
    $pubKeyPath = dirname(__DIR__, 2) . '/keys/license_public.key';
}

$token = $_COOKIE['presensi_auth'] ?? '';
if (!$token && isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $token = trim((string)preg_replace('/^Bearer\s+/i', '', $_SERVER['HTTP_AUTHORIZATION']));
}

if (!$token) {
    Response::json(401, ['success' => false, 'code' => 'UNAUTHENTICATED', 'message' => 'Sesi login tidak ditemukan']);
}

$payload = null;
if (file_exists($pubKeyPath)) {
    $pubKeyPem = file_get_contents($pubKeyPath);
    $verified = LicenseCrypto::verifyToken($token, $pubKeyPem);
    if ($verified['valid']) {
        $payload = $verified['payload'];
    }
}

if (!$payload) {
    Response::json(401, ['success' => false, 'code' => 'INVALID_TOKEN', 'message' => 'Token autentikasi tidak valid']);
}

$callerRole = $payload['role'] ?? 'user';
$callerId   = $payload['username'] ?? ($payload['sub'] ?? 'user');
$userName   = $payload['nama'] ?? ($payload['username'] ?? 'User');
$userPhoto  = null;
$extraData  = [];

// Fetch live profile data from MySQL if available
if (in_array($callerRole, ['siswa', 'guru', 'tendik', 'operator_absensi'], true)) {
    try {
        if ($callerRole === 'siswa') {
            require_once __DIR__ . '/../lib/repositories/SiswaRepository.php';
            $repo = new SiswaRepository();
            $rec = $repo->findByNisn($callerId) ?: $repo->findByBarcode($callerId);
            if ($rec) {
                $userPhoto = $rec['foto'] ?? null;
                $userName = $rec['nama'] ?? $userName;
                $extraData['kelas'] = $rec['kelas'] ?? '';
                $extraData['nisn'] = $rec['nisn'] ?? '';
            }
        } elseif ($callerRole === 'guru') {
            require_once __DIR__ . '/../lib/repositories/GuruRepository.php';
            $repo = new GuruRepository();
            $rec = $repo->findByUsername($callerId) ?: ($repo->findByNip($callerId) ?: $repo->findByBarcode($callerId));
            if ($rec) {
                $userPhoto = $rec['foto'] ?? null;
                $userName = $rec['nama'] ?? $userName;
                $extraData['nip'] = $rec['nip'] ?? '';
                $extraData['jabatan'] = $rec['jabatan'] ?? '';
            }
        } elseif ($callerRole === 'tendik' || $callerRole === 'operator_absensi') {
            require_once __DIR__ . '/../lib/repositories/TendikRepository.php';
            $repo = new TendikRepository();
            $rec = $repo->findByUsername($callerId) ?: ($repo->findByNip($callerId) ?: $repo->findByBarcode($callerId));
            if ($rec) {
                $userPhoto = $rec['foto'] ?? null;
                $userName = $rec['nama'] ?? $userName;
                $extraData['nip'] = $rec['nip'] ?? '';
                $extraData['jabatan'] = $rec['jabatan'] ?? '';
            }
        }
    } catch (Throwable $e) {
        // Fall back gracefully to token payload
    }
}

$resData = [
    'success'       => true,
    'authenticated' => true,
    'tenant_id'     => $payload['tenant_id'] ?? 'client_local',
    'role'          => $callerRole,
    'username'      => $callerId,
    'nama'          => $userName,
    'foto'          => $userPhoto,
    'token'         => $token
];

if (!empty($extraData)) {
    $resData = array_merge($resData, $extraData);
}

Response::json(200, $resData);
