<?php

namespace App\Http\Controllers\Api\RT;

use App\Http\Controllers\Controller;
use App\Models\Warga;
use App\Models\MutasiWarga;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class WargaController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Warga::query();

        if ($request->has('rt')) {
            $query->where('rt', $request->rt);
        }

        if ($request->has('status_warga')) {
            $query->where('status_warga', $request->status_warga);
        } else {
            $query->where('status_warga', 'Aktif');
        }

        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('nama', 'like', "%{$search}%")
                  ->orWhere('nik', 'like', "%{$search}%")
                  ->orWhere('kk', 'like', "%{$search}%");
            });
        }

        $wargas = $query->orderBy('nama')->paginate(20);

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

    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'nik' => 'required|string|size:16|unique:wargas',
            'kk' => 'required|string|size:16',
            'nama' => 'required|string|max:255',
            'jenis_kelamin' => 'required|in:L,P',
            'tempat_lahir' => 'required|string',
            'tanggal_lahir' => 'required|date',
            'alamat' => 'required|string',
            'rt' => 'required|string|max:3',
            'rw' => 'required|string|max:3',
            'kelurahan' => 'required|string',
            'kecamatan' => 'required|string',
            'kota' => 'required|string',
            'provinsi' => 'required|string',
            'telepon' => 'nullable|string',
            'email' => 'nullable|email',
            'status_perkawinan' => 'required|in:Belum Kawin,Kawin,Cerai Hidup,Cerai Mati',
            'pekerjaan' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $warga = Warga::create($request->all());

        return response()->json([
            'message' => 'Data warga berhasil ditambahkan',
            'data' => $warga
        ], 201);
    }

    public function show(Warga $warga): JsonResponse
    {
        return response()->json(['data' => $warga]);
    }

    public function update(Request $request, Warga $warga): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'nik' => 'required|string|size:16|unique:wargas,nik,' . $warga->id,
            'kk' => 'required|string|size:16',
            'nama' => 'required|string|max:255',
            'jenis_kelamin' => 'required|in:L,P',
            'tempat_lahir' => 'required|string',
            'tanggal_lahir' => 'required|date',
            'alamat' => 'required|string',
            'rt' => 'required|string|max:3',
            'rw' => 'required|string|max:3',
            'kelurahan' => 'required|string',
            'kecamatan' => 'required|string',
            'kota' => 'required|string',
            'provinsi' => 'required|string',
            'telepon' => 'nullable|string',
            'email' => 'nullable|email',
            'status_perkawinan' => 'required|in:Belum Kawin,Kawin,Cerai Hidup,Cerai Mati',
            'pekerjaan' => 'nullable|string',
            'status_warga' => 'required|in:Aktif,Pindah,Meninggal',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $warga->update($request->all());

        return response()->json([
            'message' => 'Data warga berhasil diupdate',
            'data' => $warga
        ]);
    }

    public function destroy(Warga $warga): JsonResponse
    {
        $warga->delete();

        return response()->json([
            'message' => 'Data warga berhasil dihapus'
        ]);
    }

    public function mutasi(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'warga_id' => 'required|exists:wargas,id',
            'jenis_mutasi' => 'required|in:Pindah Masuk,Pindah Keluar,Meninggal,Lahir',
            'tanggal_mutasi' => 'required|date',
            'alamat_tujuan' => 'nullable|string',
            'keterangan' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $mutasi = MutasiWarga::create([
            ...$request->all(),
            'user_id' => auth()->id()
        ]);

        // Update status warga jika pindah keluar atau meninggal
        if (in_array($request->jenis_mutasi, ['Pindah Keluar', 'Meninggal'])) {
            $warga = Warga::find($request->warga_id);
            $warga->update([
                'status_warga' => $request->jenis_mutasi === 'Meninggal' ? 'Meninggal' : 'Pindah'
            ]);
        }

        return response()->json([
            'message' => 'Mutasi warga berhasil dicatat',
            'data' => $mutasi
        ], 201);
    }

    public function import(Request $request): JsonResponse
    {
        // Placeholder untuk import Excel/CSV
        return response()->json([
            'message' => 'Fitur import akan segera tersedia'
        ]);
    }
}
