<?php

namespace App;

use Illuminate\Support\Facades\DB;

class Chat
{
    public $username = "";
    public $nickname = "";

    public function Authenticate()
    {
    }

    public function StoreMessage($tekst)
    {
        $userId = $_SESSION['web_login']['user_id'] ?? null;
        $username = $_SESSION['web_login']['username'] ?? null;

        if (empty($userId) || empty($username) || empty($tekst)) {
            return;
        }

        $last = DB::table('chat')
            ->select('message')
            ->where('user_id', $userId)
            ->orderByDesc('chat_id')
            ->limit(1)
            ->first();

        if (!$last || ($last->message ?? '') !== $tekst) {
            DB::table('chat')->insert([
                'time' => now(),
                'sender' => $username,
                'user_id' => $userId,
                'message' => $tekst,
            ]);
        }
    }

    public function UpdateChatFile($chat_file, $num_rows)
    {
        $output = "<ul>";

        $chats = DB::table('chat')
            ->select('time', 'sender', 'message')
            ->orderByDesc('chat_id')
            ->limit((int)$num_rows ?: 8)
            ->get();

        $x = 0;
        foreach ($chats as $chat) {
            $x++;
            $add = ($x % 2 === 0) ? ' class="odd" ' : '';
            $datetime = date("F jS @ H:i", strtotime($chat->time));
            $message = wordwrap($chat->message, 20, " ", true);
            $ime = wordwrap($chat->sender, 12, " ", true);

            $output .= '<li ' . $add . '>&lt;';
            $output .= '<a href="/profile.php?uname=' . rawurlencode($chat->sender) . '" title="' . htmlspecialchars($datetime, ENT_QUOTES, 'UTF-8') . ' GMT+1">';
            $output .= htmlspecialchars($ime, ENT_QUOTES, 'UTF-8');
            $output .= '</a>&gt; ';
            $output .= htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
            $output .= '</li>';
        }

        $output .= '</ul>';

        @file_put_contents(base_path($chat_file), $output);
    }

    public function ShowOnline()
    {
        echo '<div id="oboks" name="boks">Loading...</div>';
    }

    public function ShowChat($num_rows = 10, $username = null)
    {
        echo '<div id="chat_box" name="chat_box">Loading...</div>';

        echo '<div class="row well">';
        if (!empty($_SESSION['web_login']['status'])) {
            echo '<form action="' . htmlspecialchars(route('community.chat'), ENT_QUOTES, 'UTF-8') . '" method="post">';
            echo csrf_field();
            echo '<div class="col-sm-10">';
            echo '<input type="text" class="form-control" id="chat_txt" name="chat_txt" value="">';
            echo '</div>';

            echo '<div class="col-sm-2">';
            echo '<button type="submit" class="btn btn-success">Say</button>';
            echo '</div>';

            echo '<input type="hidden" name="store_chat" value="true">';
            echo '</form>';
        } else {
            echo '<div class="clear alert alert-danger">You should be logged in to join a chat!</div>';
        }
        echo '</div>';
    }
}
