<?php

namespace App\Http\Controllers;

use App\Models\UserModel;
use Illuminate\Http\Request;

class BiodataController extends Controller
{
    public function index()
    {
        $id = session('userID');
        $data = UserModel::where('id', $id)->first();
        return view('dashboard.biodata.biodata', ['data' => $data]);
    }
    public function update(Request $request)
    {
        $id = session('userID');
        $user = UserModel::find($id);
        if ($request->hasFile('foto')) {
            if ($user->foto != null && file_exists(public_path('storage/user/' . $user->foto))) {
                unlink(public_path('storage/user/' . $user->foto));
            }
            $imageName = time() . '.' . $request->foto->extension();
            $request->foto->move(public_path('storage/user'), $imageName);
            session(['foto' => $imageName]);
            $user->foto = $imageName;
        }
        if ($request->filled('password_now') && md5($request->password_now) != $user->password) {
            // return back()->with('error', 'Password sekarang tidak sama dengan password yang tersimpan');
        }
        $fields = ['name', 'email', 'alamat', 'notelp'];
        foreach ($fields as $field) {
            if ($request->filled($field)) {
                $user->{$field} = $request->{$field};
            }
        }
        if ($request->filled('password')) {
            $user->password = md5($request->password);
        }
        $user->save();
        return redirect()->route('biodata')->with('success', 'Biodata berhasil diperbarui');
    }
}
