<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;

Route::match(['get', 'post'], '/ch', function (Request $request) {

    if (!session()->has('chat_user')) {
        $lastUser = cache()->get('last_chat_user', 0);

        $newUser = $lastUser == 1 ? 2 : 1;

        session()->put('chat_user', $newUser);
        cache()->put('last_chat_user', $newUser);
    }

    $user = session()->get('chat_user');

    if ($request->isMethod('post')) {
        $msgs = cache()->get('msgs', []);

        if (!is_array($msgs)) {
            $msgs = [];
        }

        $msgs[] = [
            'sender' => $user,
            'text' => $request->msg
        ];

        cache()->put('msgs', $msgs);

        return redirect('/ch');
    }

    return view('ch', [
        'user' => $user
    ]);
});

Route::get('/clear', function () {
    cache()->forget('msgs');

    return redirect('/ch');
});
