<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

// Only admins can load settings
hw_require_auth(['admin']);

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

try {
    $pdo = hw_db();
    
    // Get category filter if provided
    $category = $_GET['category'] ?? 'all';
    
    // Build query based on category
    if ($category === 'all') {
        $stmt = $pdo->query('SELECT setting_key, setting_value, category FROM site_settings ORDER BY category, setting_key');
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $stmt = $pdo->prepare('SELECT setting_key, setting_value FROM site_settings WHERE category = ? ORDER BY setting_key');
        $stmt->execute([$category]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Format settings as key-value pairs
    $settings = [];
    if ($category === 'all') {
        // Group by category
        foreach ($rows as $row) {
            $cat = $row['category'];
            if (!isset($settings[$cat])) {
                $settings[$cat] = [];
            }
            $settings[$cat][$row['setting_key']] = $row['setting_value'];
        }
    } else {
        // Simple key-value pairs
        foreach ($rows as $row) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
    }
    
    echo json_encode([
        'success' => true,
        'settings' => $settings,
        'category' => $category,
        'count' => count($category === 'all' ? $rows : $settings)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to load settings: ' . $e->getMessage()
    ]);
}
