<?php
/**
 * get_public_settings.php: Returns public settings for frontend (non-sensitive)
 * No authentication required - public endpoint
 */

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';

header('Content-Type: application/json');
header('Cache-Control: public, max-age=300'); // Cache for 5 minutes
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once 'config.php';
require_once 'db.php';

try {
    // Check if settings table exists
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'settings'");
    
    if (!$tableCheck || $tableCheck->rowCount() === 0) {
        // Settings table doesn't exist, return defaults
        echo json_encode([
            'success' => true,
            'settings' => [
                'site_title' => 'First De France',
                'theme_color' => '#0ea5e9',
                'maintenance_mode' => false,
                'registration_enabled' => true,
                'withdrawal_min_amount' => 10,
                'withdrawal_fee_percent' => 0,
                'referral_bonus' => 5,
                'referral_percentage' => 5,
                'contact_email' => 'support@firstdefrance.com',
                'languages_enabled' => ['en','es','de','pt','ja','ko']
            ]
        ]);
        exit;
    }
    
    // Fetch all settings
    $stmt = $pdo->query('SELECT setting_key, setting_value FROM settings');
    $allSettings = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $allSettings[$row['setting_key']] = $row['setting_value'];
    }
    
    // Define which settings are public (non-sensitive)
    $langsRaw = $allSettings['languages_enabled'] ?? null;
    $langsDecoded = [];
    if ($langsRaw) {
        $tmp = json_decode($langsRaw, true);
        if (is_array($tmp)) { $langsDecoded = array_slice(array_values(array_unique(array_map('strval', $tmp))), 0, 12); }
    }
    if (empty($langsDecoded)) { $langsDecoded = ['en','es','de','pt','ja','ko']; }

    $publicSettings = [
        'site_title' => $allSettings['site_title'] ?? 'First De France',
        'theme_color' => $allSettings['theme_color'] ?? '#0ea5e9',
        'maintenance_mode' => ($allSettings['maintenance_mode'] ?? '0') === '1',
        'registration_enabled' => ($allSettings['registration_enabled'] ?? '1') === '1',
        'withdrawal_min_amount' => floatval($allSettings['withdrawal_min_amount'] ?? 10),
        'withdrawal_fee_percent' => floatval($allSettings['withdrawal_fee'] ?? 0),
        'referral_bonus' => floatval($allSettings['referral_bonus'] ?? 5),
        'referral_percentage' => floatval($allSettings['referral_percentage'] ?? 5),
        'contact_email' => $allSettings['contact_email'] ?? 'support@firstdefrance.com',
        'logo_url' => $allSettings['logo_url'] ?? '/logo.png',
        'languages_enabled' => $langsDecoded
    ];
    
    echo json_encode([
        'success' => true,
        'settings' => $publicSettings
    ]);
    
} catch (Exception $e) {
    error_log('Error fetching public settings: ' . $e->getMessage());
    // Return defaults on error
    echo json_encode([
        'success' => true,
        'settings' => [
            'site_title' => 'First De France',
            'theme_color' => '#0ea5e9',
            'maintenance_mode' => false,
            'registration_enabled' => true,
            'withdrawal_min_amount' => 10,
            'withdrawal_fee_percent' => 0,
            'referral_bonus' => 5,
            'referral_percentage' => 5,
            'contact_email' => 'support@firstdefrance.com'
        ]
    ]);
}
