<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GmailSellSetting;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class GmailSellSettingController extends Controller
{
    public function index()
    {
        $setting = GmailSellSetting::first() ?: new GmailSellSetting();
        $setting->telegram_link = (string) (Setting::query()->where('key', 'gmail_sell_telegram_link')->value('value') ?? '');
        return view('admin.gmail_setting', compact('setting'));
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'password'            => 'required|string',
            'recovery_email'      => 'nullable|string',
            'require_recovery'    => 'required|boolean',
            'limit'               => 'required|integer',
            'price'               => 'required|numeric',
            'admin_price'         => 'required|numeric|min:0',
            'status'              => 'required|boolean',
            'telegram_link'       => 'nullable|string|max:255',
            'upline_commissions'  => 'nullable|array',
            'upline_commissions.*'=> 'nullable|numeric|min:0',
        ]);

        $telegramLink = trim((string) ($data['telegram_link'] ?? ''));
        unset($data['telegram_link']);

        $comm = collect($request->input('upline_commissions', []))
            ->map(fn($v) => is_null($v) || $v === '' ? 0 : (float)$v)
            ->values()
            ->toArray();

        $data['upline_commissions'] = $comm;

        $setting = GmailSellSetting::first();
        if ($setting) $setting->update($data);
        else GmailSellSetting::create($data);

        if ($telegramLink === '') {
            Setting::query()->where('key', 'gmail_sell_telegram_link')->delete();
        } else {
            Setting::updateOrCreate(
                ['key' => 'gmail_sell_telegram_link'],
                ['value' => $telegramLink]
            );
        }

        return redirect()->back()->with('success', 'সেটিংস সফলভাবে আপডেট হয়েছে');
    }

    public function toggle()
    {
        $setting = GmailSellSetting::first();

        if ($setting) {
            $setting->status = !$setting->status;
            $setting->save();
            return response()->json(['status' => $setting->status]);
        }

        return response()->json(['error' => 'Settings not found'], 404);
    }

    public function resetStats(Request $request)
    {
        $setting = GmailSellSetting::first();

        if (!$setting) {
            return redirect()->back()->with('error', 'আগে Gmail settings save করুন, তারপর হিসাব reset করুন।');
        }

        $setting->stats_reset_at = Carbon::now();
        $setting->save();

        return redirect()->back()->with('success', 'Gmail payment হিসাব reset হয়েছে। এখন থেকে নতুন করে count শুরু হবে।');
    }
}
