<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
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([
        'password'              => 'nullable|min:6|confirmed',
        'password_confirmation' => 'nullable',
        'foto_profil'           => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
    ], [
        '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    = [];
    $fotoUrl = null;

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

    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 = '/E31230356/storage/app/public/' . $path;
    }

    if (!empty($data)) {
        $admin->update($data);
    }

    return response()->json([
        'success'  => true,
        'message'  => 'Profil berhasil diperbarui!',
        'foto_url' => $fotoUrl ?? ($admin->foto_profil ? '/E31230356/storage/app/public/' . $admin->foto_profil : null),
    ]);
}
}