<?php
add_action( 'init', 'themesflat_register_courses_post_type' );
/**
 * Register courses post type
 */
function themesflat_register_courses_post_type() {
	/*courses*/
	$courses_slug = 'courses';
	$labels       = array(
		'name'               => esc_html__( 'Courses', 'themesflat' ),
		'singular_name'      => esc_html__( 'Course', 'themesflat' ),
		'menu_name'          => esc_html__( 'Courses', 'themesflat' ),
		'add_new'            => esc_html__( 'New Course', 'themesflat' ),
		'add_new_item'       => esc_html__( 'Add New Course', 'themesflat' ),
		'new_item'           => esc_html__( 'New Course Item', 'themesflat' ),
		'edit_item'          => esc_html__( 'Edit Course Item', 'themesflat' ),
		'view_item'          => esc_html__( 'View Course', 'themesflat' ),
		'all_items'          => esc_html__( 'All Courses', 'themesflat' ),
		'search_items'       => esc_html__( 'Search Courses', 'themesflat' ),
		'not_found'          => esc_html__( 'No Course Items Found', 'themesflat' ),
		'not_found_in_trash' => esc_html__( 'No Course Items Found In Trash', 'themesflat' ),
		'parent_item_colon'  => esc_html__( 'Parent Course:', 'themesflat' )

	);
	$args         = array(
		'labels'       => $labels,
		'rewrite'      => array( 'slug' => $courses_slug ),
		'supports'     => array( 'title', 'editor', 'thumbnail', 'custom-fields', 'elementor', 'comments' ),
		'public'       => true,
		'show_in_rest' => true,
		'has_archive'  => true
	);
	register_post_type( 'courses', $args );
	flush_rewrite_rules();
}

add_filter( 'post_updated_messages', 'themesflat_courses_updated_messages' );
/**
 * courses update messages.
 */
