<?php

namespace App\Http\Controllers\Web\Ekosistem;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Penduduk\Keluarga;
use App\Models\Wilayah\Provinsi;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class KeluargaController extends Controller
{
    public function index(Request $request)
    {
        $query = Keluarga::with(['desakelurahan', 'adat'])->orderBy('created_at', 'desc');

        if ($request->search) {
            $query->where('kk', 'like', '%' . $request->search . '%');
        }

        $keluarga = $query->paginate($request->per_page ?? 10);
        return view('master.keluarga.index', compact('keluarga'));
    }

    public function create()
    {
        $provinsi = Provinsi::orderBy('nama', 'asc')->get();
        return view('master.keluarga.add', compact('provinsi'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'kk'                => ['required', 'string', 'min:16', 'max:16'],
            'desa_kelurahan_id' => ['required'],
            'adat_id'           => ['nullable'], 
            'file_kk'           => ['nullable', 'file', 'mimes:jpeg,jpg,png,pdf', 'max:2048'],
        ]);

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

        $pathKk = null;
        $fileNameKk = null;

        if ($request->hasFile('file_kk')) {
            $file = $request->file('file_kk');
            $fileNameKk = $file->getClientOriginalName();
            $pathKk = $file->store('uploads/keluarga', 'public');
        }

        Keluarga::create([
            'kk'                => $request->kk,
            'desa_kelurahan_id' => $request->desa_kelurahan_id,
            'adat_id'           => $request->adat_id,
            'path_kk'           => $pathKk,
            'file_kk'           => $fileNameKk,
            'created_by'        => auth()->id(),
            'updated_by'        => auth()->id(),
        ]);

        return response()->json(['status' => 'success', 'message' => 'Data Keluarga berhasil ditambahkan.']);
    }

    public function show($id)
    {
        $keluarga = Keluarga::with(['desakelurahan.kecamatan.kabupatenkota.provinsi', 'adat'])->findOrFail($id);
        return view('master.keluarga.view', compact('keluarga'));
    }

    public function edit($id)
    {
        $keluarga = Keluarga::with(['desakelurahan.kecamatan.kabupatenkota.provinsi', 'adat'])->findOrFail($id);
        $provinsi = Provinsi::orderBy('nama', 'asc')->get();
        return view('master.keluarga.edit', compact('keluarga', 'provinsi'));
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'kk'                => ['required', 'string', 'min:16', 'max:16'],
            'desa_kelurahan_id' => ['required'],
            'adat_id'           => ['nullable'],
            'file_kk'           => ['nullable', 'file', 'mimes:jpeg,jpg,png,pdf', 'max:2048'],
        ]);

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

        $keluarga = Keluarga::findOrFail($id);
        
        $pathKk = $keluarga->path_kk;
        $fileNameKk = $keluarga->file_kk;

        if ($request->hasFile('file_kk')) {
    
            if ($keluarga->path_kk && Storage::disk('public')->exists($keluarga->path_kk)) {
                Storage::disk('public')->delete($keluarga->path_kk);
            }
     
            $file = $request->file('file_kk');
            $fileNameKk = $file->getClientOriginalName();
            $pathKk = $file->store('uploads/keluarga', 'public');
        }

        $keluarga->update([
            'kk'                => $request->kk,
            'desa_kelurahan_id' => $request->desa_kelurahan_id,
            'adat_id'           => $request->adat_id,
            'path_kk'           => $pathKk,
            'file_kk'           => $fileNameKk,
            'updated_by'        => auth()->id(),
        ]);

        return response()->json(['status' => 'success', 'message' => 'Data Keluarga berhasil diupdate.']);
    }

    public function destroy($id)
    {
        $keluarga = Keluarga::findOrFail($id);
        
        // if ($keluarga->path_kk && Storage::disk('public')->exists($keluarga->path_kk)) {
        //     Storage::disk('public')->delete($keluarga->path_kk);
        // }
        
        $keluarga->update(['deleted_by' => auth()->id()]);
        $keluarga->delete();

        return response()->json(['status' => 'success', 'message' => 'Data Keluarga berhasil dihapus.']);
    }
}