<?php
/**
 * Filter by date form.
 *
 * @package EaLab\WP_Deployer
 */

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

/**
 * Requires.
 */
require_once __DIR__ . '/../utility/date.php';

/**
 * Filter by date form.
 *
 * @param array<string,mixed> $context The context of the form.
 *
 * @return string Markup.
 */
function deploy_sync_content__filter_by_date__form( array $context ): string {
	$date_field_id = esc_attr( $context['date_field_id'] ?? '' );

	if ( empty( $date_field_id ) ) {
		// No date field ID, so no form.
		return '';
	}

	$form_context = esc_attr( $context['form_context'] ?? '' );

	if ( ! in_array( $form_context, array( 'import', 'export' ), true ) ) {
		// Invalid form context, so no form.
		return '';
	}

	// Parse the date to validate it.
	$datetime = deploy_sync_content__get_datetime_from_url_param( $date_field_id );

	empty( $datetime ) && deploy_sync_content__error_notice( 'Please select a valid date.' );

	$form_action     = esc_url( admin_url( 'admin.php' ) );
	$from_date_label = esc_html__( 'From Date', 'deploy-sync-content' );

	$field_default_value = empty( $datetime ) ? '' : esc_attr( sanitize_text_field( wp_unslash( $_GET[ $date_field_id ] ?? '' ) ) );

	return '
<form action="' . $form_action . '"
      id="filter_by_date_form"
      class="form-deploy"
      method="GET">
    <div class="row g-3 align-items-middle">
        <div class="col-auto">
            <label>' . $from_date_label . '</label>
        </div>
        <div class="col-auto">
            <input type="datetime-local"
                   step="1"
                   id="' . $date_field_id . '"
                   name="' . $date_field_id . '"
                   class="form-control"
                   value="' . $field_default_value . '">
        </div>
        <div class="col-auto">
            <input type="submit" name="submit" id="submit" class="btn btn-primary" value="Go">
        </div>
    </div>
    <input type="hidden" name="action" value="do_export"/>
    <input type="hidden" name="page" value="deploy-sync-content"/>
    <input type="hidden" name="tab" value="' . $form_context . '"/>
</form>
';
}
