<?php

namespace App\Http\Controllers;

use App\Http\Requests\MatrixRegisterRequest;
use App\Services\MatrixRegistrationService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MatrixController extends Controller
{
    /**
     * Display the user page.
     */
    public function index(Request $request): View
    {
        $rooms = [
            ['name' => '🏠 General', 'description' => 'Our main chat.', 'alias' => 'https://matrix.to/#/#general:hstream.moe'],
            ['name' => '📡 Releases', 'description' => 'Were we @everyone for new releases.', 'alias' => 'https://matrix.to/#/#releases:hstream.moe'],
            ['name' => '👗 NSFW 2D', 'description' => 'Channel for R18 2D Media.', 'alias' => 'https://matrix.to/#/#nsfw:hstream.moe'],
            ['name' => '👗 NSFW IRL', 'description' => 'Channel for R18 IRL Media.', 'alias' => 'https://matrix.to/#/#nsfw-irl:hstream.moe'],
        ];

        return view('matrix.index', [
            'user' => $request->user(),
            'rooms' => $rooms,
        ]);
    }

    /**
     * Create matrix user
     */
    public function store(
        MatrixRegisterRequest $request,
        MatrixRegistrationService $matrixService
    ) {
        try {
            $result = $matrixService->registerUser(
                $request->username,
                $request->password
            );

            $user = $request->user();
            $user->matrix_id = $result['user_id'];
            $user->save();

            return redirect()
                ->back()
                ->with('success', 'Matrix user created successfully.');
        } catch (\Exception $e) {
            return back()
                ->withErrors([
                    'username' => $e->getMessage(),
                ])
                ->withInput();
        }
    }
}
