<?php
/*-----------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*  As Errors In Your Themes
/*  Are Not The Responsibility
/*  Of The DEVELOPERS
/*  @EXTHEM.ES
/*  
/*  Follow Social Media Exthem.es
/*  Youtube : https://www.youtube.com/channel/UCpcZNXk6ySLtwRSBN6fVyLA
/*  Facebook : https://www.facebook.com/groups/exthem.es
/*  Twitter : https://x.com/bangreyblog
/*  Instagram : https://www.instagram.com/exthem.es/
/*  Telegram : https://t.me/exthemes_helps
/*  TikTok : https://www.tiktok.com/@exthemes
/*	More Premium Themes Visit Now On https://exthem.es/
/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit; 
// Silence is golden.
global $opt_themes;

if (!function_exists('RandomAlphaNumeric')) {
	function RandomAlphaNumeric(int $length = 10) 
	{
		$characters 	= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randomString 	= '';
		$max 			= strlen($characters) - 1;
		for ($i = 0; $i < $length; $i++) 
		{
			$randomString .= $characters[mt_rand(0, $max)];
		}
		return $randomString;
	}
} 

if (!function_exists('upload_images_to_wp')) {
    function upload_images_to_wp($image_url, $format = 'png', $name = 'thumbnail'  )
    {
        if (!empty($image_url)) {
            $upload_dir 		= wp_upload_dir();			
            $image_full_name 	= "{$name}." . $format;
            $image_path 		= $upload_dir["path"] . "/" . $image_full_name;
            $fetch_image 		= file_get_contents($image_url);
            $existing_attachment_id = attachment_url_to_postid($upload_dir["url"] . "/" . $image_full_name);

            if ($existing_attachment_id) {
                return $existing_attachment_id;
            } else {
                file_put_contents($image_path, $fetch_image);
                $file_type = wp_check_filetype(basename($image_full_name), null);
                $image_attachment = [
                    "post_mime_type" => $file_type['type'],
                    "post_title" => $image_name,
                    "post_content" => "",
                    "post_status" => "inherit",
                ];
                $image_id = wp_insert_attachment(
                    $image_attachment,
                    $image_path
                );
				
				//if ( ! function_exists( 'download_url' ) ) {
					require_once ABSPATH . 'wp-admin/includes/file.php';
					require_once ABSPATH . 'wp-admin/includes/media.php';
					require_once ABSPATH . 'wp-admin/includes/image.php';
				//}
	
                //require_once ABSPATH . "wp-admin/includes/image.php";
                $image_data = wp_generate_attachment_metadata(
                    $image_id,
                    $image_path
                );
                wp_update_attachment_metadata($image_id, $image_data);
                return $image_id;
            }
        }
    }
}


/**
 * Allow APK files in WordPress media library
 */
if (!function_exists('allow_apk_uploads')) {
add_filter( 'upload_mimes', 'allow_apk_uploads' );
	function allow_apk_uploads( $mimes ) 
	{
		$mimes['apk'] = 'application/vnd.android.package-archive';
		return $mimes;
	}
}

if (!function_exists('allow_apk_filetype_and_ext')) {
/**
 * Fix WordPress sometimes blocking APK even when MIME is allowed
 */
add_filter( 'wp_check_filetype_and_ext', 'allow_apk_filetype_and_ext', 10, 4 );
	function allow_apk_filetype_and_ext( $values, $file, $filename, $mimes ) 
	{
		if ( strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ) === 'apk' ) 
		{
			$values['ext']  = 'apk';
			$values['type'] = 'application/vnd.android.package-archive';
		}
		return $values;
	}
}

/**
 * Allow .ipa files in WordPress
 */

if (!function_exists('allow_ipa_uploads')) {
add_filter( 'upload_mimes', 'allow_ipa_uploads' );
	function allow_ipa_uploads( $mimes ) 
	{
		// Official MIME type for iOS apps
		$mimes['ipa'] = 'application/octet-stream';
		// Some servers/CDNs serve IPA as these types too – accept them all
		$mimes['ipa'] = 'application/iphone';
		$mimes['ipa'] = 'application/x-itunes-ipa';
		return $mimes;
	}
}

