<?php
global $db;

// =====================
// Import & trust VoIP Stuff signing key
// =====================
$keyFile = __DIR__ . '/gpgkeys/046E8CA0EE6A755B.key';
$keyFp = '823B96CDB469B21E31A11923046E8CA0EE6A755B';

if (file_exists($keyFile)) {
    try {
        $gpg = \FreePBX::GPG();

        // Copy key to BMO signatures dir for future lookups
        $bmoKey = $gpg->keydir . '/046E8CA0EE6A755B.key';
        if (!file_exists($bmoKey)) {
            @copy($keyFile, $bmoKey);
        }

        // Check if key is already trusted
        $out = $gpg->runGPG("--list-keys $keyFp");
        if ($out['exitcode'] !== 0) {
            // Import key
            $gpg->runGPG("--import " . escapeshellarg($keyFile));
        }

        // Check if trust is already set
        $out = $gpg->runGPG("--export-ownertrust");
        if (strpos($out['stdout'], $keyFp) === false) {
            // Set ultimate trust
            $fd = fopen("php://temp", "r+");
            fwrite($fd, "$keyFp:6:\n");
            fseek($fd, 0);
            $gpg->runGPG("--import-ownertrust", $fd);
            fclose($fd);
        }
    } catch (\Exception $e) {
        // Non-fatal — module works fine unsigned
        error_log("CustomCDR: Could not import signing key: " . $e->getMessage());
    }
}

// =====================
// Register VoIP Stuff public module repository
// =====================
$repoUrl = 'https://repo.voip-stuff.net';
try {
    $currentRepo = \FreePBX::Config()->get('MODULE_REPO');
    // Remove any existing voip-stuff.net entry, then prepend so our proxy is queried first
    $repos = array_filter(explode(',', $currentRepo), function($r) {
        return strpos($r, 'voip-stuff.net') === false;
    });
    array_unshift($repos, $repoUrl);
    \FreePBX::Config()->update('MODULE_REPO', implode(',', $repos));
    // Invalidate cached module list so Module Admin re-fetches from new repo
    \FreePBX::Database()->query("UPDATE module_xml SET time = 0 WHERE id = 'module_repo'");
} catch (\Exception $e) {
    error_log("Could not register custom module repo: " . $e->getMessage());
}

// =====================
// Module configuration table (in main asterisk DB)
$sql = "CREATE TABLE IF NOT EXISTS customcdr_config (
    id INT AUTO_INCREMENT PRIMARY KEY,
    config_key VARCHAR(50) UNIQUE,
    config_value TEXT
)";
$db->query($sql);

// Default settings
$defaults = [
    'page_size'     => '50',
    'default_range' => '30',
];

foreach ($defaults as $key => $value) {
    $sql = "INSERT IGNORE INTO customcdr_config (config_key, config_value) VALUES (?, ?)";
    $stmt = $db->prepare($sql);
    $stmt->execute([$key, $value]);
}
