<?php

namespace App\Http\Controllers\Student;

use App\Models\Department;
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\Student\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->student->nim) || empty($user->student->department_id) || empty($user->student->faculty);

        return view('student.pages.myprofile.index', compact('user', 'age', 'profileCompletion'));
    }

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

        $departments = Department::orderBy('department_name', 'asc')->get();

        return view('student.pages.myprofile.edit', compact('user', 'departments'));
    }

    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 === 'student') {
            $student = $user->student;

            $student->update([
                'nim' => $request->nim,
                'department_id' => $request->department_id,
                'faculty' => $request->faculty,
            ]);
        }



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