<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    public function index()
    {
        $user = User::all();
        return view('user', compact('user'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6',
            'role' => 'required',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048', // Sesuai dengan nama kolom di database
            'status' => 'required',
        ]);

        // Data awal tanpa gambar
        $data = [
            'nama' => $request->nama,
            'email' => $request->email,
            'password' => Hash::make($request->password), // Gunakan Hash untuk keamanan
            'role' => $request->role,
            'status' => $request->status,
        ];

        if ($request->hasFile('image')) {
            $foto = $request->file('image');

            // Format nama file: nama_user.ekstensi
            $namaBersih = preg_replace('/[^A-Za-z0-9\-]/', '_', $request->nama);
            $ekstensi = $foto->getClientOriginalExtension();
            $namaFoto = $namaBersih . '.' . $ekstensi;

            // Path lengkap untuk penyimpanan
            $path = public_path('upload/user/');

            // Hapus file lama jika sudah ada dengan nama yang sama
            if (file_exists($path . $namaFoto)) {
                unlink($path . $namaFoto);
            }

            $foto->move($path, $namaFoto);
            $data['image'] = $namaFoto; // Simpan path relatif
        }

        // Debugging sebelum simpan ke database
        //dd($data);

        // Simpan ke database
        User::create($data);

        return redirect()->back()->with('success', 'Data berhasil disimpan!');
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'nama' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'role' => 'required|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $user = User::findOrFail($id);

        // Update data user
        $user->nama = $request->nama;
        $user->email = $request->email;
        $user->role = $request->role;
        $user->status = $request->status;

        // Jika ada file foto baru yang di-upload
        if ($request->hasFile('image')) {
            $file = $request->file('image');

            // Dapatkan ekstensi file asli
            $extension = $file->getClientOriginalExtension();

            // Buat nama file berdasarkan nama user
            $fileName = str_replace(' ', '_', $user->nama) . '.' . $extension;

            // Pindahkan file ke folder tujuan
            $file->move(public_path('upload/user'), $fileName);

            // Hapus foto lama jika ada
            if ($user->image && file_exists(public_path('upload/user/' . $user->image))) {
                unlink(public_path('upload/user/' . $user->image));
            }

            // Simpan nama file foto ke database
            $user->image = $fileName;
        }

        $user->save();

        return redirect()->back()->with('success', 'Data user berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();

        return response()->json(['success' => true]);
    }
}
