<?php

namespace App\Http\Controllers\Web\Ekosistem;

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

class ProfileController extends Controller
{
    public function index(Request $request)
    {
        // Ambil data provinsi untuk kebutuhan dropdown teratas
        $provinsi = Provinsi::orderBy('nama', 'asc')->get();

        // Query untuk tabel dengan fitur search dan pagination
        $query = Profile::with('desakelurahan')->orderBy('created_at', 'desc');

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

        $profiles = $query->paginate($request->per_page ?? 10);

        return view('master.profile.index', compact('profiles', 'provinsi'));
    }

    public function create()
    {
        $provinsi = Provinsi::orderBy('nama', 'asc')->get();
        return view('master.profile.add', compact('provinsi'));
    }
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama'              => ['required', 'string', 'max:255'],
            'email'             => ['required', 'email', 'max:255'],
            'telepon'           => ['required', 'max:13'],
            'desa_kelurahan_id' => ['required'],
            'ktp'               => ['nullable', 'min:16', 'max:16'], 
            'file_ktp'          => ['nullable', 'file', 'mimes:jpeg,jpg,png,pdf', 'max:2048'],
            'kk'                => ['nullable', 'min:16', 'max:16'], 
            'file_kk'           => ['nullable', 'file', 'mimes:jpeg,jpg,png,pdf', 'max:2048'],
        ]);

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

        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'User dengan email tersebut tidak ditemukan'
            ], 404);
        }

        $userid = $user->id;
        $userrole = $user->role;

        $pathktp = null;
        $pathkk  = null;

        if ($request->hasFile('file_ktp')) {
            $pathktp = $request->file('file_ktp')->store('uploads/users/ktp', 'public');
        }

        if ($request->hasFile('file_kk')) {
            $pathkk = $request->file('file_kk')->store('uploads/users/kk', 'public');
        }

        Profile::create([
            'user_id'           => $userid,
            'role'              => $userrole,
            'nama'              => $request->nama,
            'email'             => $request->email,
            'telepon'           => $request->telepon,
            'alamat'            => $request->alamat,
            'kk'                => $request->kk,
            'ktp'               => $request->ktp,
            'desa_kelurahan_id' => $request->desa_kelurahan_id,
            'path_kk'           => $pathkk,
            'path_ktp'          => $pathktp,
            'keluarga_id'       => $request->keluarga_id,
            'created_by'        => auth()->id(),
            'updated_by'        => auth()->id(),
        ]);

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

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

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

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

        $profile = Profile::findOrFail($id);

        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return response()->json([
                'status'  => 'error',
                'message' => 'User dengan email tersebut tidak ditemukan'
            ], 404);
        }

        $pathktp = $profile->path_ktp;
        $pathkk  = $profile->path_kk;

        if ($request->hasFile('file_ktp')) {
            if ($profile->path_ktp && \Storage::disk('public')->exists($profile->path_ktp)) {
                \Storage::disk('public')->delete($profile->path_ktp);
            }
            $pathktp = $request->file('file_ktp')->store('uploads/users/ktp', 'public');
        }

        if ($request->hasFile('file_kk')) {
            if ($profile->path_kk && \Storage::disk('public')->exists($profile->path_kk)) {
                \Storage::disk('public')->delete($profile->path_kk);
            }
            $pathkk = $request->file('file_kk')->store('uploads/users/kk', 'public');
        }

        $profile->update([
            'user_id'           => $user->id,
            'role'              => $user->role,
            'nama'              => $request->nama,
            'email'             => $request->email,
            'telepon'           => $request->telepon,
            'alamat'            => $request->alamat,
            'kk'                => $request->kk,
            'ktp'               => $request->ktp,
            'desa_kelurahan_id' => $request->desa_kelurahan_id,
            'path_kk'           => $pathkk,
            'path_ktp'          => $pathktp,
            'keluarga_id'       => $request->keluarga_id, // Pastikan input ini dikirim dari form, kalau tidak hapus saja
            'updated_by'        => auth()->id(),
        ]);

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

    /**
     * Menghapus data profile (serta file fisiknya)
     */
    public function destroy($id)
    {
        $profile = Profile::findOrFail($id);

        // if ($profile->path_ktp && Storage::disk('public')->exists($profile->path_ktp)) {
        //     Storage::disk('public')->delete($profile->path_ktp);
        // }
        // if ($profile->path_kk && Storage::disk('public')->exists($profile->path_kk)) {
        //     Storage::disk('public')->delete($profile->path_kk);
        // }
        $profile->deleted_by = auth()->user()->id;
        $profile->save();
        $profile->delete();

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