<?php
/**
 * Simply Zen functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package WordPress
 * @subpackage Simply Zen
 * @since Simply Zen 1.6
 */
 
	function simply_zen_support() {

		// Add support for block styles.
		add_theme_support( 'wp-block-styles' );

		// Enqueue editor styles.
		add_editor_style( 'style.css' );

	}

 

add_action( 'after_setup_theme', 'simply_zen_support' );

 
	function simply_zen_styles() {
		// Register theme stylesheet.
		$theme_version = wp_get_theme()->get( 'Version' );

		$version_string = is_string( $theme_version ) ? $theme_version : false;
		wp_register_style(
			'simply_zen-style',
			get_template_directory_uri() . '/style.css',
			array(),
			$version_string
		); 
		// Enqueue theme stylesheet.
		wp_enqueue_style( 'simply_zen-style' );

	}

 

add_action( 'wp_enqueue_scripts', 'simply_zen_styles' );

function simply_zen_default_image_post($post_id) {
	
$image_name = 'default-image';
 if( $image_name != '' && !has_post_thumbnail( $post_id ) ){
	 $args = array(
        'post_type' => 'attachment',
        'posts_per_page' => 1,
		'post_status' => 'inherit',
        'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
        'name' => $image_name 
    );

    $query = new WP_Query($args);
   
    if ($query->have_posts()) {
     $query->the_post();
     $old_attachment_id = get_the_ID(); // Get the attachment ID
     set_post_thumbnail( $post_id, $old_attachment_id );
	  
    } else { 
	 $base = get_stylesheet_directory();
	 $imgfile= $base . '/assets/images/post-image/' . $image_name.'.jpg'; // Images are stored inside an imports folder, in the theme directory
	 $filename = basename($imgfile);
	 $upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));

		if (!$upload_file['error']) {
		$wp_filetype = wp_check_filetype($filename, null );
		$attachment = array(
		  'post_mime_type' => $wp_filetype['type'],
		  'post_parent' => 0,
		  'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
		  'post_content' => '',
		  'post_status' => 'inherit'
		); 
		$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );

			if (!is_wp_error($attachment_id)) {
			  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
			  $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
			  wp_update_attachment_metadata( $attachment_id,  $attachment_data );
			}
		  set_post_thumbnail( $post_id, $attachment_id );
		}
    }
  }
}
 add_action('save_post', 'simply_zen_default_image_post', 10, 1);