<?php
/**
 * Admin Bonus & Cashback Settings API
 */

require_once 'config.php';

// Handle both GET and POST (JSON)
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$userId = miniapp_require_admin();

// گرفتن تنظیمات
function getSettings($pdo) {
    $keys = [
        'wallet_bonus_enabled', 
        'wallet_bonus_percent', 
        'wallet_bonus_min_amount', 
        'cashback_enabled', 
        'cashback_percent'
    ];
    
    $placeholders = implode(',', array_fill(0, count($keys), '?'));
    $stmt = $pdo->prepare("SELECT key_name, value FROM settings WHERE key_name IN ($placeholders)");
    $stmt->execute($keys);
    
    $settings = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $settings[$row['key_name']] = $row['value'];
    }
    
    return [
        'wallet_bonus_enabled' => ($settings['wallet_bonus_enabled'] ?? '0') === '1',
        'wallet_bonus_percent' => (int)($settings['wallet_bonus_percent'] ?? 10),
        'wallet_bonus_min_amount' => (int)($settings['wallet_bonus_min_amount'] ?? 100000),
        'cashback_enabled' => ($settings['cashback_enabled'] ?? '0') === '1',
        'cashback_percent' => (int)($settings['cashback_percent'] ?? 5),
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        echo json_encode(['ok' => true, 'data' => getSettings($pdo)]);
    } catch (PDOException $e) {
        // اگر تنظیمات وجود ندارد، مقادیر پیش‌فرض
        echo json_encode(['ok' => true, 'data' => [
            'wallet_bonus_enabled' => false,
            'wallet_bonus_percent' => 10,
            'wallet_bonus_min_amount' => 100000,
            'cashback_enabled' => false,
            'cashback_percent' => 5,
        ]]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $input['action'] ?? '';
    $key = $input['key'] ?? '';
    
    $validKeys = [
        'wallet_bonus_enabled', 
        'wallet_bonus_percent', 
        'wallet_bonus_min_amount', 
        'cashback_enabled', 
        'cashback_percent'
    ];
    
    if (!in_array($key, $validKeys)) {
        echo json_encode(['ok' => false, 'error' => 'کلید نامعتبر']);
        exit;
    }
    
    if ($action === 'toggle') {
        // گرفتن مقدار فعلی
        $stmt = $pdo->prepare("SELECT value FROM settings WHERE key_name = ?");
        $stmt->execute([$key]);
        $current = $stmt->fetchColumn();
        
        $newValue = ($current === '1') ? '0' : '1';
        
        $stmt = $pdo->prepare("INSERT INTO settings (key_name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
        $stmt->execute([$key, $newValue, $newValue]);
        gemaccAdminActionNotify('تنظیمات بونوس/کش‌بک تغییر وضعیت داد', ['کلید'=>$key, 'وضعیت جدید'=>$newValue === '1' ? 'فعال' : 'غیرفعال'], $userId);
        
        echo json_encode(['ok' => true, 'message' => 'وضعیت تغییر کرد']);
        exit;
    }
    
    if ($action === 'update') {
        $value = $input['value'] ?? '';
        
        $stmt = $pdo->prepare("INSERT INTO settings (key_name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
        $stmt->execute([$key, $value, $value]);
        gemaccAdminActionNotify('تنظیمات بونوس/کش‌بک بروزرسانی شد', ['کلید'=>$key, 'مقدار جدید'=>$value], $userId);
        
        echo json_encode(['ok' => true, 'message' => 'بروزرسانی شد']);
        exit;
    }
    
    echo json_encode(['ok' => false, 'error' => 'عملیات نامعتبر']);
}

