<?php

defined( 'ABSPATH' ) or exit;

foreach ( $gift_cards as $gift_card ) {

    $recipient_email = $gift_card->get_recipient_email();
    if ( empty( $recipient_email ) && ( ! defined( 'PWGC_SKIP_RECIPIENT_EMAIL_LOOKUP' ) || false === PWGC_SKIP_RECIPIENT_EMAIL_LOOKUP ) ) {

        // Do not look up cards that are scheduled for delivery.
        $scheduled_date = pwgc_delivery_date_to_time( $gift_card->get_original_order_item_meta_data( PWGC_DELIVERY_DATE_META_KEY ) );
        if ( empty( $scheduled_date ) || $scheduled_date <= strtotime( 'today midnight', current_time( 'timestamp' ) ) ) {
            $recipient_email = $gift_card->get_original_recipient();
            if ( !empty( $recipient_email ) ) {
                // Save it with the gift card to prevent having to look it up in the future.
                $gift_card->set_recipient_email( $recipient_email );
            } else {
                // Couldn't find it, set it to an empty space to prevent future lookups.
                $gift_card->set_recipient_email( ' ' );
            }
        }
    }

    $from = $gift_card->get_from();
    if ( empty( $from ) ) {
        $from = get_option( 'blogname' );
    }

    $pdf_url = pwgc_view_email_url( array(
        'pwgc_number'       => $gift_card->get_number(),
        'design_id'         => $gift_card->get_email_design_id(),
        'recipient_name'    => !empty( $gift_card->get_recipient_name() ) ? urlencode( $gift_card->get_recipient_name() ) : '',
        'from'              => !empty( $gift_card->get_from() ) ? urlencode( $gift_card->get_from() ) : '',
        'message'           => !empty( $gift_card->get_message() ) ? urlencode( $gift_card->get_message() ) : '',
        'pdf'               => 1,
    ) );


    ?>
    <tr data-gift-card-number="<?php esc_attr_e( $gift_card->get_number() ); ?>">
        <td class="pwgc-search-result-card-number">
            <?php echo esc_html( $gift_card->get_number() ); ?>
            <div class="pwgc-inactive-card pwgc-balance-error <?php if ( $gift_card->get_active() ) { echo 'pwgc-hidden'; } ?>">
                <?php _e( 'Card has been deleted.', 'pw-woocommerce-gift-cards' ); ?>
            </div>
        </td>
        <td class="pwgc-search-result-balance">
            <?php echo wc_price( $gift_card->get_balance() ); ?>
        </td>
        <td class="pwgc-search-result-expiration-date pwgc-expiration-date-element" <?php if ( 'no' !== get_option( 'pwgc_no_expiration_date', 'no' ) ) { echo 'style="display: none;"'; } ?>>
            <?php
                echo $gift_card->get_expiration_date_html();
            ?>
        </td>
        <td class="pwgc-search-result-recipient-email">
            <div style="max-width: 400px; word-wrap: break-word; white-space: normal !important;">
                <?php
                    if ( !empty( trim( $gift_card->get_recipient_email() ) ) ) {
                        ?>
                        <a href="mailto: <?php echo esc_html( $gift_card->get_recipient_email() ); ?>"><?php echo esc_html( $gift_card->get_recipient_email() ); ?></a>
                        <?php
                    }
                ?>
            </div>
        </td>
        <td class="pwgc-search-result-buttons">
            <a href="#" class="pwgc-view-activity button button-secondary"><i class="fas fa-history"></i> <?php _e( 'View activity', 'pw-woocommerce-gift-cards' ); ?></a>
            <span class="pwgc-buttons-active <?php if ( !$gift_card->get_active() ) { echo 'pwgc-hidden'; } ?>">
                <a href="#" class="pwgc-add-note button button-secondary"><i class="far fa-sticky-note"></i> <?php _e( 'Add a note', 'pw-woocommerce-gift-cards' ); ?></a>
                <a href="#" class="pwgc-adjust-balance button button-secondary"><i class="fas fa-balance-scale"></i> <?php _e( 'Adjust balance', 'pw-woocommerce-gift-cards' ); ?></a>
                <a href="#" class="pwgc-expiration-date button button-secondary pwgc-expiration-date-element" <?php if ( 'no' !== get_option( 'pwgc_no_expiration_date', 'no' ) ) { echo 'style="display: none;"'; } ?>><i class="fas fa-calendar-alt"></i> <?php _e( 'Set expiration date', 'pw-woocommerce-gift-cards' ); ?></a>
                <a href="#" class="pwgc-email button button-secondary"><i class="fas fa-envelope"></i> <?php _e( 'Email Gift Card', 'pw-woocommerce-gift-cards' ); ?></a>
                <a href="<?php echo $pdf_url; ?>" class="pwgc-pdf button button-secondary" target="_blank"><i class="fas fa-file-pdf"></i> <?php _e( 'PDF', 'pw-woocommerce-gift-cards' ); ?></a>
                <a href="#" class="pwgc-delete button button-secondary"><i class="fas fa-times"></i> <?php _e( 'Delete', 'pw-woocommerce-gift-cards' ); ?></a>
            </span>
            <span class="pwgc-buttons-inactive <?php if ( $gift_card->get_active() ) { echo 'pwgc-hidden'; } ?>">
                <a href="#" class="pwgc-restore button button-secondary"><i class="fas fa-history"></i> <?php _e( 'Restore', 'pw-woocommerce-gift-cards' ); ?></a>
                <a href="#" class="pwgc-delete-permanently button button-secondary"><i class="fas fa-times"></i> <?php _e( 'Delete Permanently', 'pw-woocommerce-gift-cards' ); ?></a>
            </span>
        </td>
    </tr>
    <?php
}
    if ( count( $gift_cards ) == PWGC_ADMIN_MAX_ROWS ) {
        ?>
        <tr class="pwgc-search-results-more" style="background-color: initial;">
            <td colspan="6">
                <a href="#" id="pwgc-search-results-more-button" class="button button-primary"><?php _e( 'Load more', 'pw-woocommerce-gift-cards' ); ?></a>
                <script>
                    jQuery('#pwgc-search-results-more-button').on('click', function(e) {
                        var messageContainer = jQuery('.pwgc-search-results-more');
                        messageContainer.html('<i class="fas fa-cog fa-spin fa-3x"></i>');

                        var searchTerms = jQuery('#pwgc-balance-search');
                        var offset = jQuery('#pwgc-search-results-table tr').length - 2; // Accounts for this row and the header row.

                        jQuery.post(ajaxurl, {'action': 'pw-gift-cards-search_load_more', 'search_terms': searchTerms.val(), 'offset': offset}, function(result) {
                            jQuery('#pwgc-search-results-table tr:last').after(result.html);
                            messageContainer.remove();
                        }).fail(function(xhr, textStatus, errorThrown) {
                            messageContainer.remove();
                            if (errorThrown) {
                                alert(errorThrown);
                            } else {
                                alert('Unknown Error');
                            }
                        });

                        e.preventDefault();
                        return false;
                    });
                </script>
            </td>
        </tr>
        <?php
    }
