<?php
namespace DOZENT_LMS_CERTIFICATE;

defined( 'ABSPATH' ) || exit;

/**
 * Class PostType
 *
 * @package Dozent
 *
 */

class Certificate_Template{

	public function __construct(){
	    add_action( 'admin_post_dozent_import_certificates', [ $this, 'import_certificates' ] );
		add_filter( 'dozent_course_settings_tabs', [ $this, 'certificate_template_tab' ] );
		add_action( 'dozent/course_metabox/saved', [ $this, '_save_course' ] );
	}

	public function import_certificates(){
		// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
		require_once ABSPATH . 'wp-admin/includes/image.php';

	    $import_data = include_once  DLC_ABSPATH . 'core/import/import.php' ;
		$upload_dir = wp_upload_dir();

	    if ( dozent_count( $import_data ) ) {
	        foreach ( $import_data as $cert_key => $cert_data ) {
	            $bg_image = dozent_array_get( 'background_image', $cert_data );
	            $bg_source = DLC_ABSPATH . "core/import/{$bg_image}";
		        $filename   = $upload_dir['basedir'] . '/' . $bg_image;

		        copy( $bg_source, $filename ); // @codingStandardsIgnoreLine.

		        $filetype   = wp_check_filetype( basename( $filename ), null );
		        $attachment = array(
			        'guid'           => $upload_dir['url'] . '/' . basename( $filename ),
			        'post_mime_type' => $filetype['type'],
			        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
			        'post_content'   => '',
			        'post_status'    => 'inherit',
		        );
		        $attach_id  = wp_insert_attachment( $attachment, $filename );
		        // Generate the metadata for the attachment, and update the database record.
		        $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
		        wp_update_attachment_metadata( $attach_id, $attach_data );

		        $certificate_title = dozent_array_get( 'name', $cert_data );
		        $certificate_id = wp_insert_post( [
		                'post_type'   => 'dozent_certificate',
		                'post_title'   => $certificate_title,
		                'post_status'   => 'publish',
		                '_thumbnail_id'   => $attach_id,
		                'meta_input'   => $cert_data[ 'post_meta' ],
                ] );
	        }
        }

	    dozent_redirect();
    }

	public function certificate_template_tab( $sections ){

		$sections['certificate_template'] = [
			'title'      => __( 'Certificate Template', 'dozent-lms-certificate' ),
			'desc'       => __( 'Choose a certificate template to personalize your course certificate', 'dozent-lms-certificate' ),
			'icon_class' => ' dicon-certificate',
			'callback'   => [ $this, 'certificate_template_tab_content' ],
		];

		return $sections;
	}

	public function certificate_template_tab_content(){
		$certificates = get_posts( [
			'post_type'   => 'dozent_certificate',
			'numberposts' => '-1',
		] );

		$selected_certificate_id = (int) get_post_meta( get_the_ID(), '_certificate_id', true );
		if ( ! $selected_certificate_id ) {
			$selected_certificate_id = (int) get_option( 'default_certificate_id' );
		}

		?>

		<div class="dozent-certificate-page certificate-templates-wrap dozent-mt-4">
			<?php
			if ( is_array( $certificates ) && count( $certificates ) > 0 ) {
				?>

				<div class="dozent-row">

					<?php foreach ( $certificates as $certificate ) {
						$thumbnail = get_the_post_thumbnail_url( $certificate->ID );
						$certificate_title = $certificate->post_title;
						?>
						<div class="dozent-col-4">
							<div class="certificate-loop-wrap certificate-template ">

                                <input type="radio" id="certificate_id_<?php echo $certificate->ID; ?>" class="course_certificate_template_input" name="_certificate_template_id" value="<?php echo $certificate->ID; ?>" <?php checked( $certificate->ID, $selected_certificate_id ); ?> >

								<label for="certificate_id_<?php echo $certificate->ID; ?>">
                                    <span class="certificate-cover-wrap">
                                        <img src="<?php echo $thumbnail; ?>" />
                                    </span>

                                    <div class="certificate-title">
                                        <h3> <?php echo $certificate_title; ?> </h3>
                                    </div>
                                </label>
							</div>
						</div>

					<?php } ?>

				</div>

				<?php
			}

			?>
		</div>
		<?php

	}

	/**
	 * Save certificate template ID
     *
	 */

	public function _save_course( $post_ID ){
	    $certificate_template_id = (int) dozent_input_text( '_certificate_template_id' );
	    if ( $certificate_template_id ) {
	        update_post_meta( $post_ID, '_certificate_id', $certificate_template_id );
	    }
	}


}