<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function update(Request $request)
    {
        $user = $request->user();

        $validated = $request->validate([
            'name'          => 'required|string|max:100',
            'designation'   => 'nullable|string|max:100',
            'avatar'        => 'nullable|image|mimes:jpeg,jpg,png,webp|max:2048',
            'remove_avatar' => 'nullable|boolean',
        ]);

        if ($request->boolean('remove_avatar')) {
            $this->deleteAvatarFile($user->avatar);
            $user->avatar = null;
        } elseif ($request->hasFile('avatar')) {
            $this->deleteAvatarFile($user->avatar);
            $user->avatar = $request->file('avatar')->store("avatars/{$user->id}", 'public');
        }

        $user->name = $validated['name'];
        $user->designation = $validated['designation'] ?? null;
        $user->save();

        return back()->with('success', 'Profile updated successfully.');
    }

    private function deleteAvatarFile(?string $path): void
    {
        if ($path && Storage::disk('public')->exists($path)) {
            Storage::disk('public')->delete($path);
        }
    }
}
