<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';

apply_cors();
$admin = require_admin();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $stmt = $pdo->query('SELECT * FROM app_settings WHERE id = 1');
    $row = $stmt->fetch();
    if ($row && $admin['role'] !== 'SUPER_ADMIN') {
        unset($row['gemini_api_key']); // secret hidden from plain ADMIN role
    } elseif ($row && !empty($row['gemini_api_key'])) {
        $row['gemini_api_key'] = str_repeat('*', max(0, strlen($row['gemini_api_key']) - 4)) . substr($row['gemini_api_key'], -4);
    }
    send_success(['settings' => $row]);
}

if ($method === 'POST' || $method === 'PUT') {
    $input = get_json_input();

    $allowed = [
        'app_name', 'support_email', 'support_whatsapp', 'support_upi_id',
        'privacy_policy', 'terms', 'about_us', 'contact_info', 'announcement',
        'facebook_url', 'instagram_url', 'youtube_url', 'telegram_url',
        'whatsapp_url', 'linkedin_url', 'twitter_url',
        'referral_commission', 'default_trial_days',
    ];

    $fields = [];
    $params = [];
    foreach ($allowed as $f) {
        if (isset($input[$f])) {
            $fields[] = "$f = :$f";
            $params[":$f"] = $input[$f];
        }
    }

    if (isset($input['gemini_api_key']) && strpos($input['gemini_api_key'], '*') === false) {
        if ($admin['role'] !== 'SUPER_ADMIN') {
            send_error('Only SUPER_ADMIN can update the AI API key.', 403);
        }
        $fields[] = 'gemini_api_key = :gemini_key';
        $params[':gemini_key'] = $input['gemini_api_key'];
    }

    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE app_settings SET ' . implode(', ', $fields) . ' WHERE id = 1');
    $stmt->execute($params);

    log_admin_action($admin['email'], 'UPDATE_APP_SETTINGS', '', 'Fields: ' . implode(',', array_keys($input)));
    send_success(null, 'App settings updated.');
}

send_error('Invalid request.', 400);
