<?php

namespace App\Http\Controllers\Employer;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\User;
use App\Models\Conversation;
use App\Models\Message;
use App\Models\Worker;

class MessageController extends Controller
{
    private function resolveCurrentUser()
    {
        $sess = session('user');
        $sessId = is_array($sess) ? ($sess['id'] ?? null) : ($sess->id ?? null);
        
        if (!$sessId) {
            $user = User::where('role', 'employer')->first();
            if ($user) {
                session(['user' => (object)[
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => 'employer',
                    'subscription_status' => $user->subscription_status ?? 'active',
                ]]);
                return $user;
            }
        } else {
            return User::find($sessId);
        }
        
        return null;
    }

    public function index(Request $request)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return redirect()->route('employer.login');
        }

        $dbConversations = Conversation::where('employer_id', $user->id)
            ->with(['worker.category', 'messages'])
            ->latest('updated_at')
            ->get();

        $conversations = $dbConversations->map(function ($conv) {
            $lastMsg = $conv->messages->last();
            return [
                'id' => $conv->id,
                'worker_name' => $conv->worker->name ?? 'Candidate',
                'category' => $conv->worker->category->name ?? 'General Helper',
                'last_message' => $lastMsg->text ?? 'No messages yet.',
                'unread' => $lastMsg ? ($lastMsg->sender_type === 'worker' && is_null($lastMsg->read_at)) : false,
                'online' => true,
                'sent_at' => $lastMsg ? $lastMsg->created_at->diffForHumans() : 'Just now',
            ];
        })->toArray();

        return Inertia::render('Employer/Messages/Index', [
            'conversations' => $conversations,
        ]);
    }

    public function show($id)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return redirect()->route('employer.login');
        }

        $dbConversations = Conversation::where('employer_id', $user->id)
            ->with(['worker.category', 'messages'])
            ->latest('updated_at')
            ->get();

        $conversations = $dbConversations->map(function ($conv) {
            $lastMsg = $conv->messages->last();
            return [
                'id' => $conv->id,
                'worker_name' => $conv->worker->name ?? 'Candidate',
                'category' => $conv->worker->category->name ?? 'General Helper',
                'last_message' => $lastMsg->text ?? 'No messages yet.',
                'unread' => $lastMsg ? ($lastMsg->sender_type === 'worker' && is_null($lastMsg->read_at)) : false,
                'online' => true,
                'sent_at' => $lastMsg ? $lastMsg->created_at->diffForHumans() : 'Just now',
            ];
        })->toArray();

        $activeConv = Conversation::where('employer_id', $user->id)
            ->where('id', $id)
            ->with(['worker.category', 'messages'])
            ->firstOrFail();

        // Mark incoming messages as read
        Message::where('conversation_id', $activeConv->id)
            ->where('sender_type', 'worker')
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

        $conversationData = [
            'id' => $activeConv->id,
            'worker_name' => $activeConv->worker->name ?? 'Candidate',
            'category' => $activeConv->worker->category->name ?? 'General Helper',
            'online' => true,
            'salary' => ($activeConv->worker->expected_salary ?? 2000) . ' AED',
            'nationality' => $activeConv->worker->nationality ?? 'Unknown',
        ];

        $initialMessages = $activeConv->messages->map(function ($msg) {
            return [
                'id' => $msg->id,
                'sender' => $msg->sender_type, // employer or worker
                'text' => $msg->text,
                'time' => $msg->created_at->format('g:i A') . ($msg->created_at->isToday() ? ' Today' : ' ' . $msg->created_at->format('M d')),
            ];
        })->toArray();

        return Inertia::render('Employer/Messages/Show', [
            'conversations' => $conversations,
            'conversation' => $conversationData,
            'initialMessages' => $initialMessages,
        ]);
    }

    public function send(Request $request, $id)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return back()->withErrors(['general' => 'User session not found.']);
        }

        $request->validate([
            'text' => 'required|string|max:1000',
        ]);

        $conv = Conversation::where('employer_id', $user->id)->where('id', $id)->firstOrFail();

        $message = Message::create([
            'conversation_id' => $conv->id,
            'sender_type' => 'employer',
            'sender_id' => $user->id,
            'text' => $request->text,
        ]);

        // Touch conversation updated_at for sorting
        $conv->touch();

        return back();
    }

    /**
     * Start or load a conversation with a specific worker.
     *
     * @param  int  $workerId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function startConversation($workerId)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return redirect()->route('employer.login');
        }

        // Find or create conversation
        $conv = Conversation::firstOrCreate([
            'employer_id' => $user->id,
            'worker_id' => $workerId,
        ]);

        return redirect()->route('employer.messages.show', ['id' => $conv->id]);
    }
}
