<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;
use Laravel\Sanctum\PersonalAccessToken;

class MaintenanceController extends Controller
{
    public function toggleMaintenanceMode(Request $request)
    {
        $user = Auth::user();

        if ($user){// && $user->access_level == 1) { // Assuming you have an is_admin field to check for admin
            $maintenanceMode = Cache::get('maintenance_mode', false);
            $newMode = !$maintenanceMode;

            Cache::put('maintenance_mode', $newMode);
            Cache::put('maintenance_user_id', $newMode ? $user->id : null);

            //delete all personal access tokens except for user who initiated maintenance mode
            if (Auth::check()) {
                // Get the last token for the authenticated user
                $lastToken = $user->tokens()->latest()->first();

                if ($lastToken) {
                    // Delete all tokens except the last one
                    PersonalAccessToken::where('id', '!=', $lastToken->id)
                        ->delete();
                }
            }

            return response()->json([
                'message' => 'Maintenance mode ' . ($newMode ? 'enabled' : 'disabled'),
                'maintenance_mode' => $newMode
            ], 200);
        }

        return response()->json(['message' => 'Unauthorized'], 403);
    }

    public function getMaintenanceMode(Request $request)
    {
        $maintenance_mode = Cache::get('maintenance_mode', false);

        return response()->json(['maintenance_mode' => $maintenance_mode], 200);
    }
}
