<?php

// use App\Models\SmaSmaUsersModel

// if (!defined('BASEPATH'))
//         exit('No direct script access allowed');

use App\Controllers\SmaUnits;
use App\Models\SmaAddressesModel;
use App\Models\SmaCompaniesModel;

/**
 * Writes base64 image into server specific $output_file_path images folder
 *
 * @return bool
 */
function base64_to_png(string $base64_string, string $output_file_path) {

    
    $bin = base64_decode($base64_string);
    
    
    // Load GD resource from binary data
    $im = imageCreateFromString($bin);
    
    if (!$im) {
        return false;
    }
    
    // Specify the location where you want to save the image
    $img_file = $output_file_path;
    
    // Save the GD resource as PNG in the best possible quality (no compression)
    // This will strip any metadata or invalid contents (including, the PHP backdoor)
    // To block any possible exploits, consider increasing the compression level
    imagepng($im, $img_file, 0);
    
    
    return true; 
}


/**
 * Writes base64 image into server specific $output_file_path images folder in .png
 *
 * @return string|bool
 */
function base64_to_selected_format(string $base64_string, string $output_file_path) {


    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    // $base64_string = str_replace(' ','+',$base64_string);
    $bin = base64_decode($base64_string);
    


    // Gather information about the image using the GD library
    $size = getImageSizeFromString($bin);
    // print_r($bin);
    // Check the MIME type to be sure that the binary data is an image
    if (empty($size['mime']) || strpos($size['mime'], 'image/') !== 0) {
        return false;
    }

    // Mime types are represented as image/gif, image/png, image/jpeg, and so on
    // Therefore, to extract the image extension, we subtract everything after the “image/” prefix
    $ext = substr($size['mime'], 6);

    // Make sure that you save only the desired file extensions
    
    if (!in_array($ext, ['png', 'gif', 'jpeg'])) {
        return false;
    }

    // Specify the location where you want to save the image
    $img_file = $output_file_path.'.'.$ext;
    // $file = fopen($img_file, "wb");

    // Save binary data as raw data (that is, it will not remove metadata or invalid contents)
    // In this case, the PHP backdoor will be stored on the server
    // $im = imageCreateFromString($bin);
    // print_r($im);
    // print_r($img_file);
    file_put_contents($img_file, $bin);

    // imagepng($im, $img_file);
    // fwrite($file, $bin);cd
    // fclose($file);

    return $ext;
}

