<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\PostCollection;
use App\Http\Resources\UserResource;
use App\Models\Post;
use App\Models\User;
use App\Traits\HttpResponses;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class APIUserProfileController extends Controller
{
    protected $limit = 12;

    use HttpResponses;

    public function index()
    {
        //
    }

    public function update(Request $request)
    {
        $attrs = $request->validate([
            'name' => 'required',
            'phone' => 'nullable',
            'bio' => 'nullable',
        ]);

        $profile = User::find(Auth::id());
        if(!$profile){
            return $this->error(data: null, message: 'Not Found', code: 404);
        }
        $profile->update($attrs);
        return $this->success(
           data: $profile,
            message: 'user has been updated successfully');
    }

    public function uploadImageProfile(Request $request)
    {
        $request->validate([
            'image' => 'required',
            'image.*' => 'mimes:jpeg,jpg,png,gif,csv,txt,pdf|max:2048'
        ]);

        $user = User::find(Auth::id());
        if (!$user) {
            return $this->abort();
        }

        if ($request->hasfile('image')) {
            try{
                $name = $request['image']->getClientOriginalName();
                $hostwithHttp = request()->getSchemeAndHttpHost();
                $request['image']->move(public_path() . '/images/profiles/', $name);   //move files
                $path = $hostwithHttp . '/images/profiles/' . $name;     //set path
                $user->update([
                    'image_url' => $path,
                ]);
            }catch(\Exception $e){
                return $this->error(
                    data: null,
                    message: 'Profile image has not been uploaded',
                    code: 400);
            }

        }else{
            return  $this->abort();
        }

        return $this->success(
            data: $path,
            message: 'Profile image has been uploaded successfully',
        );
    }

    public function destroy($id)
    {
        //
    }

    public function profile()
    {
        $user = Auth::user();
        return new UserResource($user);
    }

    public function getPosts($offset = 1){
        $posts = Post::where('user_id', Auth::id())
                        ->where('status',true)
                        ->orderBy('id','DESC')
                        ->limit(24)->get();
                        // ->paginate($this->limit, ['*'], 'page', $offset)->items();
        return new PostCollection($posts);
    }

    public function logout()
    {
        $user = User::findOrFail(Auth::id());
        $user->tokens()->delete();

        return $this->success(
            null, 'You have succesfully been logged out and your token has been removed', 200
        );
    }
}
