<?php
if (!defined('ABSPATH')) {
    exit;
}
// Check nonce for GET input security
$nonce = isset($_GET['cfn']) ? sanitize_text_field(wp_unslash($_GET['cfn'])) : '';

if (! $nonce || ! wp_verify_nonce($nonce, 'chama_view_transactions_nonce')) {
    chama_errors()->add('invalid_request', __('Invalid request.', 'chama'));
    exit;
}

$user_id = get_query_var('user_id') !== '' && get_query_var('user_id') ? (int) get_query_var('user_id') : 0;
$transactions_query = null;

$tab = isset($_GET['tab']) ? sanitize_text_field( wp_unslash($_GET['tab'])) : 'profile';

$status = isset($_GET['status']) ? sanitize_text_field( wp_unslash($_GET['status'])) : 0; 
$status_message = '';
$cpt = $type = $description = '';

$paged = isset($_GET['transactions_paged']) ? (int) $_GET['transactions_paged'] : 1; 
$confirmation_url = CHAMA_PAYMENT_CONFIRMATION_URL;
$show_description = false;
$is_subscription = false;
$subscription_status = '';
$no_transactions_message = '';

switch ($status) {
    case 'canceled':
        $stripe_current_period_end = get_user_meta($user_id, 'chama_subscription_current_period_end', true);
        $status_message = 'Your subscription has been successfully canceled. You will continue to enjoy your membership benefits until ' . $stripe_current_period_end;
        break;
    case 'paused':
        $status_message = 'Your subscription has been successfully paused.';
        break;
    case 'resumed':
        $status_message = 'Your subscription has been successfully resumed.';
        break;
    default:
        break;
}
switch ($tab) {
    case 'donations':
        $cpt = 'chama_donation';
        $type = 'one-time';
        $no_transactions_message = 'You currently do not have any donations.';
        break;
    case 'subscriptions':
        $cpt = 'chama_subscription';
        $type = 'membership';
        $confirmation_url = CHAMA_SUBSCRIPTION_CONFIRMATION_URL;
        $show_description = true;
        $is_subscription = true;
        $no_transactions_message = 'You currently do not have any subscriptions.';
        break;
    case 'crowdfunding':
        $cpt = 'chama_fund';
        $type = 'crowdfunding';
        $show_description = true;
        $no_transactions_message = 'You are currently not supporting any crowdfunding campaigns.';
        break;
    case 'commissions':
        $cpt = 'chama_com_order';
        $type = 'commission';
        $show_description = true;
        $no_transactions_message = 'You currently do not have any orders.';
        break;
    default:
        break;
}
if ($user_id) {
    $transactions_args = array(
        'post_type' => $cpt,
        'post_status' => 'publish',
        'posts_per_page' => 15,
        'paged' => $paged,
        'orderby' => 'post_date',
        'order' => 'desc',
        'meta_key' => 'chama_user_id',// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
        'meta_value' => $user_id,// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
    );
    if ($tab == 'subscriptions') {
        $meta_query_args = array(
            'key' => 'chama_subscription_event',
            'value' => 'creation',
        );
        $transactions_args['meta_query'] = $meta_query_args;// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
    }
    $transactions_query = new WP_Query($transactions_args);

} else {
    // invalid reqeuest
    chama_errors()->add('invalid_request', __('Invalid request.' , 'chama'));
    exit;
}
?>



        <div id="chama-page-content-wrapper">
        <div id="chama-page-content">
            <?php if ($status_message): ?>
        <div role="alert" class="chama-alert chama-alert-success"><?php echo esc_html($status_message);?></div>
        <?php endif;?>
       <?php

