<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UserPhotoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $response = User::findOrFail($id);
            if (!empty($request->foto)) {
                $uploadFolder = 'user-photo';
                $image = $request->file('foto');
                $image_uploaded_path = $image->store($uploadFolder, 'public_uploads');
                $uploadedImageResponse = array(
                    "image_name" => basename($image_uploaded_path),
                    "image_url" => Storage::disk('public_uploads')->url($image_uploaded_path),
                    "mime" => $image->getClientMimeType()
                );
                $namafile = $uploadedImageResponse['image_name'];
            }
            $response->update([
                'foto' => $namafile
            ]);
            return response()->json([
                'foto' => $namafile,
                'success' => true,
                'message' => 'success'
            ]);
        } catch(\Exception $e) {
            return response()->json([
                'message' => 'Err',
                'errors' => $e -> getMessage()
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
