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

<style>
	.aoust-avatar {
		width: 34px;
		height: 34px;
		border-radius: 12px;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		font-weight: 700;
		color: #0f5132;
		background: rgba(25, 135, 84, 0.14);
		border: 1px solid rgba(25, 135, 84, 0.25);
	}
	.aoust-muted { color: rgba(33, 37, 41, 0.7); }
	.aoust-table-actions .btn { padding-inline: 0.75rem; }
</style>

<div class="care-admin" id="aoustPickup">
	<div class="ca-hero">
		<div class="ca-hero-inner row align-items-center g-3">
			<div class="col-lg-8">
				<p class="ca-kicker">AOUST portal</p>
				<h1 class="ca-title"><?php echo isset($page_title) ? htmlspecialchars($page_title) : 'AOUST — Pickup Requests'; ?></h1>
				<p class="ca-sub mb-0">Demo UI: approve opens driver modal + SweetAlert processing; reject confirms with SweetAlert; <strong>Details</strong> for full row.</p>
				<p class="ca-sub mb-0 aoust-muted small">Live data: use <a href="<?php echo base_url('aoust_pickup'); ?>">Pickup (Firestore)</a>.</p>
			</div>
			<div class="col-lg-4">
				<div class="ca-nav justify-content-lg-end">
					<a class="btn btn-light" href="<?php echo base_url('admin/aoust'); ?>">Dashboard</a>
					<a class="btn btn-light" href="<?php echo base_url('aoust_stay'); ?>">Stay</a>
					<a class="btn btn-primary" href="<?php echo base_url('aoust_pickup'); ?>">Pickup (live)</a>
				</div>
			</div>
		</div>
	</div>

	<div class="ca-card mb-4">
		<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-car-side me-2 text-success"></i>Pickup Requests (demo)</h5>
				<p class="mb-0">Approve or reject pending pickup requests.</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" id="pickupCountLabel">Showing 0</span>
				<select class="form-select" id="pickupStatusFilter" style="width: 190px;">
					<option value="all">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>Location</th>
							<th>Date</th>
							<th>Status</th>
							<th class="text-end">Actions</th>
						</tr>
					</thead>
					<tbody id="pickupTbody"></tbody>
				</table>
			</div>
		</div>
		<div class="p-4 d-none" id="pickupEmpty">
			<div class="text-center">
				<div class="mb-2"><i class="fa-regular fa-face-frown fs-2 text-muted"></i></div>
				<div class="fw-semibold">No requests found</div>
				<div class="aoust-muted small">Try changing the status filter.</div>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="modalDemoApprove" tabindex="-1" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title">Approve pickup</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				<input type="hidden" id="demo_approve_pickup_id" value="">
				<label class="form-label">Select driver</label>
				<select class="form-select" id="demo_approve_driver_id"></select>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cancel</button>
				<button type="button" class="btn btn-success" id="demoBtnApproveSubmit">Submit</button>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="modalDemoDetails" tabindex="-1" aria-hidden="true">
	<div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title">Pickup details</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				<dl class="row mb-0 small" id="demoDetailsBody"></dl>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-light border" data-bs-dismiss="modal">Close</button>
			</div>
		</div>
	</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function () {
	var demoDrivers = [
		{ id: 'drv1', name: 'Ali Raza', phone: '+92 300 1112233' },
		{ id: 'drv2', name: 'Sara Malik', phone: '+92 321 4445566' }
	];
	var pickupRequests = [
		{
			id: 'p1',
			userName: 'Aisha Khan',
			location: 'Lahore Airport',
			date: '2026-04-12',
			status: 'Pending',
			flightNumber: 'PK301',
			notes: 'Wheelchair assistance',
			uid: 'demo-uid-1',
			userId: 'demo-user-1'
		},
		{
			id: 'p2',
			userName: 'Bilal Ahmed',
			location: 'Islamabad Airport',
			date: '2026-04-15',
			status: 'Approved',
			driverName: 'Ali Raza',
			driverNumber: '+92 300 1112233',
			flightNumber: 'EK612',
			notes: '',
			uid: 'demo-uid-2',
			userId: 'demo-user-2'
		},
		{
			id: 'p3',
			userName: 'Chloe Martin',
			location: 'Manchester Airport',
			date: '2026-04-18',
			status: 'Rejected',
			flightNumber: 'BA139',
			notes: 'Cancelled by user',
			uid: 'demo-uid-3',
			userId: 'demo-user-3'
		}
	];
	var statusFilter = 'all';

	function el(id) { return document.getElementById(id); }
	function escapeHtml(str) {
		return String(str)
			.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
			.replaceAll('"', '&quot;').replaceAll("'", '&#039;');
	}
	function badgeForStatus(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 === '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">—</span>';
	}

	function showProcessing(title) {
		return Swal.fire({
			title: title || 'Processing…',
			allowOutsideClick: false,
			allowEscapeKey: false,
			didOpen: function () { Swal.showLoading(); }
		});
	}

	function fillDriverSelect() {
		var sel = el('demo_approve_driver_id');
		sel.innerHTML = '<option value="">— Choose driver —</option>' +
			demoDrivers.map(function (d) {
				return '<option value="' + escapeHtml(d.id) + '">' + escapeHtml(d.name + ' · ' + d.phone) + '</option>';
			}).join('');
	}

	function openApproveModal(id) {
		el('demo_approve_pickup_id').value = id;
		el('demo_approve_driver_id').value = '';
		fillDriverSelect();
		bootstrap.Modal.getOrCreateInstance(el('modalDemoApprove')).show();
	}

	function submitDemoApprove() {
		var pid = el('demo_approve_pickup_id').value;
		var did = el('demo_approve_driver_id').value;
		if (!did) {
			Swal.fire({ icon: 'warning', title: 'Select a driver' });
			return;
		}
		var drv = demoDrivers.find(function (x) { return x.id === did; });
		var inst = bootstrap.Modal.getInstance(el('modalDemoApprove'));
		if (inst) inst.hide();

		showProcessing('Approving pickup…');
		setTimeout(function () {
			Swal.close();
			var p = pickupRequests.find(function (x) { return x.id === pid; });
			if (p && p.status === 'Pending') {
				p.status = 'Approved';
				p.driverName = drv ? drv.name : '';
				p.driverNumber = drv ? drv.phone : '';
				p.driverId = did;
			}
			render();
			Swal.fire({ icon: 'success', title: 'Approved', timer: 1600, showConfirmButton: false });
		}, 600);
	}

	function confirmReject(id) {
		Swal.fire({
			icon: 'warning',
			title: 'Reject this pickup?',
			showCancelButton: true,
			confirmButtonText: 'Yes, reject',
			cancelButtonText: 'Cancel',
			confirmButtonColor: '#dc3545'
		}).then(function (res) {
			if (!res.isConfirmed) return;
			showProcessing('Rejecting…');
			setTimeout(function () {
				Swal.close();
				var p = pickupRequests.find(function (x) { return x.id === id; });
				if (p && p.status === 'Pending') {
					p.status = 'Rejected';
					p.driverName = '';
					p.driverNumber = '';
					p.driverId = '';
				}
				render();
				Swal.fire({ icon: 'success', title: 'Rejected', timer: 1600, showConfirmButton: false });
			}, 600);
		});
	}

	function rowDetail(label, value) {
		var v = value === null || typeof value === 'undefined' || value === '' ? '—' : String(value);
		return '<dt class="col-sm-4 text-muted">' + escapeHtml(label) + '</dt><dd class="col-sm-8">' + escapeHtml(v) + '</dd>';
	}

	function openDetails(p) {
		var html = '';
		html += rowDetail('ID', p.id);
		html += rowDetail('User', p.userName);
		html += rowDetail('UID', p.uid);
		html += rowDetail('User ID', p.userId);
		html += rowDetail('Location', p.location);
		html += rowDetail('Date', p.date);
		html += rowDetail('Flight', p.flightNumber || '—');
		html += rowDetail('Notes', p.notes || '—');
		html += rowDetail('Status', p.status);
		html += rowDetail('Driver ID', p.driverId || '—');
		html += rowDetail('Driver name', p.driverName || '—');
		html += rowDetail('Driver phone', p.driverNumber || '—');
		el('demoDetailsBody').innerHTML = html;
		bootstrap.Modal.getOrCreateInstance(el('modalDemoDetails')).show();
	}

	function render() {
		var filtered = pickupRequests.filter(function (p) {
			if (statusFilter === 'all') return true;
			return p.status === statusFilter;
		});

		var countLabel = el('pickupCountLabel');
		if (countLabel) {
			var extra = statusFilter === 'all' ? '' : ' · filtered';
			countLabel.textContent = 'Showing ' + filtered.length + ' of ' + pickupRequests.length + extra;
		}

		el('pickupTbody').innerHTML = filtered.map(function (p) {
			var isPending = p.status === 'Pending';
			var initials = (p.userName || '?').split(/\s+/).filter(Boolean).slice(0, 2).map(function (x) { return x[0]; }).join('').toUpperCase();
			var actionBtns = '' +
				'<button type="button" class="btn btn-sm btn-light border" data-action="details" data-id="' + escapeHtml(p.id) + '" title="Details"><i class="fa-regular fa-eye"></i></button>';
			if (isPending) {
				actionBtns +=
					'<button type="button" class="btn btn-sm btn-success" data-action="approve" data-id="' + escapeHtml(p.id) + '" title="Approve"><i class="fa-solid fa-check"></i></button>' +
					'<button type="button" class="btn btn-sm btn-outline-danger" data-action="reject" data-id="' + escapeHtml(p.id) + '" title="Reject"><i class="fa-solid fa-xmark"></i></button>';
			}
			return '' +
				'<tr>' +
					'<td class="fw-semibold">' +
						'<div class="d-flex align-items-center gap-2">' +
							'<span class="aoust-avatar" aria-hidden="true">' + escapeHtml(initials) + '</span>' +
							'<span>' + escapeHtml(p.userName) + '</span>' +
						'</div>' +
					'</td>' +
					'<td>' + escapeHtml(p.location) + '</td>' +
					'<td>' + escapeHtml(p.date) + '</td>' +
					'<td>' + badgeForStatus(p.status) + '</td>' +
					'<td class="text-end">' +
						'<div class="btn-group aoust-table-actions" role="group">' + actionBtns + '</div>' +
					'</td>' +
				'</tr>';
		}).join('');

		var empty = el('pickupEmpty');
		if (empty) {
			if (filtered.length === 0) empty.classList.remove('d-none');
			else empty.classList.add('d-none');
		}
	}

	document.getElementById('aoustPickup').addEventListener('click', function (e) {
		var btn = e.target.closest('button[data-action]');
		if (!btn) return;
		var action = btn.getAttribute('data-action');
		if (action === 'approve') return openApproveModal(btn.getAttribute('data-id'));
		if (action === 'reject') return confirmReject(btn.getAttribute('data-id'));
		if (action === 'details') {
			var did = btn.getAttribute('data-id');
			var row = pickupRequests.find(function (x) { return x.id === did; });
			if (row) openDetails(row);
		}
	});

	el('pickupStatusFilter').addEventListener('change', function () {
		statusFilter = el('pickupStatusFilter').value || 'all';
		render();
	});

	el('demoBtnApproveSubmit').addEventListener('click', submitDemoApprove);

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