<?php

namespace App\Http\Controllers\Profile;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Profile\UserProfilePicture;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;


class UserProfilePictureController extends Controller
{
    public function create(Request $request)
    {

        $valid = Validator::make($request->all(), [
            'photo' => 'file|mimes:jpg,jpeg,png' 
        ]);

        if($valid->fails()){
            return response()->json([
                'message' => $valid->errors()
            ], 400);
        }

        DB::beginTransaction();

        try {
            $imgPath = Storage::disk('profile')->put(Auth::id(), $request->file('photo'));
            $tmpPath = Storage::disk('local')->put('tmp-profile/' . Auth::id(), $request->file('photo'));
            $newImage = Image::make(storage_path('app/' . $tmpPath))->resize(180, 180)->save(storage_path('app/' . $tmpPath), 80);
            Storage::disk('profile')->put($imgPath, $newImage);
            $userProfilePicture = UserProfilePicture::where('user_id', Auth::id())->first();
            UserProfilePicture::updateOrCreate(
                ['user_id' => Auth::id()],
                [
                    'user_id' => Auth::id(),
                    'path' => $imgPath,
                ]
            );
            if ($userProfilePicture) {
                Storage::disk('profile')->delete($userProfilePicture->path);
            }
            Storage::disk('local')->deleteDirectory(dirname($tmpPath));
            DB::commit();
            return response()->json([
                'text' => 'Profile Picture has been created or updated.'
            ]);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json([
                'errors' => ['There is a problem in creating or updating Profile Picture.'],
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function delete(Request $request)
    {

        $userProfilePictureQuery = UserProfilePicture::where([
            ['user_id', Auth::id()],
            ['path', $request->path]
        ]);
        Storage::disk('profile')->delete($userProfilePictureQuery->first()->path);
        $userProfilePictureQuery->delete();

        return response()->json([
            'text' => 'Profile Picture has been deleted'
        ]);
    }

    public function fetchProfilePicture(Request $request)
    {
        return Storage::disk('profile')->download($request->path);
    }
}
