<link href="<?php echo base_url('assets/css/admin-panel.css'); ?>?v=20260826b" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<?php
$r = $request;
$acct = $r['stripeaccount_id'];
$acctShort = $acct !== '' ? (strlen($acct) > 12 ? substr($acct, 0, 10) . '…' : $acct) : '—';
$st = strtolower($r['status']);
?>

<div class="care-admin">
	<div class="ca-hero">
		<div class="ca-hero-inner row align-items-center g-3">
			<div class="col-lg-7">
				<p class="ca-kicker">Payments</p>
				<h1 class="ca-title">Payout request</h1>
				<p class="ca-sub mb-2">ID: <code class="small"><?php echo htmlspecialchars($r['id']); ?></code></p>
				<?php if ($st === 'pending'): ?>
					<span class="badge rounded-pill ca-pill bg-warning text-dark">Pending</span>
				<?php elseif ($st === 'processing'): ?>
					<span class="badge rounded-pill ca-pill bg-info">Processing</span>
				<?php elseif ($st === 'approved'): ?>
					<span class="badge rounded-pill ca-pill bg-success">Approved</span>
				<?php else: ?>
					<span class="badge rounded-pill ca-pill bg-danger">Rejected</span>
				<?php endif; ?>
			</div>
			<div class="col-lg-5">
				<div class="ca-nav justify-content-lg-end flex-wrap">
					<a href="<?php echo base_url('admin/payments'); ?>" class="btn btn-light">Back</a>
					<?php if ($st === 'pending' || $st === 'processing'): ?>
						<button type="button" class="btn btn-primary" id="approveBtn" <?php echo empty($stripe_ready) ? 'disabled' : ''; ?>>Transfer</button>
						<button type="button" class="btn btn-outline-danger" id="rejectBtn">Reject</button>
					<?php endif; ?>
				</div>
			</div>
		</div>
	</div>

	<?php if (empty($stripe_ready) && $st === 'pending'): ?>
		<div class="alert alert-warning">Stripe secret key is missing in <code>application/config/stripe.php</code>.</div>
	<?php endif; ?>

	<div class="row g-3">
		<div class="col-lg-4">
			<div class="ca-card mb-3">
				<div class="ca-card-header"><h5 class="ca-card-title mb-0">User</h5></div>
				<div class="ca-card-body">
					<p class="mb-2"><span class="text-muted small d-block">Name</span><?php echo htmlspecialchars($r['userName'] !== '' ? $r['userName'] : '—'); ?></p>
					<p class="mb-2"><span class="text-muted small d-block">Email</span><?php echo htmlspecialchars($r['email'] !== '' ? $r['email'] : '—'); ?></p>
					<p class="mb-2"><span class="text-muted small d-block">Contact</span><?php echo htmlspecialchars($r['contactDetail'] !== '' ? $r['contactDetail'] : '—'); ?></p>
					<p class="mb-0"><span class="text-muted small d-block">User ID</span><code class="small"><?php echo htmlspecialchars($r['userId']); ?></code></p>
				</div>
			</div>
			<div class="ca-card">
				<div class="ca-card-header"><h5 class="ca-card-title mb-0">Payout</h5></div>
				<div class="ca-card-body">
					<p class="mb-2"><span class="text-muted small d-block">Coins</span><strong><?php echo (int) $r['points']; ?></strong></p>
					<p class="mb-2"><span class="text-muted small d-block">Amount</span>$<?php echo htmlspecialchars($r['amountUsd']); ?> <span class="small text-muted">(<?php echo (int) $r['amount']; ?> cents)</span></p>
					<p class="mb-2"><span class="text-muted small d-block">Stripe account</span><code class="small"><?php echo htmlspecialchars($acctShort); ?></code></p>
					<p class="mb-0"><span class="text-muted small d-block">Redeem via</span><?php echo htmlspecialchars($r['redeemVia'] !== '' ? $r['redeemVia'] : '—'); ?></p>
				</div>
			</div>
		</div>
		<div class="col-lg-8">
			<div class="ca-card mb-3">
				<div class="ca-card-header"><h5 class="ca-card-title mb-0">Status</h5></div>
				<div class="ca-card-body">
					<div class="row g-3">
						<div class="col-md-6">
							<p class="mb-0"><span class="text-muted small d-block">Requested</span><?php echo htmlspecialchars($r['requestDateLabel']); ?></p>
						</div>
						<div class="col-md-6">
							<p class="mb-0"><span class="text-muted small d-block">Transfer status</span><?php echo htmlspecialchars($r['transferStatus'] !== '' ? $r['transferStatus'] : '—'); ?></p>
						</div>
						<div class="col-md-6">
							<p class="mb-0"><span class="text-muted small d-block">Approved at</span><?php echo htmlspecialchars($r['approvedAtLabel']); ?></p>
						</div>
						<div class="col-md-6">
							<p class="mb-0"><span class="text-muted small d-block">Rejected at</span><?php echo htmlspecialchars($r['rejectedAtLabel']); ?></p>
						</div>
						<div class="col-md-6">
							<p class="mb-0"><span class="text-muted small d-block">Transfer ID</span><?php echo htmlspecialchars($r['transferId'] !== '' ? $r['transferId'] : '—'); ?></p>
						</div>
						<div class="col-md-6">
							<p class="mb-0"><span class="text-muted small d-block">Coins refunded</span><?php echo !empty($r['pointsRefunded']) ? 'Yes' : 'No'; ?></p>
						</div>
						<?php if ($r['error'] !== ''): ?>
							<div class="col-12">
								<p class="mb-0"><span class="text-muted small d-block">Error</span><?php echo htmlspecialchars($r['error']); ?></p>
							</div>
						<?php endif; ?>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function () {
	var id = <?php echo json_encode($r['id']); ?>;
	var name = <?php echo json_encode($r['userName'] !== '' ? $r['userName'] : ($r['email'] !== '' ? $r['email'] : 'this user')); ?>;
	var points = <?php echo json_encode((string) (int) $r['points']); ?>;
	var amount = <?php echo json_encode($r['amountUsd']); ?>;
	var approveBtn = document.getElementById('approveBtn');
	var rejectBtn = document.getElementById('rejectBtn');

	function escapeHtml(str) {
		return String(str == null ? '' : str)
			.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;').replace(/'/g, '&#039;');
	}
	function toast(icon, title, text) {
		return Swal.fire({
			icon: icon,
			title: title,
			text: text || '',
			confirmButtonColor: icon === 'error' ? '#dc3545' : '#6981C5'
		});
	}
	function showProcessing(title) {
		return Swal.fire({
			title: title || 'Processing…',
			text: 'Please wait. Do not close this page.',
			allowOutsideClick: false,
			allowEscapeKey: false,
			didOpen: function () { Swal.showLoading(); }
		});
	}
	function post(url, extra) {
		return fetch(url, {
			method: 'POST',
			headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
			body: extra || ''
		}).then(function (res) { return res.json(); }).then(function (json) {
			if (!json || !json.ok) throw new Error((json && json.error) ? json.error : 'Request failed');
			return json;
		});
	}
	function runAction(isApprove) {
		var opts = isApprove ? {
			icon: 'question',
			title: 'Transfer this payout?',
			html: 'Send <strong>$' + escapeHtml(amount) + '</strong> (' + escapeHtml(points) + ' coins) to <strong>' + escapeHtml(name) + '</strong> via Stripe.',
			showCancelButton: true,
			confirmButtonText: 'Yes, transfer',
			cancelButtonText: 'Cancel',
			confirmButtonColor: '#6981C5',
			cancelButtonColor: '#6c757d'
		} : {
			icon: 'warning',
			title: 'Reject this payout?',
			html: '<strong>' + escapeHtml(name) + '</strong> will be refunded <strong>' + escapeHtml(points) + ' coins</strong>. This cannot be undone.',
			input: 'textarea',
			inputPlaceholder: 'Reason (optional)',
			inputAttributes: { maxlength: 240 },
			showCancelButton: true,
			confirmButtonText: 'Yes, reject',
			cancelButtonText: 'Cancel',
			confirmButtonColor: '#dc3545',
			cancelButtonColor: '#6c757d'
		};
		Swal.fire(opts).then(function (res) {
			if (!res.isConfirmed) return;
			showProcessing(isApprove ? 'Transferring payout…' : 'Rejecting payout…');
			var extra = (!isApprove && res.value) ? ('reason=' + encodeURIComponent(String(res.value))) : '';
			var url = (isApprove
				? <?php echo json_encode(base_url('admin/payment_approve/')); ?>
				: <?php echo json_encode(base_url('admin/payment_reject/')); ?>) + encodeURIComponent(id);
			post(url, extra).then(function () {
				return toast('success', isApprove ? 'Payout transferred' : 'Payout rejected', isApprove
					? 'Stripe transfer completed and the user was notified.'
					: 'Coins were refunded and the user was notified.');
			}).then(function () {
				window.location.reload();
			}).catch(function (err) {
				toast('error', isApprove ? 'Transfer failed' : 'Reject failed', err && err.message ? err.message : 'Request failed')
					.then(function () { window.location.reload(); });
			});
		});
	}

	if (approveBtn) approveBtn.addEventListener('click', function () { runAction(true); });
	if (rejectBtn) rejectBtn.addEventListener('click', function () { runAction(false); });
})();
</script>
