<?php

namespace Modules\LiveChat\App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\JobRequestFile;
use Modules\JobPost\App\Models\JobPostMessage;
use Modules\JobPost\App\Models\JobPostMessagesDocument;
use Modules\LiveChat\App\Models\Message;
use Modules\LiveChat\App\Models\RestrictedKeyword;

class AdminLiveChatController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Get restricted keywords
        $restricted_key_word = $this->getRestrictedKeywords();

        // Load messages with related job slug
        $jobpost_message = JobPostMessage::with('job_request:id,slug')->get();

        // Group by buyer_id, seller_id, and job_request_id
        $grouped = $jobpost_message->groupBy(function ($item) {
            return $item->buyer_id . '-' . $item->seller_id . '-' . $item->job_request_id;
        });

        // Fetch user names for display
        $users = \App\Models\User::pluck('name', 'id');

        $groupedMessages = collect();
        $restrictedCounts = [];
        $unseenCounts = [];

        // Loop and compute extra data + attach latest timestamp
        foreach ($grouped as $key => $messages) {
            $restrictedCount = 0;
            $unseenCount = 0;

            foreach ($messages as $message) {
                if (!empty($message->message)) {
                    foreach ($restricted_key_word as $keyword) {
                        $restrictedCount += substr_count(strtolower($message->message), strtolower($keyword));
                    }
                }

                if (!$message->isadmin_seen) {
                    $unseenCount++;
                }
            }

            $restrictedCounts[$key] = $restrictedCount;
            $unseenCounts[$key] = $unseenCount;

            $groupedMessages->push([
                'key' => $key,
                'messages' => $messages,
                'latest_time' => $messages->last()->created_at,
            ]);
        }

        $groupedMessages = $groupedMessages->sortByDesc('latest_time');

        return view('livechat::admin.job.index', compact(
            'groupedMessages',
            'users',
            'restricted_key_word',
            'restrictedCounts',
            'unseenCounts'
        ));
    }

    /**
     * Show the specified resource.
     */
    public function show($buyer_id, $seller_id, $job_request_id)
    {
        $restricted_key_word = $this->getRestrictedKeywords();

        // Fetch messages only for this specific job
        $messages = JobPostMessage::where('buyer_id', $buyer_id)
            ->where('seller_id', $seller_id)
            ->where('job_request_id', $job_request_id)
            ->orderBy('created_at', 'asc')
            ->get();

        // return JobPostMessagesDocument::all();

        // Fetch buyer and seller info
        $buyer = \App\Models\User::find($buyer_id);
        $seller = \App\Models\User::find($seller_id);

        // Mark messages as seen by admin
        $messages->each(function ($message) {
            $message->isadmin_seen = true;
            $message->save();
        });

        // Count restricted words
        $restrictedCount = 0;


        $job_post_submition_files = JobRequestFile::where('status', 1)->where('job_request_id', $job_request_id)->first();

        foreach ($messages as $message) {
            if (!$message->message) continue;

            foreach ($restricted_key_word as $keyword) {
                $restrictedCount += substr_count(strtolower($message->message), strtolower($keyword));
            }
        }

        return view('livechat::admin.job.show', compact(
            'messages',
            'buyer',
            'seller',
            'restricted_key_word',
            'restrictedCount',
            'job_post_submition_files'
        ));
    }




    /**
     * Display a listing of the resource.
     */
    public function message_index()
    {
        $restricted_key_word = $this->getRestrictedKeywords();
        $jobpost_message = Message::all();
        $users = \App\Models\User::pluck('name', 'id');

        // Group messages by buyer_id and seller_id
        $grouped = $jobpost_message->groupBy(function ($item) {
            return $item->buyer_id . '-' . $item->seller_id;
        });

        // Build groupedMessages with last message timestamps and counts
        $groupedMessages = collect();
        $restrictedCounts = [];
        $unseenCounts = [];

        foreach ($grouped as $key => $messages) {
            // Get latest message timestamp in this group
            $latestTimestamp = $messages->max('created_at');

            // Count restricted words
            $restrictedCount = 0;
            $unseenCount = 0;

            foreach ($messages as $message) {
                if (!empty($message->message)) {
                    foreach ($restricted_key_word as $keyword) {
                        $restrictedCount += substr_count(strtolower($message->message), strtolower($keyword));
                    }
                }

                if (!$message->isadmin_seen) {
                    $unseenCount++;
                }
            }

            // Store grouped data
            $groupedMessages->put($key, [
                'messages' => $messages,
                'latest' => $latestTimestamp,
            ]);

            $restrictedCounts[$key] = $restrictedCount;
            $unseenCounts[$key] = $unseenCount;
        }

        // Sort by latest message (descending)
        $groupedMessages = $groupedMessages->sortByDesc('latest');

        return view('livechat::admin.main.index', [
            'groupedMessages' => $groupedMessages,
            'users' => $users,
            'restricted_key_word' => $restricted_key_word,
            'restrictedCounts' => $restrictedCounts,
            'unseenCounts' => $unseenCounts,
        ]);
    }



    /**
     * Show the specified resource.
     */
    public function message_show($buyer_id, $seller_id)
    {
        $restricted_key_word = $this->getRestrictedKeywords();

        $messages = Message::where('buyer_id', $buyer_id)
            ->where('seller_id', $seller_id)
            ->orderBy('created_at', 'asc')
            ->get();

        $messages->each(function ($message) {
            $message->isadmin_seen = true;
            $message->save();
        });

        $buyer = \App\Models\User::find($buyer_id);
        $seller = \App\Models\User::find($seller_id);

        $restrictedCount = 0;

        foreach ($messages as $message) {
            if (!$message->message) continue;

            foreach ($restricted_key_word as $keyword) {
                $restrictedCount += substr_count(strtolower($message->message), strtolower($keyword));
            }
        }

        return view('livechat::admin.main.show', compact('messages', 'buyer', 'seller', 'restricted_key_word', 'restrictedCount'));
    }

    private function getRestrictedKeywords(): array
    {
        return RestrictedKeyword::pluck('keyword_name')->toArray();
    }
}
