<?php

namespace App\Http\Controllers\API\v1;

use App\Models\Room;
use App\Models\User;
use App\Events\UserJoinedRoom;
use App\Events\UserLeftRoom;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class RoomController extends Controller
{
    /**
     * Display a listing of the rooms.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Fetch rooms the authenticated user belongs to
        $user = Auth::user();
        $rooms = Room::get();
        
        return response()->json([
            'success' => true,
            'data' => $rooms
        ]);
    }

    /**
     * Create a new room.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'is_private' => 'boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        $user = Auth::user();
        
        $room = new Room();
        $room->name = $request->name;
        $room->uuid = '11197';
        $room->owner_id = '11197';
        $room->user_id = '11197';
        
        // Generate a unique access code for private rooms
        if ($request->is_private) {
            $room->access_code = Str::random(8);
        }
        
        $room->save();
        
        // dd($room);
        // Add the creator to the room
        // $room->users()->attach($user->id);
        
        return response()->json([
            'success' => true,
            'message' => 'Room created successfully',
            'data' => $room
        ], 201);
    }

    /**
     * Display the specified room.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $id = 3;
        $user = Auth::user();
        $room = Room::with('users')->where('id', $id);
        
        // Check if user has access to the room
        // if (!$room->users->contains($user->id) && $room->access_code) {
        //     return response()->json([
        //         'success' => false,
        //         'message' => 'You need an access code to join this room'
        //     ], 403);
        // }
        
        return response()->json([
            'success' => true,
            'data' => $room
        ]);
    }

    /**
     * Join a room.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function join(Request $request, $id)
    {
        $user = Auth::user();
        $room = Room::findOrFail($id);
        
        // Check if the room requires an access code
        // if ($room->access_code) {
        //     $validator = Validator::make($request->all(), [
        //         'access_code' => 'required|string'
        //     ]);
            
        //     if ($validator->fails() || $request->access_code !== $room->access_code) {
        //         return response()->json([
        //             'success' => false,
        //             'message' => 'Invalid access code'
        //         ], 403);
        //     }
        // }
        
        // Check if the user is already in the room
        // if ($room->users->contains($user->id)) {
        //     return response()->json([
        //         'success' => true,
        //         'message' => 'Already in the room',
        //         'data' => $room->load('users')
        //     ]);
        // }
        
        // Add user to the room
        // $room->users()->attach($user->id);
        
        // Broadcast that a user has joined
        broadcast(new UserJoinedRoom($user, $room->id))->toOthers();
        
        return response()->json([
            'success' => true,
            'message' => 'Room joined successfully',
        ]);
    }

    /**
     * Leave a room.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function leave($id)
    {
        $user = Auth::user();
        $room = Room::findOrFail($id);
        
        // Check if the user is in the room
        if (!$room->users->contains($user->id)) {
            return response()->json([
                'success' => false,
                'message' => 'Not in the room'
            ], 400);
        }
        
        // Remove user from the room
        $room->users()->detach($user->id);
        
        // Broadcast that a user has left
        broadcast(new UserLeftRoom($room->id, $user->id))->toOthers();
        
        // If the room is empty and not owned by anyone, delete it
        if ($room->users()->count() === 0 && !$room->owner_id) {
            $room->delete();
            return response()->json([
                'success' => true,
                'message' => 'Room left and deleted successfully'
            ]);
        }
        
        return response()->json([
            'success' => true,
            'message' => 'Room left successfully'
        ]);
    }

    /**
     * Update room details.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $user = Auth::user();
        $room = Room::findOrFail($id);
        
        // Only the owner can update the room
        if ($room->owner_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to update this room'
            ], 403);
        }
        
        $validator = Validator::make($request->all(), [
            'name' => 'string|max:255',
            'is_private' => 'boolean',
        ]);
        
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        
        if ($request->has('name')) {
            $room->name = $request->name;
        }
        
        if ($request->has('is_private')) {
            if ($request->is_private && !$room->access_code) {
                $room->access_code = Str::random(8);
            } elseif (!$request->is_private) {
                $room->access_code = null;
            }
        }
        
        $room->save();
        
        return response()->json([
            'success' => true,
            'message' => 'Room updated successfully',
            'data' => $room
        ]);
    }

    /**
     * Remove the specified room.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user = Auth::user();
        $room = Room::findOrFail($id);
        
        // Only the owner can delete the room
        if ($room->owner_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to delete this room'
            ], 403);
        }
        
        // Detach all users from the room
        $room->users()->detach();
        
        // Delete the room
        $room->delete();
        
        return response()->json([
            'success' => true,
            'message' => 'Room deleted successfully'
        ]);
    }
    
    /**
     * Get room participants.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function participants($id)
    {
        $user = Auth::user();
        $room = Room::findOrFail($id);
        
        // Check if user has access to the room
        if (!$room->users->contains($user->id)) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have access to this room'
            ], 403);
        }
        
        $participants = $room->users;
        
        return response()->json([
            'success' => true,
            'data' => $participants
        ]);
    }
}