<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AssetSetting;
use App\Models\Setting;
use Illuminate\Http\Request;

class AdminSettingsController extends Controller
{
    public function index()
    {
        $settings      = Setting::all()->pluck('value', 'key');
        $assetSettings = AssetSetting::orderBy('category')->orderBy('symbol')->get();
        return view('admin.settings.index', compact('settings', 'assetSettings'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'min_trade_amount'   => 'required|numeric|min:0.01',
            'max_trade_amount'   => 'required|numeric|min:1',
            'default_payout_pct' => 'required|numeric|min:1|max:99',
            'min_expiry_seconds' => 'required|integer|min:5',
            'max_expiry_seconds' => 'required|integer|min:10',
            'maintenance_mode'   => 'sometimes|in:0,1',
        ]);

        $keys = ['min_trade_amount', 'max_trade_amount', 'default_payout_pct', 'min_expiry_seconds', 'max_expiry_seconds'];
        foreach ($keys as $key) {
            Setting::set($key, $request->input($key));
        }
        Setting::set('maintenance_mode', $request->has('maintenance_mode') ? '1' : '0');

        return back()->with('success', 'Settings saved successfully.');
    }

    public function updateAssets(Request $request)
    {
        $assets = $request->input('assets', []);
        foreach ($assets as $symbol => $data) {
            AssetSetting::updateOrCreate(
                ['symbol' => $symbol],
                [
                    'payout_percent' => max(50, min(95, (float) ($data['payout_percent'] ?? 85))),
                    'is_open'        => isset($data['is_open']) && $data['is_open'] == '1',
                ]
            );
        }
        return back()->with('success', 'Asset settings updated successfully.');
    }
}
