<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use App\Models\User;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Inertia\Inertia;
use Inertia\Response;

class ProfileController extends Controller
{
    public function edit(Request $request): Response
    {
        // $user = User::all();
        return Inertia::render('Profile/Profile');
    }
    public function updateProfile(Request $request, $id)
    {
        $request->validate([
            'password' => 'nullable',
            'nama' => 'required',
            'alamat' => 'required',
            'jk' => 'required',
            'tanggal_lahir' => 'required|date',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ], [
            'nama.required' => 'wajib mengisi nama santri',
            'alamat.required' => 'wajib mengisi alamat santri',
            'jk.required' => 'wajib mengisi gender',
            'tanggal_lahir.required' => 'wajib mengisi tanggal lahir santri',
            'tanggal_lahir.date' => 'tanggal lahir harus dalam format tanggal yang benar',
        ]);

        $santri = User::findOrFail($id);
        try {

            $updateData = [
                'nama' => $request->nama,
                'alamat' => $request->alamat,
                'jk' => $request->jk,
                'tanggal_lahir' => $request->tanggal_lahir,
            ];

            if ($request->hasFile('foto')) {
                if ($santri->foto && File::exists(public_path($santri->foto))) {
                    File::delete(public_path($santri->foto));
                }

                $foto = $request->file('foto');
                $fotoName = time() . '_' . $foto->getClientOriginalName();
                $foto->move(public_path('fotoSantri'), $fotoName);
                $updateData['foto'] = 'fotoSantri/' . $fotoName;
            }
            if ($request->filled('password')) {
                $updateData['password'] = Hash::make($request->password);
            }

            // dd($updateData);
            // return $updateData;

            $santri->update($updateData);

            return redirect()->back()->with('success', 'Data Berhasil Diubah');
        } catch (\Throwable $th) {
            return redirect()->back()->with('error', 'Gagal memperbarui data: ' . $th->getMessage());
            // return $th->getMessage();
        }
    }
}
