<?php
// ============================================================
// includes/config.php
// Konfigurasi utama aplikasi Ship Network Admin Dashboard
// Edit sesuai lingkungan Anda sebelum deploy
// ============================================================

define('SHIP_NAME', getConfig('ship_name', 'KM Nusantara Jaya'));
define('APP_VERSION', '1.0.0');
define('BASE_PATH', dirname(__DIR__));
define('CONFIG_FILE', BASE_PATH . '/data/config.json');
define('LOG_FILE', BASE_PATH . '/data/activity.log');
define('ALERTS_FILE', BASE_PATH . '/data/alerts.json');

// Pastikan direktori data ada
if (!is_dir(BASE_PATH . '/data')) {
    mkdir(BASE_PATH . '/data', 0755, true);
}

// Baca konfigurasi dari file JSON (disimpan lewat halaman Settings)
function loadConfig(): array {
    $file = CONFIG_FILE;
    if (!file_exists($file)) return [];
    $json = file_get_contents($file);
    return json_decode($json, true) ?? [];
}

function saveConfigFile(array $data): bool {
    $file = CONFIG_FILE;
    // Enkripsi password/token sebelum simpan
    $sensitiveKeys = ['ft_pass','ft_api_key','ar_client_secret','sl_token','anthropic_key','admin_pass'];
    foreach ($sensitiveKeys as $k) {
        if (isset($data[$k]) && $data[$k] !== '') {
            $data[$k] = encryptValue($data[$k]);
        } elseif (isset($data[$k])) {
            unset($data[$k]); // Jangan overwrite jika kosong
        }
    }
    return file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT)) !== false;
}

function getConfig(string $key, $default = '') {
    static $cfg = null;
    if ($cfg === null) $cfg = loadConfig();
    $val = $cfg[$key] ?? $default;
    // Dekripsi nilai terenkripsi
    $sensitiveKeys = ['ft_pass','ft_api_key','ar_client_secret','sl_token','anthropic_key','admin_pass'];
    if (in_array($key, $sensitiveKeys) && is_string($val) && str_starts_with($val, 'ENC:')) {
        return decryptValue($val);
    }
    return $val;
}

// Enkripsi sederhana untuk credential (gunakan APP_SECRET yang kuat di produksi)
define('APP_SECRET', getenv('APP_SECRET') ?: 'ship-net-admin-secret-2024-change-me');

function encryptValue(string $val): string {
    $key = hash('sha256', APP_SECRET, true);
    $iv = random_bytes(16);
    $encrypted = openssl_encrypt($val, 'AES-256-CBC', $key, 0, $iv);
    return 'ENC:' . base64_encode($iv . $encrypted);
}

function decryptValue(string $enc): string {
    if (!str_starts_with($enc, 'ENC:')) return $enc;
    $key = hash('sha256', APP_SECRET, true);
    $data = base64_decode(substr($enc, 4));
    $iv = substr($data, 0, 16);
    $encrypted = substr($data, 16);
    return openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv) ?: '';
}

function writeLog(string $message, string $level = 'info'): void {
    $line = '[' . date('Y-m-d H:i:s') . '] [' . strtoupper($level) . '] ' . $message . PHP_EOL;
    file_put_contents(LOG_FILE, $line, FILE_APPEND | LOCK_EX);
}

// Expose config ke halaman settings
$config = loadConfig();
