<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    public function index()
    {
        $user = Auth::user()->load('profile');

        $words = explode(" ", $user->name);
        $initials = "";
        if (count($words) >= 2) {
            $initials = mb_substr($words[0], 0, 1) . mb_substr($words[1], 0, 1);
        } else {
            $initials = mb_substr($user->name, 0, 2);
        }

        return view('profile.index', [
            'user' => $user,
            'initials' => strtoupper($initials)
        ]);
    }

    // Form edit
    public function edit()
    {
        $user = Auth::user()->load('profile');
        return view('profile.edit', compact('user'));
    }

    // Simpan edit
    public function update(Request $request)
{
    $user = Auth::user();

    $validated = $request->validate([
        'name'         => 'required|string|max:255',
        'phone_number' => 'required|string|max:20',
        'address'      => 'nullable|string|max:500',
        'foto_profil'  => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
    ]);

    $user->update(['name' => $validated['name']]);

    $profileData = [
        'phone_number' => $validated['phone_number'],
        'address'      => $validated['address'],
    ];

    if ($request->hasFile('foto_profil')) {
        // Hapus foto lama
        if ($user->profile && $user->profile->foto_profil) {
            \Storage::disk('public')->delete($user->profile->foto_profil);
        }
        $path = $request->file('foto_profil')->store('profil_images', 'public');
        $profileData['foto_profil'] = $path;
    }

    $user->profile()->updateOrCreate(['user_id' => $user->id], $profileData);

    return redirect()->route('profile.index')->with('success', 'Profil berhasil diperbarui!');
    }

    // Form ganti password
    public function editPassword()
    {
        return view('profile.password');
    }

    // Simpan ganti password
    public function updatePassword(Request $request)
    {
        $user = Auth::user();

        $validated = $request->validate([
            'current_password' => 'required',
            'new_password'     => 'required|string|min:8|confirmed',
        ]);

        if (!Hash::check($validated['current_password'], $user->password)) {
            return back()->with('error', 'Password saat ini salah.');
        }

        $user->update(['password' => Hash::make($validated['new_password'])]);

        return redirect()->route('profile.index')->with('success', 'Password berhasil diganti!');
    }
}