<?php

namespace App\Http\Controllers;

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

class ProfileController extends Controller
{
    /**
     * Menampilkan form edit profil
     */
    public function edit()
    {
        $user = Auth::user();
        return view('profile.edit', compact('user'));
    }

    /**
     * Update profil pengguna
     */
    public function update(Request $request)
    {
        $user = Auth::user();

        // Validasi berbeda untuk admin dan customer
        if ($user->role === 'admin') {
            $request->validate([
                'name' => 'required|string|max:255',
                'password' => 'nullable|string|min:8|confirmed',
            ]);

            // Data yang dapat diubah untuk admin
            User::where('id', $user->id)->update([
                'name' => $request->name,
                'email' => $request->email,
                'gender' => $request->gender,
                'phone' => $request->phone
                
            ]);
        } else {
            // Untuk customer
            $request->validate([
                'name' => 'required|string|max:255',
                'password' => 'nullable|string|min:8|confirmed',
                'business_name' => 'required|string|max:255',
                'business_address' => 'required|string',
            ]);

            // Data yang dapat diubah untuk customer
            User::where('id', $user->id)->update([
                'name' => $request->name,
                'business_name' => $request->business_name,
                'business_address' => $request->business_address,
                'phone' => $request->phone,
                'email' => $request->email,
                'gender' => $request->gender
            ]);
        }

        // Update password jika diisi
        if ($request->filled('password')) {
            // Validasi password lama
            $request->validate([
                'current_password' => 'required|string',
            ]);

            // Verifikasi password lama
            if (!Hash::check($request->current_password, $user->password)) {
                return back()
                    ->withErrors(['current_password' => 'Password lama tidak sesuai'])
                    ->withInput();
            }

            User::where('id', $user->id)->update([
                'password' => Hash::make($request->password)
            ]);
        }

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