<?php
if (!defined('ABSPATH')) {
	exit;
}
if (!is_user_logged_in()) {
	echo "<div class='alert alert-warning'>Please login to view history.</div>";
	return;
}

global $wpdb;
$user_id = get_current_user_id();
$users = new Users();
$vp_id = $users->getUser($user_id, true, true)["id"];
$service_key = $page2;

if ($service_key === 'wallet') {
	include_once __DIR__ . '/wallet-history.php';
	return;
}

if ($service_key === 'ng_verification') {
    include_once __DIR__ . '/verification_history.php';
    return;
}

$service = Vtupress_Service_Container::get($service_key);

if ($service && $service->is_voucher) {
	include_once __DIR__ . '/pin_history.php';
	return;
}

if ($service == null):
	?>
	<div class="alert alert-danger">Service Not Found</div>
	<?php return;
endif;

// Fetch Transactions for User
$transactions = $wpdb->get_results(
	$wpdb->prepare(
		"SELECT * FROM {$wpdb->prefix}vtupress_transactions WHERE service = %s AND user_id = %d ORDER BY id DESC LIMIT 1000",
		$service_key,
		$vp_id
	),
	ARRAY_A
);

$summary = [
	'pending' => 0,
	'successful' => 0,
	'failed' => 0,
	'success_amount' => 0.00,
];

foreach ($transactions as $txn) {
	$status = strtolower($txn['status'] ?? '');
	if ($status === 'pending' || $status === 'processing')
		$summary['pending']++;
	if ($status === 'success' || $status === 'successful') {
		$summary['successful']++;
		$summary['success_amount'] += (float) ($txn['amount'] ?? 0);
	}
	if (in_array($status, ['failed', 'cancled', 'reversed']))
		$summary['failed']++;
}

$base_columns = $service->base_history_columns();
unset($base_columns["profit"]);
$extra_columns = (method_exists($service, 'history_columns')) ? $service->history_columns() : [];
?>

