<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Block;
use App\Models\UserReport;
use Illuminate\Support\Facades\Auth;

class BlockController extends Controller
{
    public function blockUser(Request $request)
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
        ]);

        $userId = $validated['user_id'];
        $loggedUserId = Auth::id();

        if ($userId == $loggedUserId) {
            return response()->json(['code' => 403, 'message' => 'You cannot block yourself'], 403);
        }

        $existingBlock = Block::where('blocker', $loggedUserId)->where('blocked', $userId)->first();

        if ($existingBlock) {
            $existingBlock->delete();
            return response()->json(['code' => 200, 'message' => 'User unblocked successfully']);
        }

        Block::create(['blocker' => $loggedUserId, 'blocked' => $userId]);
        return response()->json(['code' => 200, 'message' => 'User blocked successfully']);
    }

    public function blockList()
    {
        $loggedUserId = Auth::id();
        $blocks = Block::where('blocker', $loggedUserId)
            ->with('blockedUser:id,name,email') // Fetch blocked user details
            ->get();

        return response()->json(['code' => 200, 'message' => 'Blocked users fetched successfully', 'data' => $blocks]);
    }

    public function reportUser(Request $request)
    {
        $validated = $request->validate([
            'report_user_id' => 'required|exists:users,id',
            'reason' => 'required|string|max:255',
        ]);

        $loggedUserId = Auth::id();
        $reportUserId = $validated['report_user_id'];

        $existingReport = UserReport::where('user_id', $loggedUserId)->where('report_user_id', $reportUserId)->first();

        if ($existingReport) {
            return response()->json(['code' => 200, 'message' => 'User already reported']);
        }

        UserReport::create([
            'user_id' => $loggedUserId,
            'report_user_id' => $reportUserId,
            'reason' => $validated['reason'],
        ]);

        return response()->json(['code' => 200, 'message' => 'User reported successfully']);
    }
}
