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

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

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

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['category']) || !isset($input['settings'])) {
        echo json_encode(['success' => false, 'error' => 'Missing category or settings']);
        exit;
    }
    
    $category = $input['category'];
    $settings = $input['settings'];
    
    if (!is_array($settings)) {
        echo json_encode(['success' => false, 'error' => 'Settings must be an array']);
        exit;
    }
    
    $pdo = hw_db();
    
    // Begin transaction
    $pdo->beginTransaction();
    
    try {
        // Prepare statement for inserting/updating settings
        $stmt = $pdo->prepare('
            INSERT INTO site_settings (setting_key, setting_value, category) 
            VALUES (?, ?, ?) 
            ON DUPLICATE KEY UPDATE 
                setting_value = VALUES(setting_value),
                updated_at = NOW()
        ');
        
        $savedCount = 0;
        foreach ($settings as $key => $value) {
            // Sanitize key (only allow alphanumeric and underscores)
            $key = preg_replace('/[^a-z0-9_]/', '', strtolower($key));
            
            // Convert value to string for storage
            $valueStr = is_bool($value) ? ($value ? '1' : '0') : (string)$value;
            
            $stmt->execute([$key, $valueStr, $category]);
            $savedCount++;
        }
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => "Successfully saved {$savedCount} settings",
            'category' => $category
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to save settings: ' . $e->getMessage()
    ]);
}
