<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Str;

class GuestAccessController extends Controller
{
    public function toggle(): RedirectResponse
    {
        $envPath = base_path('.env');
        $current = config('hotel.guest_access_enabled', true);
        $newValue = $current ? 'false' : 'true';

        $env = file_get_contents($envPath);

        if (Str::contains($env, 'HOTEL_GUEST_ACCESS=')) {
            $env = preg_replace('/^HOTEL_GUEST_ACCESS=.*/m', 'HOTEL_GUEST_ACCESS=' . $newValue, $env);
        } else {
            $env .= "\nHOTEL_GUEST_ACCESS=" . $newValue . "\n";
        }

        file_put_contents($envPath, $env);
        Artisan::call('config:clear');

        $message = $newValue === 'true'
            ? '✅ Доступ гостей ВКЛЮЧЁН.'
            : '🔒 Доступ гостей ВЫКЛЮЧЕН. Гости видят страницу обслуживания.';

        return back()->with('guest_access_message', $message);
    }
}
