<?php

namespace App\Libraries;

use CodeIgniter\HTTP\IncomingRequest;

/**
 * Logging sementara untuk verifikasi parity CI3 ↔ CI4.
 * Aktifkan dengan API_PARITY_LOG=true di .env (jangan di produksi jangka panjang).
 *
 * Output: writable/logs/api_parity-YYYY-MM-DD.log
 */
class ApiParityLogger
{
    public static function enabled(): bool
    {
        return filter_var(env('API_PARITY_LOG', false), FILTER_VALIDATE_BOOLEAN);
    }

    public static function logRequest(IncomingRequest $request): void
    {
        if (! self::enabled()) {
            return;
        }

        $post = $request->getPost() ?? [];
        $post = self::sanitizePostForLog($post);

        $line = sprintf(
            "[%s] IN  %s %s POST=%s\n",
            date('Y-m-d H:i:s'),
            $request->getMethod(),
            $request->getUri()->getPath(),
            json_encode($post, JSON_UNESCAPED_UNICODE)
        );

        self::append($line);
    }

    /**
     * @param mixed $payloadBody utf8ize'd structure (array/object) before json_encode
     */
    public static function logResponse(string $jsonBody): void
    {
        if (! self::enabled()) {
            return;
        }

        $preview = strlen($jsonBody) > 8000 ? substr($jsonBody, 0, 8000) . '...[truncated]' : $jsonBody;
        $line    = sprintf("[%s] OUT %s\n", date('Y-m-d H:i:s'), $preview);

        self::append($line);
    }

    private static function append(string $line): void
    {
        $path = WRITEPATH . 'logs' . DIRECTORY_SEPARATOR . 'api_parity-' . date('Y-m-d') . '.log';
        @file_put_contents($path, $line, FILE_APPEND | LOCK_EX);
    }

    /**
     * @param array<string, mixed> $post
     *
     * @return array<string, mixed>
     */
    private static function sanitizePostForLog(array $post): array
    {
        foreach (['password', 'pass_lama', 'pass_baru'] as $k) {
            if (array_key_exists($k, $post) && $post[$k] !== null && $post[$k] !== '') {
                $post[$k] = '***';
            }
        }
        if (isset($post['photo']) && is_string($post['photo']) && $post['photo'] !== '') {
            $post['photo'] = '[base64 len=' . strlen($post['photo']) . ']';
        }

        return $post;
    }
}
