<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once(PATH_MODELS . "corporate_gift/CorporateGiftClass.php");
require_once(PATH_MODELS . "corporate_gift/CorporateGiftDetailClass.php");
require_once(PATH_MODELS . "corporate_gift/CorporateGiftHeaderImageClass.php");
require_once(PATH_MODELS . "corporate_gift/CorporateGiftDeliveryClass.php");
require_once(PATH_MODELS . "corporate_gift/CorporateGiftRecipientClass.php");
require '../vendor/autoload.php';

class CorporateGiftMaster extends GLBase {
	private $type = "" ;
	private $user ;

	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->user) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$this->loadSetting() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			if (!$this->checkSessionTimeout($this->type)) {
				$this->db->close();
				return false;
			}

			switch ($this->type) {
				case Command::CorporateGiftMasterView:
					$this->getView($params) ;
					break ;
                case Command::CorporateGiftMasterListView:
                    $this->getCorporateGiftList($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params);
                    break;
                case REQ_DELETE:
                    $this->deleteCorporateGiftRecord($params);
                    break;
                case "DELETE_COMPANY_PROFILE_LOGO":
                    $this->deleteCompanylogo($params);
                    break;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function getView($params) {
		ob_start() ;
		include (PATH_VIEWS . "corporate_gift/CorporateGiftMasterView.php") ;

        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        $dataReturn=[];
		$dataReturn['htmlContent'] = $var_screen;
        $dataReturn['headTitle']  = "Corporate Gift Master"; ;
		$this->sendJsonResponse(Status::Ok,"Corporate Gift Master Info",$dataReturn,$this->type);
	}

    private function getCorporateGiftList($params) {
        $cls = new CorporateGiftClass($this->db);

        $sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                case "col_name":
                    $orderby = CorporateGiftTable::C_NAME . " " . $sort[1];
                    break;
                case "col_status":
                    $orderby = CorporateGiftTable::C_STATUS . " " . $sort[1];
                    break;
                default:
                    $orderby = CorporateGiftTable::C_NAME . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = CorporateGiftTable::C_NAME . " asc";
        }

        $rows  = $cls->getCorporateGiftList($orderby);
        $lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $list = [
                    "id"        => $row[CorporateGiftTable::C_ID],
                    "name"      => htmlentities($row[CorporateGiftTable::C_NAME]),
                    "status"    => ($row[CorporateGiftTable::C_STATUS] == 1 ? 'Active' : 'Inactive'),
                ];

                array_push($lists, $list);
            }
        }
        $lists = json_encode($lists);

        $this->sendJsonResponse(Status::Ok, "", $lists, $this->type);
    }

    private function addRecord($params) {
        $cls            = new CorporateGiftClass($this->db);
        $clsDetail      = new CorporateGiftDetailClass($this->db);
        $clsDelivery    = new CorporateGiftDeliveryClass($this->db);
        $clsHeaderImage = new CorporateGiftHeaderImageClass($this->db);
        $clsRecipient   = new CorporateGiftRecipientClass($this->db);

        $datas        = array();
        $modifyby     = $_SESSION[SE_USERID];
        $modifydate   = date_create('now')->format('Y-m-d H:i:s');
        $ws           = $_SESSION[SE_REMOTE_IP];
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_NAME, $this->getParam($params, 'name', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_STATUS, $this->getParamInt($params, 'active', 0));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_SUBJECT, $this->getParam($params, 'email_subject', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_CONTENT, $this->getParam($params, 'email_content', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_BUTTON, $this->getParam($params, 'email_button', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_THANKS, $this->getParam($params, 'email_footer', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_CUTOFF_DATE, $this->getParam($params, 'cut_off', NULL_DATE));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_DELIVERY_DATE_FROM, $this->getParam($params, 'date_from', NULL_DATE));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_DELIVERY_DATE_TO, $this->getParam($params, 'date_to', NULL_DATE));

        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_WS_ID, $ws);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_MODIFY_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_CREATE_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_MODIFY_DATE, $modifydate);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_CREATE_DATE, $modifydate);

        try {
            $this->db->beginTran();
            $exist          = $cls->getExistingRecords($this->getParam($params, 'code', ""));
            $item_idx       = [];
            $delivery_idx   = [];
            if (!is_null($exist)) {
                $this->sendJsonResponse(Status::Error, "Corporate gift already exist.", "", $this->type);
            } else {                
                $id = $cls->addRecord($datas);
                if($id > 0){
                    if(isset($params['items'])){
                        $items = json_decode($params['items'], true);
                        foreach($items as $item){
                            $datas_item   = [];
                            $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ID, $id);
                            $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ITEM_NAME,  $item['item_name']);

                            $filename     = 'corporate_gift_item_' . date_create('now')->format('Ymd_hisv');
                            $item_data    = $this->saveCorporateGiftImage($id, $item['item_file_base64'], $item['item_file_ext'], PATH_CORPORATE_GIFT_ITEM, $filename);
                            $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ITEM_IMAGE, str_replace(PATH_CODE,"",$item_data ?? ""));
                            $item_id = $clsDetail->addRecord($datas_item);

                            $data_id             = [];
                            $data_id['idx']      = $item['idx'];
                            $data_id['id']       = $item_id; 
                            $data_id['filename'] = $filename; 
                            array_push($item_idx, $data_id);
                        }
                    }

                    if(isset($params['delivery'])){
                        $deliveries = json_decode($params['delivery'], true);
                        foreach($deliveries as $delivery){
                            $datas_delivery   = [];
                            $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_ID, $id);
                            $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_DATE,  $this->getParam($delivery, 'delivery_date', NULL_DATE));
                            $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_TIME1, $this->getParam($delivery, 'delivery_time1', NULL_DATE));
                            $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_TIME2, $this->getParam($delivery, 'delivery_time2', NULL_DATE));
                            
                            $delivery_id = $clsDelivery->addRecord($datas_delivery);

                            $data_id = [];
                            $data_id['idx'] = $item['idx'];
                            $data_id['id']  = $delivery_id; 
                            array_push($delivery_idx, $data_id);
                        }
                    }

                    if(isset($params['header_images'])){
                        $header_images = json_decode($params['header_images'], true);
                        foreach($header_images as $header_image){
                            $datas_header   = [];
                            $datas_header[] = $this->db->fieldValue(CorporateGiftHeaderImageTable::C_ID, $id);
                            $datas_header[] = $this->db->fieldValue(CorporateGiftHeaderImageTable::C_COMPANY_ID, $header_image['comp_id']);
                            $header_data    = $this->saveCorporateGiftImage($id, $header_image['header_file_base64'], $header_image['header_file_ext'], PATH_CORPORATE_GIFT_HEADER, 'corporate_gift_header_' . $id . $header_image['comp_id']);

                            $datas_header[] = $this->db->fieldValue(CorporateGiftHeaderImageTable::C_IMAGE_PATH, str_replace(PATH_CODE,"",$header_data ?? ''));

                            $clsHeaderImage->addRecord($datas_header);
                        }
                    }

                    if(isset($params['recipient'])){
                        $recipients = json_decode($params['recipient'], true);
                        foreach($recipients as $recipient){
                            $datas_recipient    = [];
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_ID, $id);
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_CUSTOMER_ID, $recipient['customer_id']);
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_CONTACT_ID, $recipient['contact_id']);
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_GIFT_AMOUNT, $this->getParamInt($recipient, 'gift_amt', 0));

                            $clsRecipient->addRecord($datas_recipient);
                        }
                    }
                }
                $content['id']       = $id;
                $content['item']     = $item_idx;
                $content['delivery'] = $delivery_idx;
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok, "Successfully inserted into system", $content, $this->type);
            }
        } catch (Exception $e) {
            $this->db->rollbackTran() ;	
            Log::write('[CorporateGift]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error, "Sorry, there is a error in database operation.", "", $this->type);
        }
        unset($cls);
    }

    private function updateRecord($params) {
        $cls            = new CorporateGiftClass($this->db);
        $clsDetail      = new CorporateGiftDetailClass($this->db);
        $clsDelivery    = new CorporateGiftDeliveryClass($this->db);
        $clsHeaderImage = new CorporateGiftHeaderImageClass($this->db);
        $clsRecipient   = new CorporateGiftRecipientClass($this->db);

        $datas                      = array();
        $item_list_id               = array();
        $delivery_list_id           = array();
        $recipient_list_id          = array();
        $existing_item_list_id      = array();
        $existing_delivery_list_id  = array();
        $existing_recipient_list_id = array();
        $modifyby                   = $_SESSION[SE_USERID];
        $modifydate                 = date_create('now')->format('Y-m-d H:i:s');
        $ws                         = $_SESSION[SE_REMOTE_IP];

        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_NAME, $this->getParam($params, 'name', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_STATUS, $this->getParamInt($params, 'active', 0));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_SUBJECT, $this->getParam($params, 'email_subject', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_CONTENT, $this->getParam($params, 'email_content', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_BUTTON, $this->getParam($params, 'email_button', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_EMAIL_THANKS, $this->getParam($params, 'email_footer', ''));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_CUTOFF_DATE, $this->getParam($params, 'cut_off', NULL_DATE));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_DELIVERY_DATE_FROM, $this->getParam($params, 'date_from', NULL_DATE));
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_DELIVERY_DATE_TO, $this->getParam($params, 'date_to', NULL_DATE));

        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_WS_ID, $ws);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_MODIFY_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_CREATE_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_MODIFY_DATE, $modifydate);
        $datas[] = $this->db->fieldValue(CorporateGiftTable::C_CREATE_DATE, $modifydate);

        try {
            $this->db->beginTran();
            $exist  = $cls->getExistingRecords($this->getParam($params, 'code', ""), $params['id']);
            if (!is_null($exist)) {
                $this->sendJsonResponse(Status::Error, "Corporate gift already exist.", "", $this->type);
            } else {                
                $id = $params['id'];
                $cls->updateRecord($id,$datas);
                if(isset($params['items'])){
                    $items = json_decode($params['items'], true);
                    foreach($items as $item){
                        $datas_item = [];
                        
                        $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ID, $id);
                        $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ITEM_NAME,  $item['item_name']);

                        $filename     = 'corporate_gift_item_' . date_create('now')->format('Ymd_hisv');
                        $item_data    = $this->saveCorporateGiftImage($id, $item['item_file_base64'], $item['item_file_ext'], PATH_CORPORATE_GIFT_ITEM, $filename);
                        $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ITEM_IMAGE, str_replace(PATH_CODE,"",$item_data ?? ""));
                        $item_id = $clsDetail->addRecord($datas_item);

                        $data_id             = [];
                        $data_id['idx']      = $item['idx'];
                        $data_id['id']       = $item_id; 
                        $data_id['filename'] = $filename; 
                        array_push($item_list_id, $data_id);
                    }
                }
                if(isset($params['items_existing'])){
                    $items_exist = json_decode($params['items_existing'], true);
                    foreach($items_exist as $item_exist){                        
                        $datas_item = [];
                        if($item_exist['item_file_base64']  != "" && $item_exist['item_filename'] != ""){
                            $item_data    = $this->saveCorporateGiftImage($id, $item_exist['item_file_base64'], $item_exist['item_file_ext'], PATH_CORPORATE_GIFT_ITEM, $item_exist['item_filename']);
                            $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ITEM_IMAGE, str_replace(PATH_CODE,"",$item_data ?? ""));
                        }
                        $datas_item[] = $this->db->fieldValue(CorporateGiftDetailTable::C_ITEM_NAME,  $item_exist['item_name']);
                        $clsDetail->updateRecord($item_exist['item_id'], $datas_item);
                        $data_id             = [];
                        $data_id['idx']      = $item_exist['idx'];
                        $data_id['id']       = $item_exist['item_id']; 
                        $data_id['filename'] = $item_exist['item_filename']; 
                        array_push($item_list_id, $data_id);
                    }

                    //id of all item existing in database
                    $rows = $clsDetail->getCorporateGiftDetailByGiftID($id);
                    if(!is_null($rows) && count($rows) > 0){
                        foreach($rows as $row){
                            array_push($existing_item_list_id, $row[CorporateGiftDetailTable::C_DETAIL_ID]);
                        }
                    }

                    //id of all item currently exiting on screen
                    $current_items_id = [];
                    if(!is_null($item_list_id) && count($item_list_id) > 0){
                        foreach($item_list_id as $item_id){
                            array_push($current_items_id, $item_id['id']);
                        }
                    }

                    //compare the 2 array and delete item that is in db but not on screen
                    $deleted_items = array_diff($existing_item_list_id, $current_items_id);
                    if(!is_null($deleted_items) && count($deleted_items) > 0){
                        $clsDetail->deleteCorporateGiftDetailByDetailID($deleted_items, $id);
                    }

                }
                if(!isset($params['items']) && !isset($params['items_existing'])){
                    $clsDetail->deleteCorporateGiftDetailByGiftID($id);
                }
                
                $clsDelivery->deleteCorporateGiftDeliveryByGiftID($id);
                if(isset($params['delivery'])){
                    $deliveries = json_decode($params['delivery'], true);
                    foreach($deliveries as $delivery){
                        $datas_delivery = [];
                        
                        $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_ID, $id);
                        $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_DATE, $this->getParam($delivery, 'delivery_date', NULL_DATE));
                        $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_TIME1, $this->getParam($delivery, 'delivery_time1', ''));
                        $datas_delivery[] = $this->db->fieldValue(CorporateGiftDeliveryTable::C_TIME2, $this->getParam($delivery, 'delivery_time2', ''));
                        $delivery_id = $clsDelivery->addRecord($datas_delivery);

                        $data_id        = [];
                        $data_id['idx'] = $delivery['idx'];
                        $data_id['id']  = $delivery_id; 
                        array_push($delivery_list_id, $data_id);
                    }
                }

                $exist_header = $clsHeaderImage->getCompanyIDHaveHeaderImage($id) ?? [];
                if(isset($params['header_images'])){
                    $header_images = json_decode($params['header_images'], true);
                    foreach($header_images as $header_image){
                        if(!in_array($header_image['comp_id'], $exist_header)){
                            $datas_header   = [];                        
                            $header_data    = $this->saveCorporateGiftImage($id, $header_image['header_file_base64'], $header_image['header_file_ext'], PATH_CORPORATE_GIFT_HEADER, 'corporate_gift_header_' . $id . $header_image['comp_id']);
                            $datas_header[] = $this->db->fieldValue(CorporateGiftHeaderImageTable::C_ID, $id);
                            $datas_header[] = $this->db->fieldValue(CorporateGiftHeaderImageTable::C_COMPANY_ID, $header_image['comp_id']);
                            $datas_header[] = $this->db->fieldValue(CorporateGiftHeaderImageTable::C_IMAGE_PATH, str_replace(PATH_CODE,"",$header_data ?? ''));
                            $clsHeaderImage->addRecord($datas_header);
                        }else{
                            if($header_image['header_file_base64'] != "" && $header_image['header_filename'] != ""){
                                $header_data    = $this->saveCorporateGiftImage($id, $header_image['header_file_base64'], $header_image['header_file_ext'], PATH_CORPORATE_GIFT_HEADER, 'corporate_gift_header_' . $id . $header_image['comp_id']);
                                $clsHeaderImage->updateHeaderImageByCompIDAndGiftID(str_replace(PATH_CODE,"",$header_data ?? ''), $id, $header_image['comp_id']);
                            }
                        }
                    }
                }

                $rowsRecipient = $clsRecipient->getRecipientByGiftID($id);
                foreach($rowsRecipient as $rowRecipient){
                    array_push($existing_recipient_list_id, $rowRecipient[CorporateGiftRecipientTable::C_CUSTOMER_ID] . "_" . $rowRecipient[CorporateGiftRecipientTable::C_CONTACT_ID]);
                }

                if(isset($params['recipient'])){
                    $recipients = json_decode($params['recipient'], true);
                    foreach($recipients as $recipient){
                        $recipient_id = $recipient['customer_id'] . "_" . $recipient['contact_id'];
                        if(!in_array($recipient_id, $existing_recipient_list_id)){
                            $datas_recipient    = [];
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_ID, $id);
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_CUSTOMER_ID, $recipient['customer_id']);
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_CONTACT_ID, $recipient['contact_id']);
                            $datas_recipient[]  = $this->db->fieldValue(CorporateGiftRecipientTable::C_GIFT_AMOUNT, $this->getParamInt($recipient, 'gift_amt', 0));

                            array_push($recipient_list_id, $recipient_id);
                            $clsRecipient->addRecord($datas_recipient);
                        }else{
                            array_push($recipient_list_id, $recipient_id);
                            $clsRecipient->updateRecipient($recipient['customer_id'], $recipient['contact_id'], $this->getParamInt($recipient, 'gift_amt', 0), $id);
                        }
                    }
                    $clsRecipient->deleteRecipient(array_diff($existing_recipient_list_id, $recipient_list_id), $id);
                }else{
                    $clsRecipient->deleteRecipient(array_diff($existing_recipient_list_id, $recipient_list_id), $id);
                }
            }
            $content                = [];
            $content['item_id']     = $item_list_id;
            $content['delivery_id'] = $delivery_list_id;
            $this->db->commitTran();
            $this->sendJsonResponse(Status::Ok, "Successfully updated into system", $content, $this->type);
        } catch (Exception $e) {
            $this->db->rollbackTran() ;	
            Log::write('[CorporateGift]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error, "Sorry, there is a error in database operation.", "", $this->type);
        }
        unset($cls);
    }

    private function deleteCorporateGiftRecord($params) {
        $cls        = new CorporateGiftClass($this->db);
        $clsDetail  = new CorporateGiftDetailClass($this->db);
        $clsHeader  = new CorporateGiftHeaderImageClass($this->db);

        $id =  $this->getParamInt($params, 'id', 0);
        if ($id == 0) {
            $this->sendJsonResponse(Status::Error, "Invalid ID.", "", $this->type);
            return;
        }
        try {
            $this->db->beginTran();

            $cls->deleteRecord($id);
            $clsDetail->deleteCorporateGiftDetailByGiftID($id);
            $clsHeader->deleteCorporateGiftHeaderImageByGiftID($id);
            if($id != ""){//to prevent accidentaly deletion of the whole folder
                $this->deleteFolder(PATH_CORPORATE_GIFT_ITEM . $id);
            }

            $this->db->commitTran();
            $this->sendJsonResponse(Status::Ok, "Successfully delete corporate gift from system.", "", $this->type);
            return;
        } catch (Exception $e) {
            $this->db->rollbackTran() ;
            if($e->getMessage() == Message::DB_ERR_DELETE_USED){
                $this->sendJsonResponse(Status::Error, Message::DB_ERR_DELETE_USED,"",$this->type);
            }else{
                Log::write('[CorporateGift] ' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting corporate gift from the system.","",$this->type);
            }
            return;
        }

        unset($cls);
    }

    public function saveCorporateGiftImage($id, $base64file, $extension, $image_path, $image_name)
    {
		$newfile = "";
        if($base64file!="" || $base64file!=null){
            $path = $image_path . $id . "/";
            $newfile = $image_name.".".$extension;

            if (!file_exists($path)) {
                mkdir($path, 1777, true);
            }
            if (file_exists($path.$newfile)) {
                if (file_exists($path.$newfile))
                    unlink($path.$newfile) ;
            }

            $data= $base64file;
            $type= $extension;
            if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
                $data = substr($data, strpos($data, ',') + 1);
                $type = strtolower($type[1]); // jpg, png, gif

                if (!in_array($type, [ 'jpg', 'jpeg', 'png' ])) {
                    Log::write('invalid image type');
					$mesg = "invalid image type";
                    return "";
                }
                $data = str_replace( ' ', '+', $data );
                $data = base64_decode($data);

                if ($data === false) {
                    Log::write('base64_decode failed');
					$mesg = "base64_decode failed.";
                    return "";
                }

                file_put_contents($path . $newfile, $data);
            } else {
                Log::write('did not match data URI with image data');
				$mesg = "did not match data URI with image data.";
                return "";
            }
            try {
                return  $path . $newfile ;
            } catch (Exception $e){
                Log::write('[attachment]' . $e->getMessage());
				$mesg = $e->getMessage();
				throw new Exception($mesg, 1);
            }
        }
	}

    private function deleteCompanylogo($params)
	{
        $path = PATH_CODE.$params['path'];

        if (file_exists($path))
				unlink($path) ;

		$assetpicturepath = "../web/picture/default/default.png";
		$data=[];
		$data['src'] = $assetpicturepath;

		$this->sendJsonResponse(Status::Ok,"Picture successfully removed from the system.",$data,$this->type) ;
	}

    function deleteFolder($path) {
        if (!is_dir($path)) {
            return false;
        }

        $files = array_diff(scandir($path), ['.', '..']);

        foreach ($files as $file) {
            $fullPath = $path . DIRECTORY_SEPARATOR . $file;

            if (is_dir($fullPath)) {
                $this->deleteFolder($fullPath);
            } else {
                unlink($fullPath);
            }
        }

        return rmdir($path);
    }
}
