<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}


$order_id     = isset( $args['order_id'] ) ? intval( $args['order_id'] ) : 0;
$profile_type = ! empty( $args['profile_type'] ) ? $args['profile_type'] : '';

$post_status = get_post_status( $order_id );

$is_active_order   = in_array( $post_status, array( 'publish', 'delivered' ), true );
$is_finished_order = in_array( $post_status, array( 'completed', 'cancelled' ), true );

if ( ! $is_active_order && ! $is_finished_order ) {
	return;
}

if ( $is_active_order ) {
	$current_stage          = gigneo_post_meta( $order_id, '_gigneo_pm_activity_stage' );
	$start_date             = get_post_meta( $order_id, '_gigneo_pm_started_at_gmt', true );
	$extended_delivery_date = get_post_meta( $order_id, '_gigneo_pm_extended_delivery_date_time_gmt', true );
	$initial_delivery_date  = get_post_meta( $order_id, '_gigneo_pm_delivery_at_gmt', true );
	$delivery_date          = ! empty( $extended_delivery_date ) ? $extended_delivery_date : $initial_delivery_date;
	$delivery_date          = gigneo_datetime( $delivery_date );

	$delivery_ts = strtotime( $delivery_date );
	$now         = new DateTime( 'now', wp_timezone() );
	$now->setTimezone( new DateTimeZone( 'UTC' ) );
	$now_gmt    = $now->format( 'Y-m-d H:i:s' );
	$now_gmt    = gigneo_datetime( $now_gmt );
	$now_gmt_ts = strtotime( $now_gmt );

	if ( $now_gmt_ts < $delivery_ts - 60 ) {
		$delivery_status = 'pending';
	} elseif ( $now_gmt_ts <= $delivery_ts + 60 ) {
		$delivery_status = 'delivered';
	} else {
		$delivery_status = 'delayed';
	}

	// Calculate time diff
	$diff    = max( 0, $delivery_ts - $now_gmt_ts );
	$days    = floor( $diff / DAY_IN_SECONDS );
	$hours   = floor( ( $diff % DAY_IN_SECONDS ) / HOUR_IN_SECONDS );
	$minutes = floor( ( $diff % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS );
	$seconds = $diff % MINUTE_IN_SECONDS;
} else {
	$current_stage   = '';
	$start_date      = get_post_meta( $order_id, '_gigneo_pm_started_at_gmt', true );
	$delivery_date   = '';
	$delivery_ts     = 0;
	$now_gmt         = '';
	$delivery_status = 'delivered';
	$days            = 0;
	$hours           = 0;
	$minutes         = 0;
	$seconds         = 0;
}

function gigneo_pad_num( $num ) {
	return str_pad( (string) $num, 2, '0', STR_PAD_LEFT );
}

$service_order_extensions = gigneo_option( '_gigneo_ts_service_order_extensions', array( 'jpg', 'jpeg', 'png', 'doc' ) );
$service_order_max_files  = gigneo_option( '_gigneo_ts_service_order_max_files', '3' );
$service_order_max_size   = gigneo_option( '_gigneo_ts_service_order_max_size', '1' );
?>
<div class="gn-order-section gn-order-delivery">
	<div class="gn-head">
		<h3 class="gn-title">
			<?php echo esc_html__( 'Time until delivery', 'gigneo' ); ?>
			<?php if ( empty( $start_date ) ) { ?>
				<span class="gn-status-tag gn-warning"><?php echo esc_html__( 'Not Started', 'gigneo' ); ?></span>
			<?php } ?>
		</h3>
	</div>
	<div class="gn-body">
		<div id="gn-order-delivery-countdown" class="gn-delivery-countdown gn-status-<?php echo esc_attr( $delivery_status ); ?>"<?php echo $is_active_order ? ' data-gn-now="' . esc_attr( $now_gmt ) . '" data-gn-delivery="' . esc_attr( $delivery_date ) . '"' : ''; ?>>
			<div class="gn-countdown-item"><span id="gn-days"><?php echo esc_html( gigneo_pad_num( $days ?? 0 ) ); ?></span><small><?php echo esc_html__( 'Day', 'gigneo' ); ?></small></div>
			<div class="gn-countdown-item"><span id="gn-hours"><?php echo esc_html( gigneo_pad_num( $hours ?? 0 ) ); ?></span><small><?php echo esc_html__( 'Hour', 'gigneo' ); ?></small></div>
			<div class="gn-countdown-item"><span id="gn-minutes"><?php echo esc_html( gigneo_pad_num( $minutes ?? 0 ) ); ?></span><small><?php echo esc_html__( 'Min', 'gigneo' ); ?></small></div>
			<div class="gn-countdown-item"><span id="gn-seconds"><?php echo esc_html( gigneo_pad_num( $seconds ?? 0 ) ); ?></span><small><?php echo esc_html__( 'Sec', 'gigneo' ); ?></small></div>
		</div>
		<?php if ( $is_active_order && 'freelancer' === $profile_type && ! empty( $start_date ) && ( 'order_completed' !== $current_stage || 'order_delivered' !== $current_stage ) ) { ?>
			<div class="gn-actions">
				<button type="button" data-gn-modal-toggle="gn-order-deliver" class="gn-btn gn-btn-primary gn-btn-md"><?php echo esc_html__( 'Deliver now', 'gigneo' ); ?></button>
				<?php if ( in_array( 'extend_delivery', gigneo_active_modules(), true ) ) { ?>
					<button type="button" data-gn-modal-toggle="gn-extend-delivery-modal" class="gn-btn gn-btn-outline-grey gn-btn-md"><?php echo esc_html__( 'Extend delivery date', 'gigneo' ); ?></button>
				<?php } ?>
			</div>
		<?php } ?>
	</div>
	<?php if ( $is_active_order && ! empty( $start_date ) ) { ?>
		<!--Delivery Modal-->
		<div id="gn-order-deliver" class="gn-modal-wrapper gn-order-deliver">
			<div class="gn-modal-dialog">
				<div class="gn-modal-content">
					<div class="gn-modal-info">
						<div class="gn-modal-header">
							<h4 class="gn-title"><?php echo esc_html__( 'Deliver your work', 'gigneo' ); ?></h4>
							<p class="gn-description"><?php echo esc_html__( 'Submit your completed work to finalize the order and notify the client.', 'gigneo' ); ?></p>
							<button type="button" data-gn-modal-close="gn-order-deliver" class="gn-modal-close">
								<i class="hi hi-x-mark" aria-hidden="true"></i>
							</button>
						</div>
						<form id="gn-service-order-deliver-form" class="gn-theme-form">
							<div class="gn-modal-body gn-custom-scrollbar">
								<fieldset class="gn-form-fields">
									<div class="row g-4">
										<div class="col-md-12">
											<div class="gn-form-field gn-select2">
												<label class="gn-required-field-label"
														for="gn-order-delivery-type"><?php echo esc_html__( 'Type', 'gigneo' ); ?></label>
												<select id="gn-order-delivery-type" name="order_delivery_type"
														data-minimum-results-for-search="Infinity">
													<option value="final"><?php echo esc_html__( 'Final delivery', 'gigneo' ); ?></option>
													<option value="draft"><?php echo esc_html__( 'Draft work', 'gigneo' ); ?></option>
												</select>
											</div>
										</div>
										<div class="col-md-12">
											<div class="gn-form-field gn-plupload">
												<label class="gn-required-field-label"
														for="gn-order-delivery-attachments"><?php echo esc_html__( 'Attachments', 'gigneo' ); ?></label>
												<div id="gn-service-order-delivery-container"
													class="gn-plupload-container">
													<div id="gn-service-order-delivery-drop-area"
														class="gn-plupload-drop-area">
														<i class="hi hi-cloud-arrow-up" aria-hidden="true"></i>
														<div class="gn-action-info">
															<p class="gn-message"><?php echo esc_html__( 'Click here to upload.', 'gigneo' ); ?></p>
															<button id="gn-service-order-delivery-uploader" type="button" class="gn-upload"><?php echo esc_html__( 'Click here to upload', 'gigneo' ); ?></button>
															<p class="gn-note">
															<?php
															printf(
															// translators: %1$s: Valid extensions %2$s Maximum files %3$s Maximum file size.
																esc_html__( '%1$s — Up to %2$s files (Max. %3$s MB)', 'gigneo' ),
																esc_html( strtoupper( implode( ',', $service_order_extensions ) ) ),
																esc_html( $service_order_max_files ),
																esc_html( $service_order_max_size )
															);
															?>
															</p>
														</div>
													</div>
													<div id="gn-service-order-delivery-list"
														class="gn-plupload-attachments"></div>
												</div>
											</div>
										</div>
										<div class="col-md-12">
											<div class="gn-form-field gn-wysiwyg-editor-two">
												<label for="gn-order-delivery-description" class="gn-required-field-label">
													<?php echo esc_html__( 'Description', 'gigneo' ); ?>
												</label>
												<?php
												wp_editor(
													'',
													'gn-order-delivery-description',
													array(
														'textarea_name' => 'order_delivery_description',
														'media_buttons' => false,
														'quicktags'     => false,
														'textarea_rows' => 7,
														'editor_class'  => 'gn-wp-editor gn-required-field',
														'tinymce'      => array(
															'toolbar1' => 'bold italic bullist numlist link unlink',
															'toolbar2' => '',
															'plugins'  => 'lists link',
															'directionality' => is_rtl() ? 'rtl' : 'ltr',
															'forced_root_block' => false,
															'force_br_newlines' => true,
															'force_p_newlines' => false,
															'convert_newlines_to_brs' => true,
															'valid_elements' => 'strong/b,em/i,ul,ol,li,a[href|target],br,hr',
															'invalid_elements' => 'p,pre,h1,h2,h3,h4,h5,h6,img',
															'content_style' => 'body { font-size: 14px; background-color: transparent; font-family: var(--gigneo-primary-font,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji) }',
														),
													)
												);
												?>
											</div>
										</div>
									</div>
								</fieldset>
							</div>
							<div class="gn-modal-footer">
								<input type="hidden" name="order_id" value="<?php echo esc_attr( $order_id ); ?>"/>
								<button type="button" class="gn-btn gn-btn-outline-grey"
										data-gn-modal-close="gn-order-deliver"><?php echo esc_html__( 'Close', 'gigneo' ); ?></button>
								<button type="submit"
										class="gn-btn gn-btn-primary"><?php echo esc_html__( 'Submit', 'gigneo' ); ?></button>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
		<?php
		if ( in_array( 'extend_delivery' , gigneo_active_modules(), true ) ) {
			gigneo_load_template(
				'dashboard/order/service/parts/detail/extend_delivery',
				true,
				array(
					'order_id'      => $order_id,
					'delivery_date' => $delivery_date,
					'delivery_ts'   => $delivery_ts,
				)
			);
		}
		?>
	<?php } ?>
</div>