<?php

namespace App\Http\Controllers;

use App\Models\BuyerProfile;
use App\Models\User;
use Illuminate\Http\Request;

class BuyerProfileController extends Controller
{
    // Create profile
    public function store(Request $request)
    {
        $request->validate([
            'contact_number' => 'nullable|string|max:20',
            'about' => 'nullable|string|max:500',
        ]);

        $user = $request->user();

        // if (!$user->hasRole('Buyer')) {
        //     return response()->json(['message' => 'Only buyers can create profiles.'], 403);
        // }
        if (!in_array('Buyer', $user->getRoleNames()->toArray())) {
            return response()->json(['message' => 'Only buyers can create profiles.'], 403);
        }



        // Check if profile already exists
        if (BuyerProfile::where('user_id', $user->id)->exists()) {
            return response()->json(['message' => 'Profile already exists.'], 400);
        }

        $profile = BuyerProfile::create([
            'user_id' => $user->id,
            'contact_number' => $request->contact_number,
            'about' => $request->about,
        ]);

        return response()->json(['message' => 'Profile created successfully.', 'profile' => $profile]);
    }

    // Show profile
    public function show($id)
    {
        $profile = BuyerProfile::with('user:id,name,email')->find($id);

        if (!$profile) {
            return response()->json(['message' => 'Profile not found.'], 404);
        }

        return response()->json([
            'name' => $profile->user->name,
            'email' => $profile->user->email,
            'contact_number' => $profile->contact_number,
            'about' => $profile->about,
        ]);
    }

    // Update profile
    public function update(Request $request, $id)
    {
        $request->validate([
            'contact_number' => 'nullable|string|max:20',
            'about' => 'nullable|string|max:500',
        ]);

        $profile = BuyerProfile::find($id);

        if (!$profile || $profile->user_id != $request->user()->id) {
            return response()->json(['message' => 'Access denied or profile not found.'], 403);
        }

        $profile->update($request->only('contact_number', 'about'));

        return response()->json(['message' => 'Profile updated successfully.', 'profile' => $profile]);
    }

    // Delete profile
    public function destroy(Request $request, $id)
    {
        $profile = BuyerProfile::find($id);

        if (!$profile || $profile->user_id != $request->user()->id) {
            return response()->json(['message' => 'Access denied or profile not found.'], 403);
        }

        $profile->delete();

        return response()->json(['message' => 'Profile deleted successfully.']);
    }
}
