<?php

namespace App\Http\Controllers\Dashboard\Admin;

use App\Models\User;
use App\Enum\UserStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class ProfileController extends Controller
{
    public function index()
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Profile', 'active' => true]
        ];

        $user = User::where('id', Auth::id())->firstOrFail();
        $userStatuses = UserStatus::cases();

        $data = [
            'title' => 'Profile',
            'user' => $user,
            'userStatuses' => $userStatuses,
            'breadcrumbs' => $breadcrumbs
        ];

        return view('dashboard.admin.profile.index', $data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
        ]);

        try {
            $user = User::where('id', Auth::id())->firstOrFail();

            DB::beginTransaction();

            $user->name = $request->name;
            $user->save();

            DB::commit();

            return redirect()->back()->with('success', 'Profile updated successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return redirect()->back()->with('error', 'Failed to update profile.');
        }
    }
}
