<?php

namespace App\Http\Controllers\Employee;

use Illuminate\Http\Request;
use Illuminate\Contracts\View\View;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Function\GetAgeController;
use App\Http\Requests\Employee\ProfileUpdateRequest;

class ProfileController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();
        $age = (new GetAgeController())->getAge($user->birth_date);
        $profileCompletion = empty($user->gender) || empty($user->birth_date) || empty($user->address) || empty($user->phone)
            || empty($user->employee->nip) || empty($user->employee->position);

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

    public function edit(Request $request): View
    {
        $user = $request->user();

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

    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $user = $request->user();

        $user->update([
            'name' => $request->name,
            'gender' => $request->gender,
            'birth_date' => $request->birth_date,
            'phone' => $request->phone,
            'address' => $request->address,
        ]);

        if ($request->hasFile('picture')) {
            $filename = time() . '_' . uniqid() . '.' . $request->picture->getClientOriginalExtension();
            $path = $request->picture->storeAs('public/images', $filename);
            $pictureUrl = Storage::url($path);

            $user->picture = $pictureUrl;
            $user->save();
        }

        if ($user->role === 'admin') {
            $employee = $user->employee;

            $employee->update([
                'nip' => $request->nip,
                'position' => $request->position,
            ]);
        }



        return redirect()->route('employee.profile.setting')->with('success', 'Profile updated successfully!');
    }
}
