<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Conversation;
use App\Models\Message;
use Illuminate\Http\Request;

class InboxController extends Controller
{
    /**
     * Show inbox with all conversations
     */
    public function index()
    {
        $user = User::first(); // In real app: Auth::user()
        
        if (!$user) {
            return redirect()->route('home');
        }

        $conversations = Conversation::where('user_one_id', $user->id)
            ->orWhere('user_two_id', $user->id)
            ->with(['userOne', 'userTwo', 'latestMessage', 'ride.route.fromCity', 'ride.route.toCity'])
            ->orderBy('last_message_at', 'desc')
            ->get();

        return view('inbox.index', compact('user', 'conversations'));
    }

    /**
     * Show a specific conversation
     */
    public function show($id)
    {
        $user = User::first(); // In real app: Auth::user()
        
        $conversation = Conversation::with(['userOne', 'userTwo', 'messages.sender', 'ride.route.fromCity', 'ride.route.toCity'])
            ->findOrFail($id);

        // Mark messages as read
        $conversation->messages()
            ->where('sender_id', '!=', $user->id)
            ->where('is_read', false)
            ->update(['is_read' => true]);

        $otherUser = $conversation->getOtherUser($user->id);

        return view('inbox.show', compact('user', 'conversation', 'otherUser'));
    }

    /**
     * Send a message
     */
    public function sendMessage(Request $request, $id)
    {
        $request->validate([
            'content' => 'required|string|max:1000',
        ]);

        $user = User::first(); // In real app: Auth::user()
        $conversation = Conversation::findOrFail($id);

        Message::create([
            'conversation_id' => $conversation->id,
            'sender_id' => $user->id,
            'content' => $request->content,
        ]);

        $conversation->update(['last_message_at' => now()]);

        return redirect()->route('inbox.show', $id);
    }

    /**
     * Start a new conversation
     */
    public function startConversation(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'ride_id' => 'nullable|exists:rides,id',
            'message' => 'required|string|max:1000',
        ]);

        $user = User::first(); // In real app: Auth::user()
        $otherUserId = $request->user_id;

        // Check if conversation already exists
        $conversation = Conversation::where(function($q) use ($user, $otherUserId) {
            $q->where('user_one_id', $user->id)->where('user_two_id', $otherUserId);
        })->orWhere(function($q) use ($user, $otherUserId) {
            $q->where('user_one_id', $otherUserId)->where('user_two_id', $user->id);
        })->first();

        if (!$conversation) {
            $conversation = Conversation::create([
                'user_one_id' => $user->id,
                'user_two_id' => $otherUserId,
                'ride_id' => $request->ride_id,
                'last_message_at' => now(),
            ]);
        }

        Message::create([
            'conversation_id' => $conversation->id,
            'sender_id' => $user->id,
            'content' => $request->message,
        ]);

        $conversation->update(['last_message_at' => now()]);

        return redirect()->route('inbox.show', $conversation->id);
    }

    /**
     * Create demo conversations for testing
     */
    public function createDemo()
    {
        $user = User::first();
        
        if (!$user) {
            return redirect()->route('inbox')->with('error', 'No user found');
        }

        // Create demo users if needed
        $demoUsers = [
            ['name' => 'Ali Ahmed', 'email' => 'ali@demo.com'],
            ['name' => 'Sara Khan', 'email' => 'sara@demo.com'],
            ['name' => 'Hassan Malik', 'email' => 'hassan@demo.com'],
        ];

        foreach ($demoUsers as $demoData) {
            $demoUser = User::firstOrCreate(
                ['email' => $demoData['email']],
                array_merge($demoData, [
                    'password' => bcrypt('password'),
                    'user_type' => 'both',
                ])
            );

            // Create conversation if not exists
            $exists = Conversation::where(function($q) use ($user, $demoUser) {
                $q->where('user_one_id', $user->id)->where('user_two_id', $demoUser->id);
            })->orWhere(function($q) use ($user, $demoUser) {
                $q->where('user_one_id', $demoUser->id)->where('user_two_id', $user->id);
            })->exists();

            if (!$exists) {
                $conv = Conversation::create([
                    'user_one_id' => $user->id,
                    'user_two_id' => $demoUser->id,
                    'last_message_at' => now()->subMinutes(rand(1, 120)),
                ]);

                // Add sample messages
                $messages = [
                    ['sender' => $demoUser->id, 'content' => 'Hi, I saw your ride posting. Is it still available?'],
                    ['sender' => $user->id, 'content' => 'Yes, it\'s available! When do you want to travel?'],
                    ['sender' => $demoUser->id, 'content' => 'I need to go tomorrow morning. Can you pick me up from Faizabad?'],
                ];

                foreach ($messages as $i => $msg) {
                    Message::create([
                        'conversation_id' => $conv->id,
                        'sender_id' => $msg['sender'],
                        'content' => $msg['content'],
                        'created_at' => now()->subMinutes(30 - ($i * 5)),
                    ]);
                }
            }
        }

        return redirect()->route('inbox')->with('success', 'Demo conversations created!');
    }
}
