<?php
/**
 * Masteriyo course start date block builder.
 *
 * @since 2.14.0
 */

namespace Masteriyo\Addons\Certificate\PDF\BlockBuilders;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Enums\CourseProgressStatus;
use Masteriyo\Query\CourseProgressQuery;

class MasteriyoCourseStartDate extends BlockBuilder {

	/**
	 * Build and return the block HTML.
	 *
	 * @since 2.14.0
	 *
	 * @return string
	 */
	public function build() {
		$pdf         = $this->get_pdf();
		$start_date  = $pdf->is_preview() ? __( 'Start Date', 'learning-management-system' ) : '';
		$student_id  = $pdf->get_student_id();
		$course_id   = $pdf->get_course_id();
		$block_data  = $this->get_block_data();
		$date_format = masteriyo_array_get( $block_data, 'attrs.dateFormat' );
		$date_format = empty( $date_format ) ? 'F j, Y' : $date_format;

		if ( $student_id && $course_id ) {
			$query      = new CourseProgressQuery(
				array(
					'user_id'   => $student_id,
					'course_id' => $course_id,
					'status'    => CourseProgressStatus::COMPLETED,
				)
			);
			$progresses = $query->get_course_progress();
			$progress   = empty( $progresses ) ? null : $progresses[0];

			if ( $progress ) {
				$completed_at = $progress->get_started_at();

				if ( $completed_at ) {
					$start_date = gmdate( $date_format, $completed_at->getTimestamp() );
				}
			}
		}

		/**
		 * Filters the course start date displayed on the certificate.
		 *
		 * @since 2.14.0
		 *
		 * @param string $start_date The course start date.
		 * @return string The filtered course start date.
		 */
		$start_date = apply_filters( 'masteriyo_certificate_course_start_date', $start_date );

		$html  = str_replace( '{{masteriyo_course_start_date}}', $start_date, $block_data['innerHTML'] );
		$html .= '<style>' . masteriyo_array_get( $block_data, 'attrs.blockCSS', '' ) . '</style>';
		return $html;
	}
}
