<?php

namespace App\Http\Controllers\FrontUser;

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

class UserSettingsController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        return view('FrontUser.settings.index', compact('user'));
    }

    public function updateProfile(Request $request)
    {
        $user = Auth::user();
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $user->id,
            'contact_number' => 'nullable|string|max:20',
            'company_name' => 'nullable|string|max:255',
            'address' => 'nullable|string',
            'website' => 'nullable|url',
            'theme' => 'nullable|in:light,dark',
        ]);
        $user->update($validated);
        return back()->with('status', 'Profile updated');
    }

    public function updateNotifications(Request $request)
    {
        // Persist notification preferences if you have a settings table; placeholder
        return back()->with('status', 'Preferences saved');
    }

    public function updateApi(Request $request)
    {
        // Persist webhook/api key if applicable; placeholder
        return back()->with('status', 'API settings saved');
    }

    public function uploadAvatar(Request $request)
    {
        $request->validate([
            'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png', 'max:2048']
        ]);

        $user = Auth::user();

        if ($user->avatar && (str_starts_with($user->avatar, 'storage/') || str_contains($user->avatar, '/storage/'))) {
            $oldPath = str_replace('storage/', 'public/', $user->avatar);
            Storage::delete($oldPath);
        }

        $path = $request->file('avatar')->store('public/avatars');
        $publicPath = Storage::url($path); // e.g. storage/avatars/...

        $user->avatar = $publicPath;
        $user->save();

        return back()->with('status', 'Avatar updated');
    }

    public function update(Request $request)
    {
        // Update settings logic
    }
}