<?php

namespace App\Http\Controllers;

use App\Models\NationalDBUserProfile;
use App\Http\Requests\StoreNationalDBUserProfileRequest;
use App\Http\Requests\UpdateNationalDBUserProfileRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class NationalDBUserProfileController extends Controller
{

    // 🆕 List all user profiles
public function index()
{
    $profiles = NationalDBUserProfile::all();
    return response()->json($profiles, 200);
}

    // 🟢 1. Fetch all Regions
    public function regions(): JsonResponse
    {
        $regions = array_keys(config('regions'));
        return response()->json($regions);
    }

    // 🟢 2. Fetch Provinces under a Region
    public function provinces(string $region): JsonResponse
    {
        $provinces = config('regions')[$region] ?? [];
        return response()->json($provinces);
    }

    // 🟢 3. Fetch all States
    public function states(): JsonResponse
    {
        $states = array_keys(config('states'));
        return response()->json($states);
    }

    // 🟢 4. Fetch LGAs under a State
    public function lgas(string $state): JsonResponse
    {
        $lgas = config('states')[$state] ?? [];
        return response()->json($lgas);
    }

    // 🟢 5. Usual CRUD

   public function store(StoreNationalDBUserProfileRequest $request)
{
    $data = $request->validated();

    // Optional custom ID
    if ($request->has('id')) {
        $data['id'] = $request->input('id');
    }

    // Handle file upload
    if ($request->hasFile('image_path')) {
        $file = $request->file('image_path');
        $filename = uniqid('profile_') . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('uploads/user_images', $filename, 'public');
        $data['image_path'] = $path; // ✅ store relative path only
    }

    $profile = NationalDBUserProfile::create($data);

    return response()->json([
        'message' => 'User profile created successfully',
        'data' => $profile,
        'image_url' => asset('storage/' . $profile->image_path) // ✅ served URL
    ], 201);
}



    // 🔍 GET single Profile
    public function show(string $id)
    {
        $profile = NationalDBUserProfile::find($id);

        if (!$profile) {
            return response()->json(['error' => 'UserProfile Not Found'], 404);
        }

        return response()->json($profile, 200);
    }

    // ✏️ PUT update UserProfile
   public function update(UpdateNationalDBUserProfileRequest $request, string $id)
{
     Log::info('🔍 Received Payload:', $request->all()); // ✅ Debug incoming request
    $profile = NationalDBUserProfile::find($id);

    if (!$profile) {
        return response()->json(['error' => 'UserProfile Not Found'], 404);
    }

    $data = $request->validated();

    if ($request->hasFile('image_path')) {
        // Optional: remove old image if exists
        if ($profile->image_path && file_exists(public_path($profile->image_path))) {
            unlink(public_path($profile->image_path));
        }

        $file = $request->file('image_path');
        $filename = uniqid('profile_') . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('public/uploads/user_images', $filename);
        $data['image_path'] = str_replace('public/', 'storage/', $path);
    }

    $profile->update($data);

    return response()->json([
        'message' => 'User Profile Updated',
        'data' => $profile,
    ]);
}


    public function destroy(string  $id)
    {
        $profile = NationalDBUserProfile::find($id);

    if (!$profile) {
        return response()->json(['error' => 'UserProfile Not Found'], 404);
    }

    $profile->delete();

    return response()->json(['message' => 'UserProfile Deleted Successfully']);
    }
}
