<?php

namespace App\Http\Controllers\APIs;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreStateCoordinatorRequest;
use App\Models\StateCoordinator;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class StateCoordinatorController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $coordinators = StateCoordinator::latest()->get();
        return response()->json($coordinators);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreStateCoordinatorRequest $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('coordinator_') . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('uploads/coord_images', $filename, 'public');
        $data['image_path'] = $path; // ✅ store relative path only
    }


    $coordinator = StateCoordinator::create($data);

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

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        $coordinator = StateCoordinator::find($id);

        if(!$coordinator){
            return response()->json(data:['error' => 'User Not Found'], status: 404 );
        }
        return response()->json(data: $coordinator, status: 200);
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(StoreStateCoordinatorRequest $request, string $id)
    {
         $coordinator = StateCoordinator::find($id);

        if(!$coordinator){
            return response()->json(data:['error' => 'User Not Found'], status: 404 );
        }

        $coordinator->update($request->validated());

        return response()->json(data:
          ['message' => 'Coordinator Profile Updated',
          'data' => $coordinator
          ], status: 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $coordinator = StateCoordinator::find($id);

        if(!$coordinator){
            return response()->json(data:['error' => 'User Not Found'], status: 404 );
        }

        $coordinator->delete();

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