<?php

namespace App\Http\Controllers\Community;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ChatController extends Controller
{
    public function index(Request $request)
    {
        $page_title = 'Online Chat';

        $store = $request->input('store_chat');
        $chat_text = $request->input('chat_txt');

        $chat = new \App\Chat();

        if (!empty($store) && $store === 'true' && !empty($chat_text)) {
            if (!empty($_SESSION['web_login']['status'])) {
                $chat->StoreMessage($chat_text);
                $chat->UpdateChatFile('cron/chat_log.txt', 10);
            }
        }

        ob_start();
        \App\Banner::ShowResponsiveAd();
        $adHtml = ob_get_clean();

        ob_start();
        $userID = $_SESSION['web_login']['user_id'] ?? null;
        $chat->ShowChat(50, $userID);
        $chatHtml = ob_get_clean();

        try {
            $smileys = DB::table('smileys')->select('code', 'picture', 'emotion')->get();
        } catch (\Throwable $e) {
            $smileys = collect();
        }

        return view('community.chat', compact('page_title', 'adHtml', 'chatHtml', 'smileys'));
    }

    /**
     * Handle legacy AJAX chat posts from old JS.
     */
    public function post(Request $request)
    {
        $message = $request->input('message') ?? $request->input('chat_txt') ?? null;
        if (empty($message)) {
            return response()->json(['ok' => false, 'error' => 'empty_message'], 400);
        }

        // Ensure legacy $_SESSION keys exist for Chat class (best-effort sync from Laravel session/auth)
        if (empty($_SESSION['web_login']['user_id'])) {
            $webLogin = session('web_login');
            if ($webLogin && isset($webLogin['user_id'])) {
                $_SESSION['web_login'] = $webLogin;
            } elseif (auth()->check()) {
                $user = auth()->user();
                $_SESSION['web_login'] = [
                    'user_id' => $user->id,
                    'username' => $user->username ?? $user->name ?? null,
                    'status' => true,
                ];
            }
        }

        $chat = new \App\Chat();
        try {
            $chat->StoreMessage($message);
            $chat->UpdateChatFile('cron/chat_log.txt', 50);
        } catch (\Throwable $e) {
            return response()->json(['ok' => false, 'error' => 'store_failed', 'message' => $e->getMessage()], 500);
        }

        return response()->json(['ok' => true]);
    }
}
