<?php
require_once '../config/database.php';

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $settings = $_POST;
        
        foreach ($settings as $key => $value) {
            // Skip non-setting fields
            if (in_array($key, ['submit', 'token'])) {
                continue;
            }
            
            // Handle checkbox values
            if (is_array($value)) {
                $value = implode(',', $value);
            }
            
            // Convert boolean-like strings
            if ($value === 'on') {
                $value = '1';
            } elseif ($value === 'off' || $value === '') {
                $value = '0';
            }
            
            // Check if setting exists
            $check_query = "SELECT id FROM settings WHERE setting_key = ?";
            $check_stmt = $pdo->prepare($check_query);
            $check_stmt->execute([$key]);
            
            if ($check_stmt->fetch()) {
                // Update existing setting
                $update_query = "UPDATE settings SET setting_value = ?, updated_at = NOW() WHERE setting_key = ?";
                $update_stmt = $pdo->prepare($update_query);
                $update_stmt->execute([$value, $key]);
            } else {
                // Insert new setting
                $insert_query = "INSERT INTO settings (setting_key, setting_value, setting_type, created_at, updated_at) 
                                VALUES (?, ?, 'string', NOW(), NOW())";
                $insert_stmt = $pdo->prepare($insert_query);
                $insert_stmt->execute([$key, $value]);
            }
        }
        
        echo json_encode(['success' => true, 'message' => 'Settings updated successfully']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error updating settings: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
