<?php

namespace App\Http\Controllers\V3;

use App\Facades\File\FileFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\Profile\ChangePasswordRequest;
use App\Http\Requests\V3\Profile\EditRequest;
use App\Http\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    use ApiResponse;
    public function info(): JsonResponse
    {
        $user = Auth::user();

        return $this->successResponse([
            'username' => $user->username,
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'name' => $user->name,
            'last_login' => $user->last_login,
            'major' => $user->major,
            'degree' => $user->degree,
            'mobile' => $user->mobile,
            'province_id' => $user->province_id,
            'avatar' => $user->avatarUrl()
        ]);
    }

    public function edit(EditRequest $request): JsonResponse
    {
        $user = Auth::user();

        if ($request->has('avatar'))
        {
            if ($user->avatar) {
                File::delete($user->avatar);
            }

            $destinationPath = 'avatar/' . $user->username;
            $filename = time() .".". $request->file('avatar')->getClientOriginalExtension();
            $request->file('avatar')->storeAs($destinationPath, $filename, 'public');
            $avatar = 'storage/'.$destinationPath ."/". $filename;
        }

        $user->update([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'major' => $request->major,
            'degree' => $request->degree,
            'mobile' => $request->mobile,
            'avatar' => $avatar ?? $user->avatar
        ]);

        return $this->successResponse();
    }

    public function changePassword(ChangePasswordRequest $request): JsonResponse
    {
        $user = Auth::user();

        if (! Hash::check($request->current_password, $user->password))
        {
            return $this->errorResponse(__('messages.incorrect_current_password'));
        }

        $user->update([
            'password' => Hash::make($request->new_password)
        ]);

        return $this->successResponse();

    }

    public function addActivity(Request $request): JsonResponse
    {
        auth()->user()->addActivityComplete($request->activityCode);
        return $this->successResponse();
    }
}
