<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
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 index()
    {
        $user = Auth::user();
        $employee = $user->employee;

        return view('employee.profile.index', compact('user', 'employee'));
    }

    public function update(Request $request)
    {
        $user = Auth::user();
        $employee = $user->employee;

        $validated = $request->validate([
            'phone' => ['nullable', 'string', 'max:20'],
            'address' => ['nullable', 'string'],
            'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg', 'max:2048'],
            'current_password' => ['nullable', 'required_with:new_password', 'current_password'],
            'new_password' => ['nullable', 'min:6', 'confirmed'],
        ]);

        $photoPath = $employee->photo;
        if ($request->hasFile('photo')) {
            $stored = $request->file('photo')->store('employees/photos', 'public');
            $photoPath = 'storage/' . $stored;
        }

        $employee->update([
            'phone' => $validated['phone'],
            'address' => $validated['address'],
            'photo' => $photoPath,
        ]);

        $userData = [
            'avatar' => $photoPath,
        ];

        if (!empty($validated['new_password'])) {
            $userData['password'] = Hash::make($validated['new_password']);
        }

        $user->update($userData);

        AuditLog::log('Update Profil Pribadi', "Karyawan {$employee->name} memperbarui data profil/password");

        return back()->with('success', 'Profil Anda berhasil diperbarui.');
    }
}
