<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Facilitator\Facilitator;

class FacilitatorController extends Controller
{
    /**
     * Menampilkan daftar user detail dengan fitur search, sort, dan filter.
     */
    public function index(Request $request): JsonResponse
    {
        $size = +$request->get('size') ?: 10;
        $query = Facilitator::query();

        // Fitur Pencarian (berdasarkan nama atau email)
        if ($request->has('search')) {
            $s = strtolower($request->get('search'));
            $query->where(function($q) use ($s) {
                $q->whereRaw('lower(full_name) like (?)', ["%{$s}%"])
                  ->orWhereRaw('lower(user_email) like (?)', ["%{$s}%"]);
            });
        }

        // Fitur Sorting (contoh: ?sort=-full_name)
        if ($request->has('sort')) {
            $order = $request->get('sort');
            $firstChar = substr($order, 0, 1);
            $dir = $firstChar === '-' ? 'desc' : 'asc';
            $field = $firstChar === '-' ? substr($order, 1) : $order;
            $query->orderBy($field, $dir);
        }

        // Fitur Filter Wilayah
        if ($request->has('province')) {
            $query->where('province', $request->get('province'));
        }
        if ($request->has('regency')) {
            $query->where('regency', $request->get('regency'));
        }
        if ($request->has('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        $users = $query->paginate($size);

        return response()->json($users);
    }

    /**
     * Menyimpan data user detail baru.
     */
    public function store(Request $request): JsonResponse
    {

        $validated = $request->validate([
            'user_email' => ['required', 'email', 'unique:facilitator,user_email'],
            'full_name'  => ['required', 'string', 'max:255'],
            'role'       => ['required', 'string'],
            'village'    => ['nullable', 'string'],
            'district'   => ['nullable', 'string'],
            'regency'    => ['nullable', 'string'],
            'province'   => ['nullable', 'string'],
            'phone'      => ['nullable', 'string'],
            'is_active'  => ['boolean'],
        ]);

        $user = Facilitator::create($validated);

        return response()->json($user, 201);
    }

    /**
     * Menampilkan detail satu user.
     */
    public function show(string $id): JsonResponse
    {
        
        $user = Facilitator::findOrFail($id);
        return response()->json($user);
    }

    /**
     * Memperbarui data user detail.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        
        $user = Facilitator::findOrFail($id);

        $validated = $request->validate([
            'user_email' => ['required', 'email', 'unique:facilitator,user_email,' . $id],
            'full_name'  => ['required', 'string', 'max:255'],
            'role'       => ['required', 'string'],
            'village'    => ['nullable', 'string'],
            'district'   => ['nullable', 'string'],
            'regency'    => ['nullable', 'string'],
            'province'   => ['nullable', 'string'],
            'phone'      => ['nullable', 'string'],
            'is_active'  => ['boolean'],
        ]);

        $user->update($validated);

        return response()->json($user);
    }

    /**
     * Menghapus data user detail.
     */
    public function destroy(string $id): JsonResponse
    {
        
        $user = Facilitator::findOrFail($id);
        $user->delete();

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