<?php

namespace App\Trait;

use Illuminate\Http\UploadedFile;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Illuminate\Support\Facades\File;



trait FileManagement
{



    // public function uploadFile(UploadedFile $file, string $directory = '/uploads/default_uploads'): string {
        public function uploadFile(UploadedFile $file, string $directory): string
        {

            // dd($directory);
            // $filename = 'company_' . uniqid() . '.' . $file->getClientOriginalExtension();
            //     $extension = $file->getClientOriginalExtension();

          $filename =  $file->getClientOriginalName();
        //   dd( $filename);
            //move the file to storage
            $file->move(public_path($directory), $filename);

         //  dd($directory . '/' . $filename, $filename);
            return $directory . '/' . $filename;
        }


        public function deleteFile(?string $path): bool
        {
            if (File::exists(public_path($path))) {
                File::delete(public_path($path));
                return true;
            }
            return false;
        }





        public function uploadImageFile(UploadedFile $image_file, string $directory): string
        {

            //declare new resize image path
            $resizedDirectory = $directory . '/thumbnails';
//dd($resizedDirectory );
          //provide as temp_path
            $path = public_path($resizedDirectory);

            // check if the path exists, else create the path
            if (!File::isDirectory($path)) {
                File::makeDirectory($path, 0777, true, true);
            }

            //Generate a unique name
            $gen_image_filename = 'company_' . uniqid() . '.' . $image_file->getClientOriginalExtension();

            //move the file to storage
            ///  $image_file->move(public_path($directory),   $gen_image_filename);
            $image_file->move($directory, $gen_image_filename);


            // create image manager instance with desired driver
            $imgManager = new ImageManager(new Driver());

            // read image from file system
            $thumbImage = $imgManager->read($directory . '/' . $gen_image_filename);


            // Resize Image;
            $thumbImage->resize(350, 350);


            // Store Resized Image in jpeg format;
            $thumbImage->toJpeg(80)->save(public_path($resizedDirectory . '/' . $gen_image_filename));

//dd($resizedDirectory . '/' . $gen_image_filename);
            //return the final saved directory
            return $resizedDirectory . '/' . $gen_image_filename;
        }


        public function deleteImageFile(?string $path): bool
        {
            // dd('delet listening' , $path);
            if (File::exists(public_path($path))) {
                File::delete(public_path($path));
                return true;
            }
            return false;
        }





}
