<?php
/**
 * Schedule tab — scheduled backup configuration.
 *
 * @package BackupRestore
 *
 * @var array<string, mixed> $br_settings
 * @var bool $settings_updated
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$s = $br_settings;

$next_ts     = wp_next_scheduled( 'wpps_br_scheduled_backup' );
$tz          = wp_timezone();
$server_time = date_i18n( 'D, F j, Y H:i', current_time( 'U' ) );
$now_in_tz   = new \DateTimeImmutable( 'now', $tz );
$utc_offset  = $now_in_tz->format( 'P' );
$tz_id       = $tz->getName();
$is_enabled  = ! empty( $s['schedule_enabled'] );
$freq        = $s['schedule_frequency'] ?? 'daily';
$tz_settings = admin_url( 'options-general.php' );
?>
<?php if ( ! empty( $settings_updated ) ) : ?>
	<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Schedule saved.', 'wp-powersuite' ); ?></p></div>
<?php endif; ?>

<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="wpps-br-schedule-form">
	<?php wp_nonce_field( 'wpps_br_schedule' ); ?>
	<input type="hidden" name="action" value="wpps_br_save_schedule" />

	<div class="wpps-br-card wpps-br-sched">
		<div class="wpps-br-sched-header">
			<div class="wpps-br-sched-header__text">
				<h2 style="margin:0;font-size:15px;"><?php esc_html_e( 'Scheduled Backups', 'wp-powersuite' ); ?></h2>
				<p class="wpps-br-muted" style="margin:4px 0 0;"><?php esc_html_e( 'Automatically create backups on a recurring schedule.', 'wp-powersuite' ); ?></p>
			</div>
			<label class="wpps-br-sched-toggle">
				<input type="checkbox" name="schedule_enabled" value="1" <?php checked( $is_enabled ); ?> id="wpps-br-schedule-enabled" />
				<span class="wpps-br-sched-toggle__slider"></span>
			</label>
		</div>

		<?php if ( $next_ts ) : ?>
			<?php
			$next_dt  = ( new \DateTimeImmutable( '@' . $next_ts ) )->setTimezone( $tz );
			$diff_sec = max( 0, $next_ts - time() );
			$diff_h   = (int) floor( $diff_sec / 3600 );
			$diff_m   = (int) floor( ( $diff_sec % 3600 ) / 60 );
			if ( $diff_h >= 24 ) {
				$diff_d    = (int) floor( $diff_h / 24 );
				$rem_h     = $diff_h % 24;
				$countdown = sprintf(
					/* translators: 1: days 2: hours */
					__( '%1$dd %2$dh', 'wp-powersuite' ),
					$diff_d,
					$rem_h
				);
			} elseif ( $diff_h > 0 ) {
				$countdown = sprintf(
					/* translators: 1: hours 2: minutes */
					__( '%1$dh %2$dm', 'wp-powersuite' ),
					$diff_h,
					$diff_m
				);
			} else {
				$countdown = sprintf(
					/* translators: %d: minutes */
					__( '%dm', 'wp-powersuite' ),
					max( 1, $diff_m )
				);
			}
			?>
			<div class="wpps-br-sched-next wpps-br-sched-next--active">
				<span class="dashicons dashicons-backup"></span>
				<span>
					<?php
					printf(
						esc_html__( 'Next backup: %s', 'wp-powersuite' ),
						'<strong>' . esc_html( $next_dt->format( 'D, M j, Y \a\t H:i' ) ) . '</strong>'
					);
					?>
				</span>
				<span class="wpps-br-sched-countdown"><?php echo esc_html( $countdown ); ?></span>
			</div>
		<?php elseif ( $is_enabled ) : ?>
			<div class="wpps-br-sched-next wpps-br-sched-next--warn">
				<span class="dashicons dashicons-warning"></span>
				<?php esc_html_e( 'Enabled but no cron event registered. Save to re-register.', 'wp-powersuite' ); ?>
			</div>
		<?php endif; ?>

		<div class="wpps-br-sched-body" id="wpps-br-schedule-fields">

			<div class="wpps-br-sched-section">
				<div class="wpps-br-sched-section__label"><?php esc_html_e( 'When', 'wp-powersuite' ); ?></div>
				<div class="wpps-br-sched-section__fields">
					<div class="wpps-br-sched-row">
						<select name="schedule_frequency" id="wpps-br-schedule-frequency" class="wpps-br-sched-select">
							<option value="daily" <?php selected( $freq, 'daily' ); ?>><?php esc_html_e( 'Daily', 'wp-powersuite' ); ?></option>
							<option value="weekly" <?php selected( $freq, 'weekly' ); ?>><?php esc_html_e( 'Weekly', 'wp-powersuite' ); ?></option>
							<option value="monthly" <?php selected( $freq, 'monthly' ); ?>><?php esc_html_e( 'Monthly', 'wp-powersuite' ); ?></option>
						</select>

						<span id="wpps-br-row-day-of-week" class="wpps-br-sched-inline-field" <?php echo 'weekly' !== $freq ? 'style="display:none;"' : ''; ?>>
							<?php esc_html_e( 'on', 'wp-powersuite' ); ?>
							<select name="schedule_day_of_week" id="wpps-br-schedule-dow" class="wpps-br-sched-select">
								<?php
								$days = [
									0 => __( 'Sunday', 'wp-powersuite' ),
									1 => __( 'Monday', 'wp-powersuite' ),
									2 => __( 'Tuesday', 'wp-powersuite' ),
									3 => __( 'Wednesday', 'wp-powersuite' ),
									4 => __( 'Thursday', 'wp-powersuite' ),
									5 => __( 'Friday', 'wp-powersuite' ),
									6 => __( 'Saturday', 'wp-powersuite' ),
								];
								foreach ( $days as $val => $label ) :
									?>
									<option value="<?php echo esc_attr( (string) $val ); ?>" <?php selected( (int) ( $s['schedule_day_of_week'] ?? 0 ), $val ); ?>><?php echo esc_html( $label ); ?></option>
								<?php endforeach; ?>
							</select>
						</span>

						<span id="wpps-br-row-day-of-month" class="wpps-br-sched-inline-field" <?php echo 'monthly' !== $freq ? 'style="display:none;"' : ''; ?>>
							<?php esc_html_e( 'on day', 'wp-powersuite' ); ?>
							<select name="schedule_day_of_month" id="wpps-br-schedule-dom" class="wpps-br-sched-select wpps-br-sched-select--narrow">
								<?php for ( $d = 1; $d <= 28; $d++ ) : ?>
									<option value="<?php echo esc_attr( (string) $d ); ?>" <?php selected( (int) ( $s['schedule_day_of_month'] ?? 1 ), $d ); ?>><?php echo esc_html( (string) $d ); ?></option>
								<?php endfor; ?>
							</select>
						</span>

						<span class="wpps-br-sched-inline-field">
							<?php esc_html_e( 'at', 'wp-powersuite' ); ?>
							<input type="time" name="schedule_time" id="wpps-br-schedule-time" value="<?php echo esc_attr( (string) ( $s['schedule_time'] ?? '03:00' ) ); ?>" class="wpps-br-sched-time" />
						</span>
					</div>
					<div
						class="wpps-br-sched-clocks"
						title="<?php esc_attr_e( 'Current date and time in the site timezone (Settings → General).', 'wp-powersuite' ); ?>"
					>
						<span class="wpps-br-sched-clocks__time"><?php echo esc_html( $server_time ); ?></span>
						<span class="wpps-br-sched-clocks__sep" aria-hidden="true">·</span>
						<span class="wpps-br-sched-clocks__tz">
							<code class="wpps-br-sched-clocks__tz-id"><?php echo esc_html( $tz_id ); ?></code>
							<span class="wpps-br-sched-clocks__offset"><?php echo esc_html( sprintf( /* translators: %s: offset like +02:00 or -05:00 */ __( 'UTC%s', 'wp-powersuite' ), $utc_offset ) ); ?></span>
						</span>
					</div>
					<p class="wpps-br-sched-hint wpps-br-sched-hint--tz-detail">
						<?php
						echo wp_kses(
							sprintf(
								/* translators: 1: URL to Settings → General. 2: current UTC offset (e.g. +02:00). */
								__(
									'Scheduled times follow <a href="%1$s">Settings → General → Timezone</a>. The offset <strong>%2$s</strong> is for today—regions that use daylight saving time shift automatically. The clock above is the site’s “now”; WP-Cron usually runs after a page load, so the first run after the scheduled moment may be slightly late unless your host calls <code>wp-cron.php</code> on a system schedule.',
									'wp-powersuite'
								),
								esc_url( $tz_settings ),
								esc_html( $utc_offset )
							),
							[
								'a'      => [ 'href' => true ],
								'strong' => [],
								'code'   => [],
							]
						);
						?>
					</p>
				</div>
			</div>

			<div class="wpps-br-sched-section">
				<div class="wpps-br-sched-section__label"><?php esc_html_e( 'What', 'wp-powersuite' ); ?></div>
				<div class="wpps-br-sched-section__fields">
					<div class="wpps-br-sched-type-pills">
						<?php
						$types = [
							'full'     => __( 'Full backup', 'wp-powersuite' ),
							'database' => __( 'Database only', 'wp-powersuite' ),
							'files'    => __( 'Files only', 'wp-powersuite' ),
						];
						foreach ( $types as $tv => $tl ) :
							$checked_attr = checked( $s['schedule_backup_type'] ?? 'full', $tv, false );
							?>
							<label class="wpps-br-sched-type-pill">
								<input type="radio" name="schedule_backup_type" value="<?php echo esc_attr( $tv ); ?>" <?php echo $checked_attr; ?> />
								<span class="wpps-br-sched-type-pill__text"><?php echo esc_html( $tl ); ?></span>
							</label>
						<?php endforeach; ?>
					</div>
				</div>
			</div>

		</div>
	</div>

	<div class="wpps-br-card wpps-br-sched">
		<div class="wpps-br-sched-header">
			<div class="wpps-br-sched-header__text">
				<h2 style="margin:0;font-size:15px;"><?php esc_html_e( 'Email Notifications', 'wp-powersuite' ); ?></h2>
				<p class="wpps-br-muted" style="margin:4px 0 0;"><?php esc_html_e( 'Get notified when a scheduled backup completes or fails.', 'wp-powersuite' ); ?></p>
			</div>
			<label class="wpps-br-sched-toggle">
				<input type="checkbox" name="schedule_email_enabled" value="1" <?php checked( ! empty( $s['schedule_email_enabled'] ) ); ?> id="wpps-br-email-enabled" />
				<span class="wpps-br-sched-toggle__slider"></span>
			</label>
		</div>

		<div class="wpps-br-sched-body" id="wpps-br-email-fields">
			<div class="wpps-br-sched-section">
				<div class="wpps-br-sched-section__label"><?php esc_html_e( 'Notify on', 'wp-powersuite' ); ?></div>
				<div class="wpps-br-sched-section__fields">
					<div class="wpps-br-sched-type-pills">
						<label class="wpps-br-sched-type-pill">
							<input type="radio" name="schedule_email_on" value="both" <?php checked( $s['schedule_email_on'] ?? 'both', 'both' ); ?> />
							<span class="wpps-br-sched-type-pill__text"><?php esc_html_e( 'Success & failure', 'wp-powersuite' ); ?></span>
						</label>
						<label class="wpps-br-sched-type-pill">
							<input type="radio" name="schedule_email_on" value="failure" <?php checked( $s['schedule_email_on'] ?? '', 'failure' ); ?> />
							<span class="wpps-br-sched-type-pill__text"><?php esc_html_e( 'Failure only', 'wp-powersuite' ); ?></span>
						</label>
					</div>
				</div>
			</div>

			<div class="wpps-br-sched-section">
				<div class="wpps-br-sched-section__label"><?php esc_html_e( 'Send to', 'wp-powersuite' ); ?></div>
				<div class="wpps-br-sched-section__fields">
					<textarea name="schedule_email_recipients" id="wpps-br-email-recipients" rows="2" class="wpps-br-sched-textarea" placeholder="<?php echo esc_attr( get_option( 'admin_email', '' ) ); ?>"><?php echo esc_textarea( (string) ( $s['schedule_email_recipients'] ?? '' ) ); ?></textarea>
					<p class="wpps-br-sched-hint"><?php esc_html_e( 'One email per line. Leave empty to use the site admin email.', 'wp-powersuite' ); ?></p>
				</div>
			</div>
		</div>
	</div>

	<button type="submit" class="button button-primary button-large"><?php esc_html_e( 'Save schedule', 'wp-powersuite' ); ?></button>
</form>