if (!function_exists('fix_ipa_filetype')) {
/**
 * Force WordPress to recognize .ipa even if MIME sniff fails
 */
add_filter( 'wp_check_filetype_and_ext', 'fix_ipa_filetype', 99, 4 );
	function fix_ipa_filetype( $data, $file, $filename, $mimes ) 
	{
		$ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );

		if ( $ext === 'ipa' ) 
		{
			$data['ext']  = 'ipa';
			$data['type'] = 'application/octet-stream';
			$data['proper_filename'] = $filename;
		}

		return $data;
	}
}

 
if (!function_exists('upload_remote_file_apk')) {
/**
 * Upload a remote file to the WordPress media library by URL.
 *
 * @param string $file_url     Full URL of the remote file (e.g. https://example.com/image.jpg)
 * @param int    $parent_post_id Optional. Post ID to attach the media to.
 * @return int|WP_Error        Attachment ID on success, WP_Error on failure.
 */
	function upload_remote_file_apk( $file_url, $parent_post_id = 0 ) 
	{

		// 1. Load WordPress core files (only needed if called outside WP context)
		if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) 
		{
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
			require_once( ABSPATH . 'wp-admin/includes/media.php' );
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
		}
		
		// 1. Check by remote URL stored in postmeta (fastest)
		global $wpdb;
		$existing_id = $wpdb->get_var( $wpdb->prepare(
			"SELECT post_id FROM $wpdb->postmeta 
			 WHERE meta_key = '_remote_file_url' 
			 AND meta_value = %s 
			 LIMIT 1",
			$file_url
		) );

		if ( $existing_id ) {
			//if ( is_callable( $progress_callback ) ) {
			//    call_user_func( $progress_callback, 1, 1, 'already_exists' );
			//}
			return (int) $existing_id; // Already uploaded → return ID immediately
		}
		
		// 2. Validate URL
		if ( ! filter_var( $file_url, FILTER_VALIDATE_URL ) ) {
			return new WP_Error( 'invalid_url', 'Invalid file URL.' );
		}

		// 3. Download file to temp directory
		$tmp = download_url( $file_url );
		if ( is_wp_error( $tmp ) ) {
			return $tmp; // contains download error
		}

		// 4. Security checks (MODIFIED)
		$file_array = array(
			'name'     => wp_basename( parse_url( $file_url, PHP_URL_PATH ) ),
			'type'     => wp_check_filetype( $tmp )['type'],
			'tmp_name' => $tmp,
			'error'    => 0,
			'size'     => filesize( $tmp ),
		);

		// Force APK if extension is .apk (in case wp_check_filetype fails)
		// Force correct MIME if extension is .ipa or .apk
		$ext = strtolower( pathinfo( $file_array['name'], PATHINFO_EXTENSION ) );
		if ( $ext === 'ipa' ) {
			$file_array['type'] = 'application/octet-stream';
		} elseif ( $ext === 'apk' ) {
			$file_array['type'] = 'application/vnd.android.package-archive';
		}

		$allowed = get_allowed_mime_types();
		if ( empty( $file_array['type'] ) || ! in_array( $file_array['type'], $allowed, true ) ) {
			@unlink( $tmp );
			return new WP_Error( 'invalid_type', 'File type not allowed: ' . $file_array['type'] );
		}

		// Optional: max size (5 MB)
		//if ( $file_array['size'] > 5 * MB_IN_BYTES ) {
		//    @unlink( $tmp );
		//    return new WP_Error( 'file_too_large', 'File exceeds 5 MB.' );
		//}

		// 5. Handle the upload (sideloading)
		$overrides = array( 'test_form' => false );
		$results   = wp_handle_sideload( $file_array, $overrides );

		if ( isset( $results['error'] ) ) {
			@unlink( $tmp );
			return new WP_Error( 'sideload_failed', $results['error'] );
		}

		$filename = $results['file'];   // Full server path
		$url      = $results['url'];    // Public URL

		// 6. Prepare attachment data
		$attachment = array(
			'post_mime_type' => $results['type'],
			'post_title'     => preg_replace( '/\.[^.]+$/', '', wp_basename( $filename ) ),
			'post_content'   => '',
			'post_status'    => 'inherit',
			'post_parent'    => (int) $parent_post_id,
		);

		// 7. Insert attachment
		$attach_id = wp_insert_attachment( $attachment, $filename, (int) $parent_post_id );
		if ( is_wp_error( $attach_id ) ) {
			@unlink( $filename );
			return $attach_id;
		}

		// 8. Generate metadata & thumbnails
		$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
		wp_update_attachment_metadata( $attach_id, $attach_data );

		return $attach_id; // Success!
	}
}

