<?php

namespace site;

/** */

class images {

/* Upload image */

public static function upload( $file, $prefix, $etc = array( 'name' => '', 'location' => '', 'current' => '', 'path' => '', 'max_size' => '', 'max_height' => '', 'max_width' => '' ), $delete_old_file = true ) {

    if( !isset( $etc['path'] ) ) $etc['path'] = '';

    if( !isset( $file['tmp_name'] ) ) {

        // check if file is empty, local or external url
        if( empty( $file ) ) {

            return ( isset( $etc['current'] ) ? $etc['current'] : false );

        } else if( filter_var( $file, FILTER_VALIDATE_URL )) {

            // Ensure temp directory exists
            $temp_dir = $etc['path'] . TEMP_LOCATION;
            if( !file_exists( $temp_dir ) ) {
                @mkdir( $temp_dir, 0755, true );
            }
            
            $temp_file = $temp_dir . '/' . uniqid( 'img_' ) . '_' . basename( parse_url( $file, PHP_URL_PATH ) );
            
            // Try file_get_contents first
            $image_data = @file_get_contents( $file );
            
            // If that fails, try cURL
            if( $image_data === false && function_exists( 'curl_init' ) ) {
                $ch = curl_init( $file );
                curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
                curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
                curl_setopt( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' );
                curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
                curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
                curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
                $image_data = curl_exec( $ch );
                curl_close( $ch );
            }
            
            if( $image_data !== false && !empty( $image_data ) ) {
                $ufile['tmp_name'] = $temp_file;
                $ufile['size'] = @file_put_contents( $ufile['tmp_name'], $image_data );
            } else {
                $ufile['tmp_name'] = '';
                $ufile['size'] = 0;
            }

        } else {

            $ufile['tmp_name'] =    $etc['path'] . TEMP_LOCATION . '/' . basename( $file );
            $ufile['size'] = @file_put_contents( $ufile['tmp_name'], file_get_contents( $etc['path'] . $file ) );

        }

        $ufile['name'] = basename( $ufile['tmp_name'] );
        $file = $ufile;

    }

    if( !empty( $etc['location'] ) ) {
        $location = $etc['location'];
    } else {
        $location = UPLOAD_IMAGES_LOC;
    }
    
    // Ensure upload directory exists
    $upload_dir = $etc['path'] . $location;
    if( !file_exists( $upload_dir ) ) {
        @mkdir( $upload_dir, 0755, true );
    }

    if( isset( $file['size'] ) && (int) $file['size'] === 0 ) {

        @unlink( $file['tmp_name'] );

        return ( isset( $etc['current'] ) ? $etc['current'] : false );

    }
    
    // Verify the temp file exists and is readable
    if( empty( $file['tmp_name'] ) || !file_exists( $file['tmp_name'] ) || !is_readable( $file['tmp_name'] ) ) {
        return ( isset( $etc['current'] ) ? $etc['current'] : false );
    }

    $image_info = @getimagesize( $file['tmp_name'] );
    if( $image_info === false ) {
        @unlink( $file['tmp_name'] );
        return ( isset( $etc['current'] ) ? $etc['current'] : false );
    }
    
    list( $width, $height ) = $image_info;

    if( ( !empty( $etc['max_size'] ) && ( $etc['max_size'] * 1024 ) < $file['size'] ) || ( !empty( $etc['max_height'] ) && $etc['max_height'] < $height ) || ( !empty( $etc['max_width'] ) && $etc['max_width'] < $width ) ) {

        if( !empty( $file['tmp_name'] ) ) {
            // delete the temporary file
            @unlink( $file['tmp_name'] );
        }

        return ( !empty( $etc['current'] ) ? $etc['current'] : false ); // It's not a image in standars, size it's too big or filename it's empty. In this case return the current image, if is not set, then return false.

    }

    // Get file extension from name or detect from image data
    $file_ext = \site\utils::get_extension( $file['name'] );
    
    // If no extension in filename, try to detect from image data
    if( empty( $file_ext ) && !empty( $file['tmp_name'] ) && file_exists( $file['tmp_name'] ) ) {
        $image_info = @getimagesize( $file['tmp_name'] );
        if( $image_info !== false ) {
            $mime_to_ext = array(
                'image/jpeg' => '.jpg',
                'image/jpg' => '.jpg',
                'image/png' => '.png',
                'image/gif' => '.gif',
                'image/webp' => '.webp'
            );
            if( isset( $image_info['mime'] ) && isset( $mime_to_ext[$image_info['mime']] ) ) {
                $file_ext = $mime_to_ext[$image_info['mime']];
                $file['name'] = $file['name'] . $file_ext;
            }
        }
    }
    
    if( !\site\utils::file_has_extension( $file['name'], '.jpg,.jpeg,.png,.gif,.webp' ) ) {

        if( !empty( $file['tmp_name'] ) ) {

            // delete the temporary file
            @unlink( $file['tmp_name'] );

        }

        return ( !empty( $etc['current'] ) ? $etc['current'] : false ); // This file has not an allowed extension.

    }

    $new_name = ( !empty( $etc['name'] ) && strtolower( $etc['name'] ) !== 'auto' ) ? $etc['name'] . \site\utils::get_extension( $file['name'] ) : uniqid( $prefix ) . \site\utils::get_extension( $file['name'] );

    $final_path = $etc['path'] . $location . '/' . $new_name;
    $upload_dir = dirname( $final_path );
    
    // Ensure the upload directory exists
    if( !file_exists( $upload_dir ) ) {
        @mkdir( $upload_dir, 0755, true );
    }

    // Copy file to final location on local server
    if( file_exists( $final_path ) || !copy( $file['tmp_name'], $final_path ) ) {

        // delete the temporary file
        @unlink( $file['tmp_name'] );

        return ( !empty( $etc['current'] ) ? $etc['current'] : false );

    }
    
    // Verify the file was copied successfully to local server
    if( !file_exists( $final_path ) || filesize( $final_path ) == 0 ) {
        @unlink( $file['tmp_name'] );
        return ( !empty( $etc['current'] ) ? $etc['current'] : false );
    }

    if( !empty( $etc['current'] ) && $delete_old_file === true ) {
        // delete the temporary file
        @unlink( $etc['path'] . $etc['current'] );
    }

    // delete the temporary file
    @unlink( $file['tmp_name'] );

    return $location . '/' . $new_name;

}

}