<?php

namespace App\Http\Controllers\Admin;

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

class InSettingController extends Controller
{
    public function edit()
    {
        $setting = InSetting::first();
        if (!$setting) {
            $setting = new InSetting();
        }
        $setting->telegram_link = (string) (Setting::query()->where('key', 'instagram_sell_telegram_link')->value('value') ?? '');
        return view('admin.in.edit', compact('setting'));
    }

    public function update(Request $request)
{
    $request->validate([
        'account_password'       => 'required|string',
        'per_account_price'      => 'required|numeric',
        'daily_limit_per_user'   => 'required|integer',
        'telegram_link'          => 'nullable|string|max:255',
        'upline_commissions'     => 'nullable|array',
        'upline_commissions.*'   => 'numeric|min:0',
    ]);

    $setting = InSetting::first();
    if (!$setting) {
        $setting = new InSetting();
    }

    $setting->update([
        'account_password'     => $request->account_password,
        'per_account_price'    => $request->per_account_price,
        'daily_limit_per_user' => $request->daily_limit_per_user,
        'submission_enabled'   => $request->has('submission_enabled'),
        'upline_commissions'   => array_values($request->upline_commissions ?? []),
    ]);

    $telegramLink = trim((string) $request->input('telegram_link', ''));
    if ($telegramLink === '') {
        Setting::query()->where('key', 'instagram_sell_telegram_link')->delete();
    } else {
        Setting::updateOrCreate(
            ['key' => 'instagram_sell_telegram_link'],
            ['value' => $telegramLink]
        );
    }

    return back()->with('success', 'Settings updated successfully!');
}
}
