<?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 {
        $setting_key = $_POST['setting_key'];
        $setting_value = $_POST['setting_value'];
        $setting_type = $_POST['setting_type'];
        $description = $_POST['description'] ?? '';
        $is_public = isset($_POST['is_public']) ? 1 : 0;
        
        // Check if setting already exists
        $check_query = "SELECT id FROM settings WHERE setting_key = ?";
        $check_stmt = $pdo->prepare($check_query);
        $check_stmt->execute([$setting_key]);
        
        if ($check_stmt->fetch()) {
            echo json_encode(['success' => false, 'message' => 'Setting key already exists']);
            exit;
        }
        
        $query = "INSERT INTO settings (setting_key, setting_value, setting_type, description, is_public, created_at, updated_at) 
                  VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$setting_key, $setting_value, $setting_type, $description, $is_public]);
        
        echo json_encode(['success' => true, 'message' => 'Setting added successfully']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error adding setting: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