?>
<script>
    jQuery('.pwgc-view-activity').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');

        // Hide the Email grid if it is visible.
        row.find('.pwgc-balance-email-container').remove();

        // Toggle the View Activity.
        if (row.find('.pwgc-balance-activity-table').length > 0) {
            row.find('.pwgc-balance-activity-container').remove();
        } else {
            pwgcAdminGiftCardActivity(row);
        }

        e.preventDefault();
        return false;
    });

    jQuery('.pwgc-adjust-balance').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');
        var amount = prompt( pwgc.i18n.adjustment_amount_prompt );
        if (amount) {
            pwgcAdjustBalance(row, amount);
        }

        e.preventDefault();
        return false;
    });

    jQuery('.pwgc-add-note').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');
        pwgcAdjustBalance(row, 0);

        e.preventDefault();
        return false;
    });

    jQuery('.pwgc-expiration-date').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');
        pwgcSetExpirationDate(row);

        e.preventDefault();
        return false;
    });

    jQuery('.pwgc-email').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');

        pwgcToggleEmailGiftCard(row);

        e.preventDefault();
        return false;
    });

    jQuery('.pwgc-delete').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');
        if (confirm('<?php _e( 'Are you sure you want to delete this gift card?', 'pw-woocommerce-gift-cards' ); ?>')) {
            pwgcDelete(row);
        }

        e.preventDefault();
        return false;
    });

    jQuery('.pwgc-delete-permanently').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');
        if (confirm('<?php _e( 'Are you sure you want to PERMANENTLY delete this gift card? This action cannot be undone!', 'pw-woocommerce-gift-cards' ); ?>')) {
            pwgcDelete(row);
        }

        e.preventDefault();
        return false;
    });

    jQuery('.pwgc-restore').off('click').on('click', function(e) {
        var row = jQuery(this).closest('tr');
        pwgcRestore(row);

        e.preventDefault();
        return false;
    });
</script>
<?php
