<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">

<div class="care-admin" id="sleeperPayments">
	<div class="ca-hero">
		<div class="ca-hero-inner row align-items-center g-3">
			<div class="col-lg-8">
				<p class="ca-kicker">Billing</p>
				<h1 class="ca-title"><?php echo isset($page_title) ? htmlspecialchars($page_title) : 'Payments'; ?></h1>
				<p class="ca-sub mb-0">User withdrawal requests from <code>redemption_requests</code>. Default status is pending until you transfer or reject.</p>
			</div>
			<div class="col-lg-4">
				<div class="ca-nav justify-content-lg-end flex-wrap">
					<a href="<?php echo base_url('admin/export_payments'); ?>" class="btn btn-light"><i class="fa-solid fa-file-csv me-2"></i>Export CSV</a>
				</div>
			</div>
		</div>
	</div>

	<?php if (!empty($load_error)): ?>
		<div class="alert alert-danger">Could not load payouts: <?php echo htmlspecialchars($load_error); ?></div>
	<?php endif; ?>
	<?php if (empty($stripe_ready)): ?>
		<div class="alert alert-warning">Stripe secret key is missing. Add it in <code>application/config/stripe.php</code> before approving transfers.</div>
	<?php endif; ?>

	<div class="row g-3 mb-4">
		<div class="col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-hourglass-half"></i></div>
				<p class="ca-stat-label">Pending</p>
				<div class="display-6 fw-bold mb-0"><?php echo (int) $kpis['pending']; ?></div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-circle-check"></i></div>
				<p class="ca-stat-label">Approved</p>
				<div class="display-6 fw-bold mb-0"><?php echo (int) $kpis['approved']; ?></div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-circle-xmark"></i></div>
				<p class="ca-stat-label">Rejected</p>
				<div class="display-6 fw-bold mb-0"><?php echo (int) $kpis['rejected']; ?></div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="ca-stat h-100">
				<div class="ca-stat-icon"><i class="fa-solid fa-sack-dollar"></i></div>
				<p class="ca-stat-label">Pending (Stripe cents)</p>
				<div class="display-6 fw-bold mb-0"><?php echo (int) $kpis['pending_amount']; ?></div>
			</div>
		</div>
	</div>

	<div class="ca-card">
		<div class="ca-card-header d-flex flex-column flex-lg-row align-items-lg-center justify-content-lg-between gap-2">
			<div>
				<h5 class="ca-card-title mb-1"><i class="fa-solid fa-building-columns me-2 text-success"></i>Withdrawals</h5>
				<p class="mb-0">Approve runs a Stripe transfer to the user’s connected account.</p>
			</div>
			<div class="d-flex align-items-stretch gap-2 flex-wrap justify-content-lg-end">
				<span class="badge rounded-pill ca-pill bg-light text-dark border align-self-center" id="payCountLabel">Showing 0</span>
				<div class="input-group" style="min-width: 240px;">
					<span class="input-group-text bg-white"><i class="fa-solid fa-magnifying-glass"></i></span>
					<input type="search" class="form-control" id="paySearch" placeholder="Search user, email, ID">
				</div>
				<select class="form-select" id="payStatus" style="width: 170px;">
					<option value="all" selected>All statuses</option>
					<option value="pending">Pending</option>
					<option value="approved">Approved</option>
					<option value="rejected">Rejected</option>
				</select>
			</div>
		</div>
		<div class="ca-card-body p-0">
			<div class="ca-table-wrap border-0 rounded-0 border-top">
				<table class="table ca-table table-striped mb-0 align-middle">
					<thead>
						<tr>
							<th>User</th>
							<th>Coins</th>
							<th>Amount</th>
							<th>Requested</th>
							<th>Status</th>
							<th class="text-end">Actions</th>
						</tr>
					</thead>
					<tbody id="payTbody">
						<?php if (empty($requests)): ?>
							<tr class="js-empty-row">
								<td colspan="6" class="text-center text-muted py-4">No payouts found.</td>
							</tr>
						<?php else: ?>
							<?php foreach ($requests as $r): ?>
								<?php
								$st = strtolower($r['status']);
								$name = $r['userName'] !== '' ? $r['userName'] : ($r['email'] !== '' ? $r['email'] : $r['userId']);
								$canAct = ($st === 'pending' || $st === 'processing');
								?>
								<tr>
									<td class="fw-semibold">
										<div><?php echo htmlspecialchars($name !== '' ? $name : '—'); ?></div>
										<div class="small text-muted"><?php echo htmlspecialchars($r['email'] !== '' ? $r['email'] : $r['contactDetail']); ?></div>
									</td>
									<td><?php echo (int) $r['points']; ?></td>
									<td>
										<strong>$<?php echo htmlspecialchars($r['amountUsd']); ?></strong>
										<div class="small text-muted"><?php echo (int) $r['amount']; ?> cents</div>
									</td>
									<td class="small text-muted"><?php echo htmlspecialchars($r['requestDateLabel']); ?></td>
									<td>
										<?php if ($st === 'pending'): ?>
											<span class="badge bg-warning-subtle text-warning border border-warning-subtle">Pending</span>
										<?php elseif ($st === 'processing'): ?>
											<span class="badge bg-info-subtle text-info border border-info-subtle">Processing</span>
										<?php elseif ($st === 'approved'): ?>
											<span class="badge bg-success-subtle text-success border border-success-subtle">Approved</span>
										<?php else: ?>
											<span class="badge bg-danger-subtle text-danger border border-danger-subtle"><?php echo htmlspecialchars(ucfirst($st)); ?></span>
										<?php endif; ?>
									</td>
									<td class="text-end">
										<div class="btn-group">
											<a class="btn btn-sm btn-light border" href="<?php echo base_url('admin/payment_view/' . rawurlencode($r['id'])); ?>">View</a>
											<?php if ($canAct): ?>
												<button type="button" class="btn btn-sm btn-primary" data-action="approve" data-id="<?php echo htmlspecialchars($r['id']); ?>" data-name="<?php echo htmlspecialchars($name); ?>" data-points="<?php echo (int) $r['points']; ?>" data-amount="<?php echo htmlspecialchars($r['amountUsd']); ?>" <?php echo empty($stripe_ready) ? 'disabled' : ''; ?>>Transfer</button>
												<button type="button" class="btn btn-sm btn-outline-danger" data-action="reject" data-id="<?php echo htmlspecialchars($r['id']); ?>" data-name="<?php echo htmlspecialchars($name); ?>" data-points="<?php echo (int) $r['points']; ?>">Reject</button>
											<?php endif; ?>
										</div>
									</td>
								</tr>
							<?php endforeach; ?>
						<?php endif; ?>
					</tbody>
				</table>
			</div>
			<div class="p-4 d-none" id="payEmpty">
				<div class="text-center">
					<div class="mb-2"><i class="fa-regular fa-credit-card fs-2 text-muted"></i></div>
					<div class="fw-semibold">No payouts</div>
					<div class="text-muted small">Nothing matches this filter.</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function () {
	var payload = <?php
		$list = array();
		foreach ((array) $requests as $r) {
			unset($r['user'], $r['transferResponse']);
			$list[] = $r;
		}
		$jsonFlags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
		if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
			$jsonFlags |= JSON_INVALID_UTF8_SUBSTITUTE;
		}
		$encoded = json_encode(array_values($list), $jsonFlags);
		echo ($encoded !== false) ? $encoded : '[]';
	?>;
	var rows = Array.isArray(payload) ? payload : [];
	var stripeReady = <?php echo !empty($stripe_ready) ? 'true' : 'false'; ?>;
	var viewBase = <?php echo json_encode(base_url('admin/payment_view/')); ?>;
	var approveBase = <?php echo json_encode(base_url('admin/payment_approve/')); ?>;
	var rejectBase = <?php echo json_encode(base_url('admin/payment_reject/')); ?>;
	var searchQuery = '';
	var statusFilter = 'all';

	function el(id) { return document.getElementById(id); }
	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 statusBadge(st) {
		var s = String(st || '').toLowerCase();
		if (s === 'pending') return '<span class="badge bg-warning-subtle text-warning border border-warning-subtle">Pending</span>';
		if (s === 'processing') return '<span class="badge bg-info-subtle text-info border border-info-subtle">Processing</span>';
		if (s === 'approved') return '<span class="badge bg-success-subtle text-success border border-success-subtle">Approved</span>';
		if (s === 'rejected') return '<span class="badge bg-danger-subtle text-danger border border-danger-subtle">Rejected</span>';
		return '<span class="badge bg-light text-dark border">' + escapeHtml(st || '—') + '</span>';
	}
	function matches(r) {
		var st = String(r.status || '').toLowerCase();
		if (statusFilter === 'pending') {
			if (st !== 'pending' && st !== 'processing') return false;
		} else if (statusFilter !== 'all' && st !== statusFilter) {
			return false;
		}
		var q = searchQuery.trim().toLowerCase();
		if (!q) return true;
		var hay = ((r.userName || '') + ' ' + (r.email || '') + ' ' + (r.contactDetail || '') + ' ' + (r.userId || '') + ' ' + (r.id || '')).toLowerCase();
		return hay.indexOf(q) !== -1;
	}
	function render() {
		var filtered = rows.filter(matches);
		el('payCountLabel').textContent = 'Showing ' + filtered.length + ' of ' + rows.length;
		el('payTbody').innerHTML = filtered.map(function (r) {
			var name = r.userName || r.email || r.userId || '—';
			var st = String(r.status || '').toLowerCase();
			var canAct = st === 'pending' || st === 'processing';
			var actions = '<a class="btn btn-sm btn-light border" href="' + viewBase + encodeURIComponent(r.id) + '">View</a>';
			if (canAct) {
				actions +=
					'<button type="button" class="btn btn-sm btn-primary" data-action="approve" data-id="' + escapeHtml(r.id) + '" data-name="' + escapeHtml(name) + '" data-points="' + Number(r.points || 0) + '" data-amount="' + escapeHtml(r.amountUsd || '0.00') + '" ' + (stripeReady ? '' : 'disabled') + '>Transfer</button>' +
					'<button type="button" class="btn btn-sm btn-outline-danger" data-action="reject" data-id="' + escapeHtml(r.id) + '" data-name="' + escapeHtml(name) + '" data-points="' + Number(r.points || 0) + '">Reject</button>';
			}
			return '' +
				'<tr>' +
					'<td class="fw-semibold">' +
						'<div>' + escapeHtml(name) + '</div>' +
						'<div class="small text-muted">' + escapeHtml(r.email || r.contactDetail || '') + '</div>' +
					'</td>' +
					'<td>' + Number(r.points || 0) + '</td>' +
					'<td><strong>$' + escapeHtml(r.amountUsd || '0.00') + '</strong><div class="small text-muted">' + Number(r.amount || 0) + ' cents</div></td>' +
					'<td class="small text-muted">' + escapeHtml(r.requestDateLabel || '—') + '</td>' +
					'<td>' + statusBadge(r.status) + '</td>' +
					'<td class="text-end"><div class="btn-group">' + actions + '</div></td>' +
				'</tr>';
		}).join('');
		var empty = el('payEmpty');
		if (filtered.length === 0) empty.classList.remove('d-none');
		else empty.classList.add('d-none');
	}

	function postAction(url, extra) {
		var body = extra || '';
		return fetch(url, {
			method: 'POST',
			headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
			body: body
		}).then(function (res) { return res.json().then(function (json) { return { res: res, json: json }; }); })
		.then(function (out) {
			if (!out.json || !out.json.ok) throw new Error((out.json && out.json.error) ? out.json.error : 'Request failed');
			return out.json;
		});
	}

	function runPayoutAction(action, id, meta) {
		var name = (meta && meta.name) || 'this user';
		var points = (meta && meta.points) || '0';
		var amount = (meta && meta.amount) || '0.00';
		var isApprove = action === 'approve';
		var confirmOpts = isApprove ? {
			icon: 'question',
			title: 'Transfer this payout?',
			html: 'Send <strong>$' + escapeHtml(amount) + '</strong> (' + escapeHtml(String(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(String(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(confirmOpts).then(function (res) {
			if (!res.isConfirmed) return;
			showProcessing(isApprove ? 'Transferring payout…' : 'Rejecting payout…');
			var extra = '';
			if (!isApprove && res.value) {
				extra = 'reason=' + encodeURIComponent(String(res.value));
			}
			var url = (isApprove ? approveBase : rejectBase) + encodeURIComponent(id);
			postAction(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(); });
			});
		});
	}

	el('paySearch').addEventListener('input', function () {
		searchQuery = el('paySearch').value || '';
		render();
	});
	el('payStatus').addEventListener('change', function () {
		statusFilter = el('payStatus').value || 'all';
		render();
	});
	el('sleeperPayments').addEventListener('click', function (e) {
		var btn = e.target.closest('button[data-action]');
		if (!btn) return;
		var id = btn.getAttribute('data-id');
		var action = btn.getAttribute('data-action');
		if (!id) return;
		if (action !== 'approve' && action !== 'reject') return;
		runPayoutAction(action, id, {
			name: btn.getAttribute('data-name') || '',
			points: btn.getAttribute('data-points') || '0',
			amount: btn.getAttribute('data-amount') || '0.00'
		});
	});

	render();
})();
</script>
