<?php

namespace App\Http\Controllers;

use App\Models\SystemSetting;
use App\Services\OtpService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;

class OtpSettingsController extends Controller
{
    protected OtpService $otpService;

    public function __construct(OtpService $otpService)
    {
        $this->otpService = $otpService;
    }

    /**
     * Display the OTP settings page.
     */
    public function index(): View
    {
        // Only Super Manager can access
        abort_unless(Auth::user()->hasRole('Super Manager'), 403);

        $otpEnabled = $this->otpService->isEnabled();

        return view('settings.otp', compact('otpEnabled'));
    }

    /**
     * Toggle OTP system-wide.
     */
    public function toggle(Request $request): JsonResponse
    {
        // Only Super Manager can toggle
        abort_unless(Auth::user()->hasRole('Super Manager'), 403);

        $request->validate([
            'enabled' => ['required', 'boolean'],
        ]);

        $this->otpService->toggle($request->boolean('enabled'));

        return response()->json([
            'success' => true,
            'message' => $request->boolean('enabled') 
                ? 'OTP verification has been enabled for all users.' 
                : 'OTP verification has been disabled for all users.',
            'enabled' => $request->boolean('enabled'),
        ]);
    }

    /**
     * Get OTP status via AJAX.
     */
    public function status(): JsonResponse
    {
        return response()->json([
            'enabled' => $this->otpService->isEnabled(),
        ]);
    }
}
