<?php

if ( !defined( 'ABSPATH' ) ) {
	exit;
}

add_action( 'pre_get_posts', 'ova_doc_post_per_page_archive' );
function ova_doc_post_per_page_archive( $query ) {

	if ( ( is_post_type_archive( array( 'ova_doc' ) )  && !is_admin() )  || ( is_tax('cat_doc') && !is_admin() )  ) {

		if( $query->is_post_type_archive( 'ova_doc' ) || $query->is_tax('cat_doc') ) {
			$query->set('post_type', array( 'ova_doc' ) );
			$query->set('posts_per_page', get_theme_mod( 'ova_doc_total_record', 8 ) );
		}
	}
	return $query;
}

function get_category_doc_by_id_doc( $id_doc = '' ){

	if( $id_doc === '' ) return;

	$cat_docs = get_the_terms( $id_doc, 'cat_doc' );
	$i = 0;

	if( ! empty( $cat_docs ) ){
		$count_cat = count( $cat_docs );
		?>
		<span class="separator-in doc-meta-general">
			<?php esc_html_e( '- In', 'ova-doc' ) ?>
		</span>
		<?php
		foreach ($cat_docs as $cat_doc) {
			$i++;
			$separator = ( $count_cat !== $i ) ? "," : "";

			$link = get_term_link($cat_doc->term_id);
			$name = $cat_doc->name;
			?>
				<span class="cat-doc">
					<a href="<?php echo esc_url( $link ) ?>"><?php echo esc_html( $name ) ?></a>
				</span>
				<span class="separator">
					<?php echo esc_html( $separator ) ?>
				</span>

			<?php
		}
	}
}

function ova_doc_get_icon_attachment_file( $ext_file = '' ){
	if( $ext_file == '' ) return '<i class="flaticon-file-2"></i>';

	if( $ext_file === 'docx' || $ext_file === 'doc' ){
		$icon = '<i class="flaticon-document"></i>';
	} elseif( $ext_file === 'jpg' || $ext_file === 'gif' || $ext_file === 'png' ){
		$icon = '<i class="flaticon-image-file"></i>';
	} elseif( $ext_file === 'pdf' ){
		$icon = '<i class="flaticon-pdf-2"></i>';
	} else{
		$icon = '<i class="flaticon-document"></i>';
	}

	return $icon;
}

function ova_doc_get_file_size( $url_file = '' ){
	if( $url_file === '' ) return;
	$upload_dir = wp_upload_dir();
	$path_upload_full = $upload_dir['path'];

	$path_upload_sub = substr( $path_upload_full, 0, strpos( $path_upload_full, 'wp-content/uploads' ) );


	$position = strpos( $url_file, 'wp-content/uploads' );
	$sub_str = substr( $url_file, $position );
	$path_file = $path_upload_sub . $sub_str;

	$file_size_byte = filesize( $path_file );
	$file_size_kb = $file_size_byte * 0.0009765625;
	$file_size_kb = round( $file_size_kb );

	return $file_size_kb;
}
