<?php

namespace App\Services;

use Spatie\Image\Image;

class UploadService
{

    public function __construct()
    {
    }

    public static function upload_image($image)
    {
        // $fp = null;

        // $a = mt_rand(1111, 3333) . ".jpg";
        // $p_upload = Image::load($image->getRealPath());

        // if ($image->getSize() > 1002526) {
        //     $new_width = (40 / 100) * $p_upload->getWidth();
        //     $new_height = (40 / 100) * $p_upload->getHeight();
        // } else {
        //     $new_width = $p_upload->getWidth();
        //     $new_height = $p_upload->getHeight();
        // }

        // $p_upload->width($new_width)->height($new_height)->save(public_path("/$a"));
        // $pic = $image->store("faulty/img");


        // $uploaded = cloudinary()->upload(public_path("/$a"));


        // $res = $uploaded->getResponse();
        // $fp = [
        //     'public_id' => $res['public_id'],
        //     'url' => $res['secure_url'],
        //     'version' => $res['version'],
        //     'format' => $res['format'],
        // ];

        // unlink(public_path("/$a"));

        $fp = null;
        $name = mt_rand(111_111_111, 999_999_999);

        $a = $name . ".jpg";
        $p_upload = $image;

        $pic_path = "/faulty/img/$a";

        $p_upload->storeAs('/faulty/img/', $a);

        $fp = [
            'public_id' => $a,
            'url' => asset($pic_path),
            'version' => 1,
            'format' => '.jpg',
        ];

        return $fp;
    }

    public static function upload_cloudinary($path)
    {
        $uploaded = cloudinary()->upload($path);
        $res = $uploaded->getResponse();
        if ($res) {
            $fp = [
                'public_id' => $res['public_id'],
                'url' => $res['secure_url'],
                'version' => $res['version'],
                'format' => $res['format'],
            ];

            return $fp;
        } else {
            return false;
        }
    }
}
