<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$conn = getDBConnection();
if (!$conn instanceof mysqli) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

$action = trim((string) ($_POST['action'] ?? 'keys'));

// ── ENGINE PRIORITY ───────────────────────────────────────────────
if ($action === 'priority') {
    $raw     = trim((string) ($_POST['priority'] ?? ''));
    $allowed = ['claude', 'groq', 'gemini'];
    $parts   = array_values(array_intersect(
        array_map('trim', explode(',', $raw)),
        $allowed
    ));

    if (count($parts) !== 3) {
        echo json_encode(['success' => false, 'message' => 'Invalid priority — must contain claude, groq, gemini']);
        exit;
    }

    $value  = implode(',', $parts);
    $userId = (int) $_SESSION['user_id'];

    $stmt = $conn->prepare(
        "INSERT INTO ai_engine_config (setting_key, setting_value, updated_by)
         VALUES ('engine_priority', ?, ?)
         ON DUPLICATE KEY UPDATE setting_value = ?, updated_by = ?"
    );
    $stmt->bind_param('sisi', $value, $userId, $value, $userId);
    $stmt->execute();
    $stmt->close();

    echo json_encode(['success' => true, 'message' => 'Engine priority saved']);
    exit;
}

// ── API KEYS / MODELS ────────────────────────────────────────────
$configPath = dirname(__DIR__, 2) . '/config.php';
$configContent = file_get_contents($configPath);

if ($configContent === false) {
    echo json_encode(['success' => false, 'message' => 'Cannot read config.php — check file permissions']);
    exit;
}

/**
 * Maps POST field → [CONSTANT_NAME, is_api_key]
 * Only update a constant when the POST value is non-empty.
 */
$fields = [
    'claude_api_key' => ['CLAUDE_API_KEY', true],
    'claude_model'   => ['CLAUDE_MODEL',   false],
    'groq_api_key'   => ['GROQ_API_KEY',   true],
    'groq_model'     => ['GROQ_MODEL',     false],
    'gemini_api_key' => ['GEMINI_API_KEY', true],
    'gemini_model'   => ['GEMINI_MODEL',   false],
];

$updated = [];

foreach ($fields as $postKey => [$constant, $isKey]) {
    $raw = trim((string) ($_POST[$postKey] ?? ''));
    if ($raw === '') {
        continue; // don't blank out existing values
    }

    // Sanitise: allow only safe characters
    if ($isKey) {
        // API keys: alphanumeric + common key chars
        $safe = preg_replace('/[^a-zA-Z0-9\-_\.]+/', '', $raw);
    } else {
        // Model identifiers: alphanumeric + dash/dot/colon/slash
        $safe = preg_replace('/[^a-zA-Z0-9\-_\.\/:]+/', '', $raw);
    }

    if ($safe === '') {
        continue;
    }

    // Replace inside define('CONSTANT', '...') — handles both bare define and guarded form
    $escaped = addslashes($safe);
    $pattern = "/define\('" . preg_quote($constant, '/') . "',\s*'[^']*'\)/";
    $replacement = "define('{$constant}', '{$escaped}')";

    $newContent = preg_replace($pattern, $replacement, $configContent);

    if ($newContent !== null && $newContent !== $configContent) {
        $configContent = $newContent;
        $updated[] = $constant;
    }
}

if (!empty($updated)) {
    if (file_put_contents($configPath, $configContent) === false) {
        echo json_encode(['success' => false, 'message' => 'Cannot write config.php — check file permissions']);
        exit;
    }
}

$msg = empty($updated)
    ? 'No changes detected (leave fields blank to keep existing values)'
    : 'Saved: ' . implode(', ', $updated);

echo json_encode(['success' => true, 'message' => $msg, 'updated' => $updated]);
