<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\File;

class ProfilController extends Controller
{
    public function index()
    {
        $admin = Auth::user();
        return view('admin.profil', compact('admin'));
    }

    public function update(Request $request)
    {
        $admin = Auth::user();

        $request->validate(
            [
                'name'     => 'required|string|max:255',
                'username' => 'required|string|max:100|unique:users,username,' . $admin->id_users . ',id_users',
                'foto'     => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                'password' => 'nullable|min:6|confirmed',
            ],
            [
                'name.required' => 'Nama wajib diisi',
                'username.required' => 'Username wajib diisi',
                'username.unique' => 'Username sudah digunakan',
                'foto.image' => 'File harus berupa gambar',
                'foto.mimes' => 'Format foto harus JPG atau PNG',
                'foto.max' => 'Ukuran foto maksimal 2 MB',
                'password.min' => 'Password minimal 6 karakter',
                'password.confirmed' => 'Konfirmasi password tidak cocok',
            ]
        );

        // update data dasar
        $admin->name = $request->name;
        $admin->username = $request->username;

        // upload foto
        if ($request->hasFile('foto')) {

            // hapus foto lama
            if ($admin->foto && file_exists(public_path('assets/admin/foto-admin/' . $admin->foto))) {
                unlink(public_path('assets/admin/foto-admin/' . $admin->foto));
            }

            $file = $request->file('foto');
            $namaFoto = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();

            $file->move(public_path('assets/admin/foto-admin'), $namaFoto);

            $admin->foto = $namaFoto;
        }

        // update password jika diisi
        if ($request->filled('password')) {
            $admin->password = Hash::make($request->password);
        }

        $admin->save();

        return redirect()
            ->route('admin.profil')
            ->with('success', 'Profil berhasil diperbarui');
    }
}