if ($transactions_query && $transactions_query->found_posts) {
    ?>
            <div class="chama-transactions-table-wrapper">
            <table class="chama-transactions-table">
    <tr>
        <?php if ($show_description): ?>
        <th>Description</th>
        <?php endif;?>
        <th>Payment</th>
        <?php if ($is_subscription): ?>
        <th>Subscription</th>
        <?php endif;?>
        <th>Date</th>
        <th>Amount</th>
        <?php if ($is_subscription): ?>
        <th>Update</th>
        <?php endif;?>
        <th>Receipt</th>
    </tr>
            <?php
/* Start the Loop */
    while ($transactions_query->have_posts()): $transactions_query->the_post();
        $id = get_the_ID();
        $currency = get_post_meta($id, $cpt . '_currency', true);
        $amount = get_post_meta($id, $cpt . '_total_amount', true);
        $transaction_date = get_post_meta($id, $cpt . '_date_time', true);
        $transaction_date_formatted = gmdate("F, j, Y", strtotime($transaction_date));
        $status = get_post_meta($id, 'chama_payment_status', true);
        $confirmation_receipt_id = base64_encode($id);
        $description = get_post_meta($id, $cpt . '_description', true);
        $subscription_status = get_post_meta($id, 'chama_subscription_status', true);
        $receipt_url = add_query_arg(
            array(
                'receipt-id' => $confirmation_receipt_id,
                'type' => $type,
            ),
            $confirmation_url
        );

        ?>
				    <tr>
		                <?php if ($show_description): ?>
		                <td><?php echo esc_html($description); ?></td>
		                <?php endif;?>
		        <td><?php echo '<span class="chama-payment-status listing-status"><span class="chama-payment-status-icon ' . esc_attr($status) . '"></span>&nbsp;' . esc_html(ucwords($status)) . '</span> '; ?></td>
                <?php if ($is_subscription): ?>
                    <td><?php echo '<span class="chama-subscription-status listing-status"><span class="chama-subscription-status-icon ' . esc_attr($subscription_status) . '"></span>&nbsp;' . esc_html(ucwords($subscription_status)) . '</span> '; ?></td>
        <?php endif;?>
		        <td><?php echo esc_html($transaction_date_formatted); ?></td>
		        <td  class="chama-action-col"><?php echo esc_html(CHAMA_SYMBOL . number_format((float) $amount, 2, '.', '')); ?></td>
                <?php if ($is_subscription): ?>
                <td  class="chama-action-col">
                    <div class="chama-action-group">
                <?php if ($subscription_status == 'active'): ?>
                    <button class="chama-cancel-subscription chama-action chama-action-red" type="button" data-id="<?php echo esc_attr($id); ?>"><i class="fa-solid fa-ban"></i> Cancel</button>
                    <?php elseif ($subscription_status == 'canceled'): ?>
                        <button class="chama-cancel-subscription chama-action disabled chama-action-red" type="button" disabled="disabled"><i class="fa-solid fa-ban"></i> Canceled</button>

                    <?php endif;?>
           
                    </div>
                </td>
                <?php endif;?>
		        <td class="chama-action-col"><a href="<?php echo esc_url($receipt_url); ?>">View Receipt</a></td>
		    </tr>
		<?php
endwhile;
    wp_reset_postdata();
    ?>
</table>
</div>
 <!-- Start Pagination -->
 <?php
// Set up paginated links.
    // Preserve nonce from request or create a new one
$links = paginate_links(array(
        'format' => '?transactions_paged=%#%',
        'current' => $paged,
        'total' => $transactions_query->max_num_pages,
        'prev_text' => wp_kses(__('<i class=\'fas fa-chevron-left\'></i>', 'chama'), array('i' => array('class' => array()))),
        'next_text' => wp_kses(__('<i class=\'fas fa-chevron-right\'></i>', 'chama'), array('i' => array('class' => array()))),
    ));

    if ($links):

    ?>

<nav class="chama-pagination">

            <?php echo wp_kses($links, array(
        'a' => array(
            'href' => array(),
            'class' => array(),
        ),
        'i' => array(
            'class' => array(),
        ),
        'span' => array(
            'class' => array(),
        ),
    )); ?>

    </nav><!--/ .navigation -->
    <?php
endif;
    ?>
 <!-- End Pagination -->
  <?php
} else {
    echo esc_html($no_transactions_message);
}
?>

            </div>
</div>

<!--modal-->
<div class="chama_modal micromodal-slide" id="chama-modal" aria-hidden="true">
    <div class="chama_modal__overlay" tabindex="-1" data-micromodal-close>
      <div class="chama_modal__container" role="dialog" aria-modal="true" aria-labelledby="chama-modal-title">
        <header class="chama_modal__header">
          <h2 class="chama_modal__title" id="chama-modal-title">
          <i class="fa-solid fa-triangle-exclamation"></i> <span>Cancel</span>
          </h2>
          <button class="chama_modal__close" aria-label="Close modal" data-micromodal-close></button>
        </header>
        <main class="chama_modal__content" id="chama-modal-content">
        <div id="chama-transaction-errors" role="alert" class="chama-alert chama-alert-error"></div>
          <p id="chama-modal-warning">
          </p>
        </main>
        <footer class="chama_modal__footer">
          <button id="chama-confirm-cancelation" class="chama_modal__btn chama_modal_btn_red"><i class="chama-button-spinner fa-solid fa-circle-notch fa-spin chama-hide"></i>Yes, cancel</button>
          <button id="chama-confirm-pause" class="chama_modal__btn chama_modal_btn_orange"><i class="chama-button-spinner fa-solid fa-circle-notch fa-spin chama-hide"></i>Yes, pause</button>
          <button id="chama-confirm-resume" class="chama_modal__btn chama_modal_btn_orange"><i class="chama-button-spinner fa-solid fa-circle-notch fa-spin chama-hide"></i>Yes, resume</button>
          <button id="chama-modal-close" class="chama_modal__btn" data-micromodal-close aria-label="Close this dialog window">Nevermind</button>
          <?php wp_nonce_field('wp_rest')?>
          <input type="hidden" id="chama_base_rest_url" name="chama_base_rest_url" value="<?php echo esc_url(get_rest_url(null, '/')); ?>" />
        </footer>
      </div>
    </div>
  </div>