function themesflat_courses_updated_messages( $messages ) {
	Global $post, $post_ID;
	$messages[ esc_html__( 'courses' ) ] = array(
		0  => '',
		1  => sprintf( esc_html__( 'Course Updated. <a href="%s">View Course</a>', 'themesflat' ), esc_url( get_permalink( $post_ID ) ) ),
		2  => esc_html__( 'Custom Field Updated.', 'themesflat' ),
		3  => esc_html__( 'Custom Field Deleted.', 'themesflat' ),
		4  => esc_html__( 'Course Updated.', 'themesflat' ),
		5  => isset( $_GET['revision'] ) ? sprintf( esc_html__( 'Course Restored To Revision From %s', 'themesflat' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
		6  => sprintf( esc_html__( 'Course Published. <a href="%s">View Course</a>', 'themesflat' ), esc_url( get_permalink( $post_ID ) ) ),
		7  => esc_html__( 'Course Saved.', 'themesflat' ),
		8  => sprintf( esc_html__( 'Course Submitted. <a target="_blank" href="%s">Preview Course</a>', 'themesflat' ), esc_url( add_query_arg( 'preview', 'true', get_permalink( $post_ID ) ) ) ),
		9  => sprintf( esc_html__( 'Course Scheduled For: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Course</a>', 'themesflat' ), date_i18n( esc_html__( 'M j, Y @ G:i', 'themesflat' ), strtotime( $post->post_date ) ), esc_url( get_permalink( $post_ID ) ) ),
		10 => sprintf( esc_html__( 'Course Draft Updated. <a target="_blank" href="%s">Preview Course</a>', 'themesflat' ), esc_url( add_query_arg( 'preview', 'true', get_permalink( $post_ID ) ) ) ),
	);

	return $messages;
}

add_action( 'init', 'themesflat_register_courses_taxonomy' );
/**
 * Register courses taxonomy
 */
function themesflat_register_courses_taxonomy() {
	/*courses Categories*/
	$courses_cat_slug = 'courses_category';
	$labels           = array(
		'name'                  => esc_html__( 'Course Categories', 'themesflat' ),
		'singular_name'         => esc_html__( 'Categories', 'themesflat' ),
		'search_items'          => esc_html__( 'Search Categories', 'themesflat' ),
		'menu_name'             => esc_html__( 'Categories', 'themesflat' ),
		'all_items'             => esc_html__( 'All Categories', 'themesflat' ),
		'parent_item'           => esc_html__( 'Parent Categories', 'themesflat' ),
		'parent_item_colon'     => esc_html__( 'Parent Categories:', 'themesflat' ),
		'new_item_name'         => esc_html__( 'New Categories Name', 'themesflat' ),
		'add_new_item'          => esc_html__( 'Add New Categories', 'themesflat' ),
		'edit_item'             => esc_html__( 'Edit Categories', 'themesflat' ),
		'update_item'           => esc_html__( 'Update Categories', 'themesflat' ),
		'add_or_remove_items'   => esc_html__( 'Add or remove Categories', 'themesflat' ),
		'choose_from_most_used' => esc_html__( 'Choose from the most used Categories', 'themesflat' ),
		'not_found'             => esc_html__( 'No Categories found.' ),
	);
	$args             = array(
		'labels'       => $labels,
		'rewrite'      => array( 'slug' => $courses_cat_slug ),
		'hierarchical' => true,
		'show_in_rest' => true,
	);
	register_taxonomy( 'courses_category', 'courses', $args );
	flush_rewrite_rules();
}

add_action( 'init', 'themesflat_register_courses_tag' );
/**
 * Register tag taxonomy
 */
function themesflat_register_courses_tag() {
	$courses_tag_slug = 'courses_tag';

	$labels = array(
		'name'          => esc_html__( 'Course Tags', 'themesflat' ),
		'singular_name' => esc_html__( 'Course Tags', 'themesflat' ),
		'search_items'  => esc_html__( 'Search Tags', 'themesflat' ),
		'all_items'     => esc_html__( 'All Tags', 'themesflat' ),
		'new_item_name' => esc_html__( 'Add New Tag', 'themesflat' ),
		'add_new_item'  => esc_html__( 'New Tag Name', 'themesflat' ),
		'edit_item'     => esc_html__( 'Edit Tag', 'themesflat' ),
		'update_item'   => esc_html__( 'Update Tag', 'themesflat' ),
		'menu_name'     => esc_html__( 'Tags' ),
	);
	$args   = array(
		'labels'       => $labels,
		'rewrite'      => array( 'slug' => $courses_tag_slug ),
		'hierarchical' => true,
		'show_in_rest' => true,
	);
	register_taxonomy( 'courses_tag', 'courses', $args );
	flush_rewrite_rules();
}

add_action( 'add_meta_boxes', 'themesflat_course_add_meta_box' );
function themesflat_course_add_meta_box() {
	add_meta_box( 'tf_course_meta', esc_html__( 'Addition Information', 'themesflat' ), 'themesflat_course_meta_box', 'courses', 'advanced' );
	add_meta_box( 'tf_course_meta_curriculum', esc_html__( 'Curriculum', 'themesflat' ), 'themesflat_course_meta_box_curriculum', 'courses', 'advanced' );
	add_meta_box( 'tf_course_meta_instructor', esc_html__( 'Instructor', 'themesflat' ), 'themesflat_course_meta_box_instructor', 'courses', 'advanced' );
}

function themesflat_course_meta_box( $post ) {
	$price               = get_post_meta( $post->ID, 'tf_course_price', true );
	$theory_session      = get_post_meta( $post->ID, 'tf_course_theory_session', true );
	$practical_session   = get_post_meta( $post->ID, 'tf_course_practical_session', true );
	$certificate_quality = get_post_meta( $post->ID, 'tf_course_certificate_quality', true );

	wp_nonce_field( 'tf_courses_metabox_nonce', 'tf_courses_metabox_nonce_field' );
	?>
    <table class="form-table">

        <tr>
            <th><label for="tf-course-price"><?php esc_html_e( 'Price', 'themesflat' ) ?></label></th>
            <td>
                <input id='tf-course-price' type="text" name="tf_course_price"
                       value="<?php echo esc_attr( $price ) ?>">
            </td>
        </tr>
        <tr>
            <th><label for="tf-course-theory-session"><?php esc_html_e( 'Theory session', 'themesflat' ) ?></label></th>
            <td>
                <input id='tf-course-theory-session' type="text" name="tf_course_theory_session"
                       value="<?php echo esc_attr( $theory_session ) ?>">
            </td>
        </tr>
        <tr>
            <th>
                <label for="tf-course-practical-session"><?php esc_html_e( 'Practical session', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-practical-session' type="text" name="tf_course_practical_session"
                       value="<?php echo esc_attr( $practical_session ) ?>">
            </td>
        </tr>
        <tr>
            <th>
                <label for="tf-course-certificate-quality"><?php esc_html_e( 'Certificate quality', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-certificate-quality' type="text" name="tf_course_certificate_quality"
                       value="<?php echo esc_attr( $certificate_quality ) ?>">
            </td>
        </tr>
    </table>
	<?php
}

function themesflat_course_meta_box_curriculum( $post ) {
	$curriculum = get_post_meta( $post->ID, 'tf_course_curriculum', true );

	wp_nonce_field( 'tf_courses_metabox_curriculum_nonce', 'tf_courses_metabox_curriculum_nonce_field' );
	?>
    <table class="form-table">
        <tr>
            <td>
				<?php wp_editor( $curriculum, 'tf_course_curriculum' ) ?>
            </td>
        </tr>

    </table>
	<?php
}

function themesflat_course_meta_box_instructor( $post ) {
	$id       = get_post_meta( $post->ID, 'tf_course_instructor_avatar', true );
	$name     = get_post_meta( $post->ID, 'tf_course_instructor_name', true );
	$position = get_post_meta( $post->ID, 'tf_course_instructor_position', true );
	$face     = get_post_meta( $post->ID, 'tf_course_instructor_facebook', true );
	$twitter  = get_post_meta( $post->ID, 'tf_course_instructor_twitter', true );
	$insta    = get_post_meta( $post->ID, 'tf_course_instructor_instagram', true );
	$behance  = get_post_meta( $post->ID, 'tf_course_instructor_behance', true );

	wp_nonce_field( 'tf_courses_metabox_instructor_nonce', 'tf_courses_metabox_instructor_nonce_field' );
	?>
    <table class="form-table">

        <tr>
            <th><label for="tf-course-instructor-avatar"><?php esc_html_e( 'Avatar', 'themesflat' ) ?></label></th>
            <td>
				<?php
				$url = wp_get_attachment_url( $id );
				if ( $url ):
					?>
                    <div class='image-preview-wrapper' style='width: 100px;'>

                        <img id='image-preview' src='<?php echo esc_url( $url ) ?>' style=' max-width: 100%;'>
                    </div>
				<?php endif; ?>
                <input id='tf-course-instructor-avatar' type="file" name="tf_course_instructor_avatar">
            </td>
        </tr>
        <tr>
            <th><label for="tf-course-instructor-name"><?php esc_html_e( 'Instructor Name', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-instructor-name' type="text" name="tf_course_instructor_name"
                       value="<?php echo esc_attr( $name ) ?>">
            </td>
        </tr>
        <tr>
            <th>
                <label for="tf-course-instructor-position"><?php esc_html_e( 'Instructor Position', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-instructor-position' type="text" name="tf_course_instructor_position"
                       value="<?php echo esc_attr( $position ) ?>">
            </td>
        </tr>
        <tr>
            <th>
                <label for="tf-course-instructor-facebook"><?php esc_html_e( 'Facebook Url', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-instructor-facebook' type="text" name="tf_course_instructor_facebook"
                       value="<?php echo esc_attr( $face ) ?>">
            </td>
        </tr>
        <tr>
            <th>
                <label for="tf-course-instructor-twitter"><?php esc_html_e( 'Twitter Url', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-instructor-twitter' type="text" name="tf_course_instructor_twitter"
                       value="<?php echo esc_attr( $twitter ) ?>">
            </td>
        </tr>
        <tr>
            <th>
                <label for="tf-course-instructor-instagram"><?php esc_html_e( 'Instagram Url', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-instructor-instagram' type="text" name="tf_course_instructor_instagram"
                       value="<?php echo esc_attr( $insta ) ?>">
            </td>
        </tr>
        <tr>
            <th>
                <label for="tf-course-instructor-behance"><?php esc_html_e( 'Behance Url', 'themesflat' ) ?></label>
            </th>
            <td>
                <input id='tf-course-instructor-behance' type="text" name="tf_course_instructor_behance"
                       value="<?php echo esc_attr( $behance ) ?>">
            </td>
        </tr>
    </table>
	<?php
}

add_action( "save_post", 'themesflat_course_save_post' );
function themesflat_course_save_post( $post_id ) {
	// Secure with nonce field check
	if ( ! isset( $_POST['tf_courses_metabox_nonce_field'] ) ) {
		return;
	}

	if ( ! wp_verify_nonce( $_POST['tf_courses_metabox_nonce_field'], 'tf_courses_metabox_nonce' ) ) {
		return;
	}

	if ( isset( $_POST['tf_course_price'] ) ) {
		$price = sanitize_text_field( $_POST['tf_course_price'] );
		update_post_meta( $post_id, 'tf_course_price', $price );
	}
	if ( isset( $_POST['tf_course_theory_session'] ) ) {
		$theory_session = sanitize_text_field( $_POST['tf_course_theory_session'] );
		update_post_meta( $post_id, 'tf_course_theory_session', $theory_session );
	}
	if ( isset( $_POST['tf_course_practical_session'] ) ) {
		$practical_session = sanitize_text_field( $_POST['tf_course_practical_session'] );
		update_post_meta( $post_id, 'tf_course_practical_session', $practical_session );
	}
	if ( isset( $_POST['tf_course_certificate_quality'] ) ) {
		$certificate_quality = sanitize_text_field( $_POST['tf_course_certificate_quality'] );
		update_post_meta( $post_id, 'tf_course_certificate_quality', $certificate_quality );
	}

}

add_action( "save_post", 'themesflat_course_save_curriculum' );
function themesflat_course_save_curriculum( $post_id ) {
	// Secure with nonce field check
	if ( ! isset( $_POST['tf_courses_metabox_curriculum_nonce_field'] ) ) {
		return;
	}

	if ( ! wp_verify_nonce( $_POST['tf_courses_metabox_curriculum_nonce_field'], 'tf_courses_metabox_curriculum_nonce' ) ) {
		return;
	}

	if ( isset( $_POST['tf_course_curriculum'] ) ) {
		$curriculum =  $_POST['tf_course_curriculum'];
		update_post_meta( $post_id, 'tf_course_curriculum', $curriculum );
	}
}

add_action( "save_post", 'themesflat_course_save_instructor' );
function themesflat_course_save_instructor( $post_id ) {
	// Secure with nonce field check
	if ( ! isset( $_POST['tf_courses_metabox_instructor_nonce_field'] ) ) {
		return;
	}

	if ( ! wp_verify_nonce( $_POST['tf_courses_metabox_instructor_nonce_field'], 'tf_courses_metabox_instructor_nonce' ) ) {
		return;
	}

	$filename = sanitize_file_name( $_FILES['tf_course_instructor_avatar']['name'] );
	if ( ! empty( $filename ) ) {
		$wp_filetype = wp_check_filetype( basename( $filename ), null );
		if ( $wp_filetype['type'] == 'image/png' || $wp_filetype['type'] == 'image/jpeg' ) {
			$wp_upload_dir = wp_upload_dir();

			move_uploaded_file( $_FILES['tf_course_instructor_avatar']['tmp_name'], $wp_upload_dir['path'] . '/' . $filename );

			$attachment = array(
				'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
				'post_mime_type' => $wp_filetype['type'],
				'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
				'post_content'   => '',
				'post_status'    => 'inherit'
			);
			$filename  = $wp_upload_dir['path'] . '/' . $filename;
			$attach_id = wp_insert_attachment( $attachment, $filename, wp_get_post_parent_id() );
			update_post_meta( $post_id, 'tf_course_instructor_avatar', $attach_id );
		}
	}

	if ( isset( $_POST['tf_course_instructor_name'] ) ) {
		$curriculum = sanitize_text_field( $_POST['tf_course_instructor_name'] );
		update_post_meta( $post_id, 'tf_course_instructor_name', $curriculum );
	}
	if ( isset( $_POST['tf_course_instructor_position'] ) ) {
		$curriculum = sanitize_text_field( $_POST['tf_course_instructor_position'] );
		update_post_meta( $post_id, 'tf_course_instructor_position', $curriculum );
	}
	if ( isset( $_POST['tf_course_instructor_facebook'] ) ) {
		$curriculum = sanitize_text_field( $_POST['tf_course_instructor_facebook'] );
		update_post_meta( $post_id, 'tf_course_instructor_facebook', $curriculum );
	}
	if ( isset( $_POST['tf_course_instructor_twitter'] ) ) {
		$curriculum = sanitize_text_field( $_POST['tf_course_instructor_twitter'] );
		update_post_meta( $post_id, 'tf_course_instructor_twitter', $curriculum );
	}
	if ( isset( $_POST['tf_course_instructor_instagram'] ) ) {
		$curriculum = sanitize_text_field( $_POST['tf_course_instructor_instagram'] );
		update_post_meta( $post_id, 'tf_course_instructor_instagram', $curriculum );
	}
	if ( isset( $_POST['tf_course_instructor_behance'] ) ) {
		$curriculum = sanitize_text_field( $_POST['tf_course_instructor_behance'] );
		update_post_meta( $post_id, 'tf_course_instructor_behance', $curriculum );
	}
}