<div class="container-fluid history-container mt-4">
	<style>
		.history-container * {
			font-family: 'Roboto', sans-serif;
		}

		/* Glassmorphism Styling */
		.vtupress-summary {
			padding: 20px 0;
		}

		.vtupress-glass {
			background: rgba(255, 255, 255, 0.7);
			backdrop-filter: blur(10px);
			-webkit-backdrop-filter: blur(10px);
			border: 1px solid rgba(255, 255, 255, 0.3);
			border-radius: 15px;
			padding: 20px;
			transition: all 0.3s ease;
			box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.07);
			display: flex;
			align-items: center;
			height: 100%;
		}

		.vtupress-glass:hover {
			transform: translateY(-5px);
			box-shadow: 0 12px 40px 0 rgba(31, 38, 135, 0.12);
			background: rgba(255, 255, 255, 0.85);
		}

		.glass-icon {
			width: 50px;
			height: 50px;
			border-radius: 12px;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 15px;
			font-size: 1.6rem;
		}

		.glass-content h6 {
			font-size: 0.85rem;
			text-transform: uppercase;
			letter-spacing: 1px;
			font-weight: 600;
			margin-bottom: 5px;
			color: #6c757d;
		}

		.glass-content h3 {
			margin: 0;
			font-weight: 700;
			color: #2d3436;
		}

		/* Status Specific Accents */
		.glass-pending .glass-icon {
			background: rgba(255, 193, 7, 0.15);
			color: #ffc107;
		}

		.glass-success .glass-icon {
			background: rgba(40, 167, 69, 0.15);
			color: #28a745;
		}

		.glass-failed .glass-icon {
			background: rgba(220, 53, 69, 0.15);
			color: #dc3545;
		}

		.glass-amount .glass-icon {
			background: rgba(0, 123, 255, 0.15);
			color: #007bff;
		}

		#vtupress-history {
			background: white;
			border-radius: 10px;
			overflow: hidden;
			border: none;
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		}

		#vtupress-history thead th {
			background-color: #f8f9fa;
			border-bottom: 2px solid #dee2e6;
			color: #495057;
			font-weight: 600;
		}

		/* Receipt Modal Styles */
		.receipt-content {
			border-radius: 15px;
			border: none;
			box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
			overflow: hidden;
		}

		.modal-header {
			background: #f8f9fa;
			border-bottom: 1px solid #dee2e6;
		}

		.receipt-list .receipt-item {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			padding: 10px 0;
			border-bottom: 1px dashed #e9ecef;
		}

		.receipt-list .receipt-item:last-child {
			border-bottom: none;
		}

		.receipt-item .key {
			color: #6c757d;
			font-weight: 500;
			font-size: 0.95rem;
			margin-right: 15px;
			text-transform: capitalize;
		}

		.receipt-item .value {
			color: #212529;
			font-weight: 600;
			text-align: right;
			font-size: 0.95rem;
			word-break: break-word;
		}
	</style>

	<div class="row mb-4 vtupress-summary">
		<!-- Pending Card -->
		<div class="col-xl-3 col-md-6 mb-4">
			<div class="vtupress-glass glass-pending">
				<div class="glass-icon"><i class="mdi mdi-clock-outline"></i></div>
				<div class="glass-content">
					<h6>Pending</h6>
					<h3><?= number_format($summary['pending']) ?></h3>
				</div>
			</div>
		</div>
		<!-- Success Card -->
		<div class="col-xl-3 col-md-6 mb-4">
			<div class="vtupress-glass glass-success">
				<div class="glass-icon"><i class="mdi mdi-check-decagram-outline"></i></div>
				<div class="glass-content">
					<h6>Successful</h6>
					<h3><?= number_format($summary['successful']) ?></h3>
				</div>
			</div>
		</div>
		<!-- Failed Card -->
		<div class="col-xl-3 col-md-6 mb-4">
			<div class="vtupress-glass glass-failed">
				<div class="glass-icon"><i class="mdi mdi-close-octagon-outline"></i></div>
				<div class="glass-content">
					<h6>Failed</h6>
					<h3><?= number_format($summary['failed']) ?></h3>
				</div>
			</div>
		</div>
		<!-- Amount Card -->
		<div class="col-xl-3 col-md-6 mb-4">
			<div class="vtupress-glass glass-amount">
				<div class="glass-icon"><i class="mdi mdi-currency-ngn"></i></div>
				<div class="glass-content">
					<h6>Total Success</h6>
					<h3><?= $currency_symbol . number_format($summary['success_amount'], 2) ?></h3>
				</div>
			</div>
		</div>
	</div>

	<?php if (empty($transactions)): ?>
		<div class="alert alert-info">No Transaction found for this service</div>
		<?php return;
	endif; ?>

	<div class="table-responsive">
		<table id="vtupress-history" class="table table-hover">
			<thead>
				<tr>
					<?php foreach ($base_columns as $label): ?>
						<th><?= esc_html($label) ?></th>
					<?php endforeach; ?>
					<?php foreach ($extra_columns as $label): ?>
						<th><?= esc_html($label) ?></th>
					<?php endforeach; ?>
				</tr>
			</thead>
			<tbody>
				<?php foreach ($transactions as $txn):
					// Prepare data for modal
					$details = !empty($txn['details']) ? json_decode($txn['details'], true) : [];
					if (!is_array($details))
						$details = [];

					$keys = array_keys($details);
					$pos = array_search('software', $keys);
					if ($pos) {
						$details = array_slice($details, 0, $pos, true);
					}

					unset($details["pin"]);
					unset($details["_nonce"]);
					unset($details["nonce"]);
					// unset($txn["status"]);
					// unset($txn["profit"]);
					// unset($txn["created_at"]);
				
					// Merge basic info
					$modalData = [
						'ID' => $txn['id'],
						'Reference' => $txn['reference'] ?? $txn['ref'] ?? '-',
						'Service' => $txn['service'],
						'Amount' => $txn['amount'],
						'Status' => $txn['status'],
					];



					foreach (array_keys($base_columns) as $key):
						if (in_array($key, ['pin', 'response', 'api_response', 'status', 'profit', 'created_at']))
							continue;
						if (isset($txn[$key])) {
							$modalData[ucfirst($key)] = $txn[$key];
						}
					endforeach;
					foreach (array_keys($extra_columns) as $col):
						$modalData[ucfirst($col)] = ($service && method_exists($service, 'resolve_history_column'))
							? esc_html($service->resolve_history_column($col, (array) $txn))
							: '-';
					endforeach;
					$modalData['Date'] = $txn['created_at'] ?? $txn['time'] ?? '-';

					// Add details
					// foreach ($details as $k => $v) {
					// 	if (in_array($k, ['pin', 'response', 'api_response']))
					// 		continue; // Skip sensitive/verbose fields if desired
					// 	$modalData[ucfirst(str_replace('_', ' ', $k))] = is_string($v) ? $v : json_encode($v);
					// }
				
					$jsonReceipt = htmlspecialchars(json_encode($modalData), ENT_QUOTES, 'UTF-8');
					?>
					<tr data-receipt="<?= $jsonReceipt ?>" class="history-row" style="cursor: pointer;">
						<?php foreach (array_keys($base_columns) as $key): ?>
							<td><?= esc_html($txn[$key] ?? '-') ?></td>
						<?php endforeach; ?>
						<?php foreach (array_keys($extra_columns) as $col): ?>
							<td>
								<?= ($service && method_exists($service, 'resolve_history_column'))
									? esc_html($service->resolve_history_column($col, (array) $txn))
									: '-' ?>
							</td>
						<?php endforeach; ?>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	</div>

	<!-- Receipt Modal -->
	<div class="modal fade" id="transactionModal" tabindex="-1" role="dialog" aria-hidden="true">
		<div class="modal-dialog modal-dialog-centered" role="document">
			<div class="modal-content receipt-content">
				<div class="modal-header border-0 pb-0">
					<h5 class="modal-title font-weight-bold">Transaction Receipt</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body">
                    <div class="d-flex justify-content-between align-items-center border-bottom pb-3 mb-3">
                        <div class="d-flex align-items-center">
                            <?php 
                            $icon_url = get_site_icon_url();
                            if($icon_url): ?>
                                <img src="<?= esc_url($icon_url) ?>" alt="Site Logo" style="width: 40px; height: 40px; margin-right: 10px; border-radius: 50%;">
                            <?php else: ?>
                                <span style="font-size: 2rem; margin-right: 10px;">🧾</span>
                            <?php endif; ?>
                            <h5 class="mb-0 font-weight-bold"><?= get_bloginfo('name'); ?></h5>
                        </div>
                        <div class="text-right">
                             <small class="text-muted d-block">Receipt</small>
                             <!-- <small class="text-muted"><?= date('M d, Y') ?></small> -->
                        </div>
                    </div>

					<div class="text-center mb-4">
						<div class="receipt-status-icon ">
							<!-- my-3 -->
							<i id="receipt-icon" class="mdi mdi-check-circle text-success" style="font-size: 4rem;"></i>
						</div>
						<h2 id="receipt-amount-display" class=" font-weight-bold">
							<?= $currency_symbol ?><span class="receipt-amount">0.00</span>
						</h2>
						<span id="receipt-status-display" class="badge bg-success">Success</span>
					</div>

					<div class="receipt-list" id="modal-basic">
						<!-- Populated by JS -->
					</div>

                    <div class="mt-4 text-center border-top pt-3">
                        <small class="text-muted">Receipt generated from <?= get_bloginfo('name'); ?></small>
                    </div>
				</div>
				<div class="modal-footer border-0 justify-content-center" data-html2canvas-ignore="true">
					<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					<button type="button" class="btn btn-primary downloadHistory">Download</button>
					<!-- <button type="button" class="btn btn-info text-white" id="download-btn">Download</button> -->
				</div>
			</div>
		</div>
	</div>

	<script>
		jQuery(function ($) {
			if ($.fn.DataTable) {
				$('#vtupress-history').DataTable({
					pageLength: 25,
					order: [[0, 'desc']],
					responsive: true,
					language: {
						search: "_INPUT_",
						searchPlaceholder: "Search records..."
					}
				});
			}

			$('.history-row').on('click', function () {
				var receiptData = $(this).data('receipt');

				// Clear Modal
				$('#modal-basic').empty();

				// Set Header Info
				var status = (receiptData.Status || '').toLowerCase();
				var amount = receiptData.Amount || '<?= $currency_symbol ?>0.00';

				$('#receipt-amount-display').text('<?= $currency_symbol ?>' + amount);
				$('#receipt-status-display').text(receiptData.Status).removeClass('bg-success bg-danger bg-warning');

				var iconClass = 'mdi-clock-outline text-warning';
				var badgeClass = 'bg-warning';

				if (status === 'success' || status === 'successful') {
					iconClass = 'mdi-check-circle text-success';
					badgeClass = 'bg-success';
				} else if (status === 'failed' || status === 'cancled' || status === 'cancelled') {
					iconClass = 'mdi-close-circle text-danger';
					badgeClass = 'bg-danger';
				}

				$('#receipt-icon').attr('class', 'mdi ' + iconClass);
				$('#receipt-status-display').addClass(badgeClass);

				// Populate List
				$.each(receiptData, function (k, v) {
					$('#modal-basic').append(`
						<div class="receipt-item ${k.toLowerCase()}">
							<span class="key">${k}</span>
							<span class="value">${v}</span>
						</div>
					`);
				});

				// Show Modal
				// var transactionModal = new bootstrap.Modal(document.getElementById('transactionModal'));
				// transactionModal.show();
				$('#transactionModal').modal('show');
			});


			$('.downloadHistory').on('click', function () {
				if (typeof html2pdf === 'undefined') {
					alert('PDF library not loaded. Please reload the page.');
					return;
				}
				
				var btn = jQuery(this);
				var originalText = btn.text();
				// Select the specific modal content that contains the button
				var element = $(this).closest('.modal-content').get(0); 
				var recipient = '<?= $service_key;?>-'+jQuery(".recipient .value").text() || '';
				btn.text('Downloading...');
				
				var opt = {
					margin: 10,
					filename: recipient + '.pdf',
					image: { type: 'jpeg', quality: 0.98 },
					html2canvas: { scale: 2, logging: true, useCORS: true, scrollY: 0 },
					jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
				};

				html2pdf().set(opt).from(element).save().then(function(){
					btn.text(originalText);
				});
			});
		});
	</script>
</div>