<?php
namespace App\Http\Helpers;

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;

class ExcelHandel
{
	function __construct()
	{

	}

	public static function generateFolder($set_path = '')
    {
        $folder = public_path() . $set_path;
        \File::isDirectory($folder) or \File::makeDirectory($folder, 0777, true, true); //check folder is exist
        return $folder;
    }

	public static function insertExcel($path = '', $base64Set = [])
	{
    	$file_info = [];
        $folder_path = ExcelHandel::generateFolder('/share/excels/' . $path);

        foreach ($base64Set as $key => $row) {

	    	$exceldata = $row;
	        $filename = (string) Str::uuid();

	        $f = finfo_open();
	        $mime_type = finfo_file($f, $exceldata, FILEINFO_MIME_TYPE);

	        $extension = 'xls';

	        switch ($mime_type) {
	            case 'application/vnd.ms-excel':
	                $extension = 'xls';
	                break;
	            case 'application/zip':
	                $extension = 'xlsx';
	                break;
	        }

	        if (empty($extension)) {
	            return false;
	        }

	        $exceldata = explode('base64,', $exceldata);
	        $exceldata = base64_decode($exceldata[1]);

	        $filename_with_ext = $filename . '.' . $extension;

	        $file = ExcelHandel::generateExcel($path, $exceldata, $filename, $extension);

	        $file_info[] = [
	            'path' => $path,
	            'filename' => $filename_with_ext,
	            'mime_type' => $mime_type,
	            'extension' => $extension,
	            'file_info' => empty($file) ? [] : $file,
	        ];
    	}

        return $file_info;
	}

	public static function generateExcel($path = '', $exceldata = '', $filename = '', $extension = '')
    {
        $file_info = [];
	    $file = \File::put(public_path('share/excels/' . $path) . '/' . $filename . '.' . $extension, $exceldata);
        $file_info['original']['file'] = public_path('/share/excels/' . $path . '/' . $filename . '.' . $extension);
        $file_info['large']['file'] = public_path('/share/excels/' . $path . '/' . $filename . '.' . $extension);
        $file_info['medium']['file'] = public_path('/share/excels/' . $path . '/' . $filename . '.' . $extension);
        $file_info['small']['file'] = public_path('/share/excels/' . $path . '/' . $filename . '.' . $extension);
        
        return $file_info;
    }

    public static function removeExcel($excel_info = [])
    {
        $excel_info = json_decode(json_encode($excel_info), true);
        foreach ($excel_info as $key => $row) {
        	if (!empty($row['path'])) {
	            \File::delete([$row['file_info']['original']['file']]);
           }
        }
        return true;
    }

}