<?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\Storage;

class ProfileController extends Controller
{
    public function edit()
    {
        $admin = Auth::guard('admin')->user();
        return view('admin.profile.edit', compact('admin'));
    }

    public function updateAjax(Request $request)
    {
        $admin = Auth::guard('admin')->user();

        $request->validate([
            'username'              => 'required|string|max:100|unique:admins,username,' . $admin->id_admin . ',id_admin',
            'password'              => 'nullable|min:6|confirmed',
            'password_confirmation' => 'nullable',
            'foto_profil'           => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
        ], [
            'username.required'  => 'Username wajib diisi.',
            'username.unique'    => 'Username sudah digunakan.',
            'password.min'       => 'Password minimal 6 karakter.',
            'password.confirmed' => 'Konfirmasi password tidak cocok.',
            'foto_profil.image'  => 'File harus berupa gambar.',
            'foto_profil.max'    => 'Ukuran foto maksimal 2MB.',
        ]);

        $data = ['username' => $request->username];

        if ($request->filled('password')) {
            $data['password'] = Hash::make($request->password);
        }

        $fotoUrl = null;
        if ($request->hasFile('foto_profil')) {
            if ($admin->foto_profil && Storage::disk('public')->exists($admin->foto_profil)) {
                Storage::disk('public')->delete($admin->foto_profil);
            }
            $path = $request->file('foto_profil')->store('foto_profil/admin', 'public');
            $data['foto_profil'] = $path;
            $fotoUrl = Storage::url($path);
        }

        $admin->update($data);

        return response()->json([
            'success'    => true,
            'message'    => 'Profil berhasil diperbarui!',
            'foto_url'   => $fotoUrl ?? ($admin->foto_profil ? Storage::url($admin->foto_profil) : null),
            'username'   => $admin->fresh()->username,
        ]);
    }
}