<link href="<?php echo base_url('assets/css/admin-panel.css'); ?>" rel="stylesheet">

<style>
	.aoust-muted { color: rgba(33, 37, 41, 0.7); }
	.aoust-table-actions .btn { padding-inline: 0.75rem; }
	.btn-ca-success { color: #fff !important; }
	.aoust-driver-thumb {
		width: 36px;
		height: 36px;
		object-fit: cover;
		border-radius: 8px;
		border: 1px solid rgba(0,0,0,0.08);
		vertical-align: middle;
	}
	.aoust-pickup-actions { min-width: 260px; }
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<?php
	$filter = isset($status_filter) ? $status_filter : 'all';
	$drivers = isset($drivers) && is_array($drivers) ? $drivers : array();
	$pickups = isset($pickups) && is_array($pickups) ? $pickups : array();
	$hasDrivers = count($drivers) > 0;

	function aoust_pickup_norm_status($row) {
		$s = isset($row['status']) ? strtolower(trim((string) $row['status'])) : '';
		return $s;
	}
	function aoust_pickup_badge($status) {
		$s = strtolower(trim((string) $status));
		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">' . htmlspecialchars($status !== '' ? $status : '—') . '</span>';
	}
	function aoust_pickup_fmt_ms($ms) {
		if ($ms === null || $ms === '' || !is_numeric($ms)) return '—';
		return date('Y-m-d H:i', (int) round(((float) $ms) / 1000));
	}
	$q = function ($v) {
		return $v === 'all' ? '' : ('?status=' . rawurlencode($v));
	};
?>

<div class="care-admin" id="aoustPickupCrud">
	<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">Firestore <strong>Pickup</strong> · Pending: choose a driver, then approve or reject.</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_driver'); ?>">Drivers</a>
					<a class="btn btn-primary" href="<?php echo base_url('aoust_pickup'); ?>">Pickup</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</h5>
				<p class="mb-0">Approved pickups copy driver name, phone, image, and driver id onto the request.</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">Showing: <?php echo (int) count($pickups); ?></span>
				<div class="btn-group" role="group">
					<a class="btn btn-sm <?php echo $filter === 'all' ? 'btn-primary' : 'btn-light border'; ?>" href="<?php echo base_url('aoust_pickup'); ?>">All</a>
					<a class="btn btn-sm <?php echo $filter === 'pending' ? 'btn-primary' : 'btn-light border'; ?>" href="<?php echo base_url('aoust_pickup' . $q('pending')); ?>">Pending</a>
					<a class="btn btn-sm <?php echo $filter === 'approved' ? 'btn-primary' : 'btn-light border'; ?>" href="<?php echo base_url('aoust_pickup' . $q('approved')); ?>">Approved</a>
					<a class="btn btn-sm <?php echo $filter === 'rejected' ? 'btn-primary' : 'btn-light border'; ?>" href="<?php echo base_url('aoust_pickup' . $q('rejected')); ?>">Rejected</a>
				</div>
			</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>Flight / Airport</th>
							<th>Drop-off</th>
							<th>Pickup time</th>
							<th>Driver</th>
							<th>Status</th>
							<th class="text-end" style="min-width: 200px;">Actions</th>
						</tr>
					</thead>
					<tbody>
					<?php if (!empty($pickups)): ?>
						<?php foreach ($pickups as $p): ?>
							<?php
								$pid = isset($p['id']) ? $p['id'] : '';
								$flight = isset($p['flightNumber']) ? $p['flightNumber'] : '';
								$airport = isset($p['airportName']) ? $p['airportName'] : '';
								$drop = isset($p['dropoffLocation']) ? $p['dropoffLocation'] : '';
								$puTs = isset($p['pickupTimestamp']) ? $p['pickupTimestamp'] : null;
								$st = aoust_pickup_norm_status($p);
								$isPending = ($st === 'pending');
								$dName = isset($p['driverName']) ? $p['driverName'] : '';
								$dPhone = isset($p['driverNumber']) ? $p['driverNumber'] : '';
								$dImg = isset($p['driverImage']) && $p['driverImage'] !== null ? trim((string) $p['driverImage']) : '';
								$dId = isset($p['driverId']) ? $p['driverId'] : '';
								$pickupDetail = array(
									'id' => $pid,
									'uid' => isset($p['uid']) ? (string) $p['uid'] : '',
									'userId' => isset($p['userId']) ? (string) $p['userId'] : '',
									'airportName' => $airport,
									'flightNumber' => $flight,
									'dropoffLocation' => $drop,
									'dropoffLat' => isset($p['dropoffLat']) ? $p['dropoffLat'] : '',
									'dropoffLon' => isset($p['dropoffLon']) ? $p['dropoffLon'] : '',
									'pickupTimestamp' => $puTs,
									'pickupTimeLabel' => aoust_pickup_fmt_ms($puTs),
									'notes' => isset($p['notes']) ? (string) $p['notes'] : '',
									'status' => isset($p['status']) ? (string) $p['status'] : '',
									'createdAt' => isset($p['createdAt']) ? $p['createdAt'] : '',
									'createdAtLabel' => aoust_pickup_fmt_ms(isset($p['createdAt']) ? $p['createdAt'] : null),
									'updatedAt' => isset($p['updatedAt']) ? $p['updatedAt'] : '',
									'updatedAtLabel' => aoust_pickup_fmt_ms(isset($p['updatedAt']) ? $p['updatedAt'] : null),
									'driverId' => (string) $dId,
									'driverName' => (string) $dName,
									'driverNumber' => (string) $dPhone,
									'driverImage' => (string) $dImg,
								);
								$pickupDetailJson = htmlspecialchars(json_encode($pickupDetail, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
							?>
							<tr>
								<td class="small">
									<div class="fw-semibold"><?php echo htmlspecialchars($flight !== '' ? $flight : '—'); ?></div>
									<div class="aoust-muted"><?php echo htmlspecialchars($airport); ?></div>
								</td>
								<td class="small text-muted" style="max-width: 220px;">
									<div class="text-truncate" title="<?php echo htmlspecialchars($drop); ?>"><?php echo htmlspecialchars($drop); ?></div>
								</td>
								<td class="small"><?php echo htmlspecialchars(aoust_pickup_fmt_ms($puTs)); ?></td>
								<td class="small">
									<?php if ($dName !== '' || $dPhone !== '' || $dImg !== ''): ?>
										<div class="d-flex align-items-center gap-2">
											<?php if ($dImg !== ''): ?>
												<img class="aoust-driver-thumb" src="<?php echo htmlspecialchars($dImg); ?>" alt="">
											<?php endif; ?>
											<div>
												<div class="fw-semibold"><?php echo htmlspecialchars($dName); ?></div>
												<div class="aoust-muted"><?php echo htmlspecialchars($dPhone); ?></div>
												<?php if ($dId !== ''): ?>
													<div class="aoust-muted" style="font-size: 0.75rem;">ID: <?php echo htmlspecialchars($dId); ?></div>
												<?php endif; ?>
											</div>
										</div>
									<?php else: ?>
										<span class="aoust-muted">—</span>
									<?php endif; ?>
								</td>
								<td><?php echo aoust_pickup_badge(isset($p['status']) ? $p['status'] : ''); ?></td>
								<td class="text-end aoust-pickup-actions">
									<div class="btn-group aoust-table-actions flex-wrap justify-content-end" role="group">
										<button type="button" class="btn btn-sm btn-light border" data-action="pickup-details" data-detail="<?php echo $pickupDetailJson; ?>" title="Details">
											<i class="fa-regular fa-eye"></i>
										</button>
										<?php if ($isPending): ?>
											<button type="button" class="btn btn-sm btn-success" data-action="pickup-open-approve" data-pickup-id="<?php echo htmlspecialchars($pid); ?>" <?php echo $hasDrivers ? '' : 'disabled title="Add drivers first"'; ?>>
												Approve
											</button>
											<button type="button" class="btn btn-sm btn-outline-danger" data-action="pickup-reject" data-pickup-id="<?php echo htmlspecialchars($pid); ?>">Reject</button>
										<?php endif; ?>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php else: ?>
						<tr>
							<td colspan="6" class="p-4 text-center">
								<div class="mb-2"><i class="fa-regular fa-face-frown fs-2 text-muted"></i></div>
								<div class="fw-semibold">No pickups in this view</div>
								<div class="aoust-muted small">Try another status filter or create requests from the app.</div>
							</td>
						</tr>
					<?php endif; ?>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</div>

<!-- Approve: assign driver -->
<div class="modal fade" id="modalPickupApprove" 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="approve_modal_pickup_id" value="">
				<label class="form-label">Select driver</label>
				<select class="form-select" id="approve_modal_driver_id" <?php echo $hasDrivers ? '' : 'disabled'; ?>>
					<option value=""><?php echo $hasDrivers ? '— Choose driver —' : 'Add drivers in Pickup Drivers first'; ?></option>
					<?php foreach ($drivers as $dr): ?>
						<?php $did = isset($dr['id']) ? $dr['id'] : ''; $dn = isset($dr['name']) ? $dr['name'] : ''; $dph = isset($dr['phone']) ? $dr['phone'] : ''; ?>
						<option value="<?php echo htmlspecialchars($did); ?>"><?php echo htmlspecialchars($dn . ($dph !== '' ? ' · ' . $dph : '')); ?></option>
					<?php endforeach; ?>
				</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="btnPickupApproveSubmit">Submit</button>
			</div>
		</div>
	</div>
</div>

<!-- Details -->
<div class="modal fade" id="modalPickupDetails" 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="pickupDetailsBody"></dl>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-light border" data-bs-dismiss="modal">Close</button>
			</div>
		</div>
	</div>
</div>

<form id="formPickupApproveHidden" method="post" action="<?php echo base_url('aoust_pickup/approve'); ?>" class="d-none">
	<input type="hidden" name="pickup_id" id="hidden_approve_pickup_id" value="">
	<input type="hidden" name="driver_id" id="hidden_approve_driver_id" value="">
</form>
<form id="formPickupRejectHidden" method="post" action="<?php echo base_url('aoust_pickup/reject'); ?>" class="d-none">
	<input type="hidden" name="pickup_id" id="hidden_reject_pickup_id" value="">
</form>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function () {
	var hasDrivers = <?php echo $hasDrivers ? 'true' : 'false'; ?>;

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

	function openApproveModal(pickupId) {
		if (!hasDrivers) {
			Swal.fire({ icon: 'info', title: 'No drivers', text: 'Add drivers under Pickup Drivers first.' });
			return;
		}
		document.getElementById('approve_modal_pickup_id').value = pickupId;
		document.getElementById('approve_modal_driver_id').value = '';
		var m = document.getElementById('modalPickupApprove');
		bootstrap.Modal.getOrCreateInstance(m).show();
	}

	function submitApprove() {
		var pid = document.getElementById('approve_modal_pickup_id').value.trim();
		var did = document.getElementById('approve_modal_driver_id').value.trim();
		if (!pid || !did) {
			Swal.fire({ icon: 'warning', title: 'Select a driver', text: 'Choose a driver before submitting.' });
			return;
		}
		var apprModal = document.getElementById('modalPickupApprove');
		var apprInst = bootstrap.Modal.getInstance(apprModal);
		if (apprInst) apprInst.hide();
		showProcessing('Approving pickup…');
		document.getElementById('hidden_approve_pickup_id').value = pid;
		document.getElementById('hidden_approve_driver_id').value = did;
		document.getElementById('formPickupApproveHidden').submit();
	}

	function confirmReject(pickupId) {
		Swal.fire({
			icon: 'warning',
			title: 'Reject this pickup?',
			text: 'The request will be marked as rejected.',
			showCancelButton: true,
			confirmButtonText: 'Yes, reject',
			cancelButtonText: 'Cancel',
			confirmButtonColor: '#dc3545'
		}).then(function (res) {
			if (!res.isConfirmed) return;
			showProcessing('Rejecting…');
			document.getElementById('hidden_reject_pickup_id').value = pickupId;
			document.getElementById('formPickupRejectHidden').submit();
		});
	}

	function escapeHtml(str) {
		return String(str)
			.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
			.replaceAll('"', '&quot;').replaceAll("'", '&#039;');
	}

	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(raw) {
		var d;
		try { d = typeof raw === 'string' ? JSON.parse(raw) : raw; } catch (e) { return; }
		var html = '';
		html += rowDetail('Document ID', d.id);
		html += rowDetail('UID', d.uid);
		html += rowDetail('User ID', d.userId);
		html += rowDetail('Airport', d.airportName);
		html += rowDetail('Flight', d.flightNumber);
		html += rowDetail('Drop-off', d.dropoffLocation);
		html += rowDetail('Drop-off lat / lon', (d.dropoffLat !== '' && d.dropoffLon !== '') ? (d.dropoffLat + ', ' + d.dropoffLon) : '');
		html += rowDetail('Pickup time', d.pickupTimeLabel || d.pickupTimestamp);
		html += rowDetail('Notes', d.notes);
		html += rowDetail('Status', d.status);
		html += rowDetail('Created', d.createdAtLabel || d.createdAt);
		html += rowDetail('Updated', d.updatedAtLabel || d.updatedAt);
		html += rowDetail('Driver ID', d.driverId);
		html += rowDetail('Driver name', d.driverName);
		html += rowDetail('Driver phone', d.driverNumber);
		html += rowDetail('Driver image URL', d.driverImage);
		document.getElementById('pickupDetailsBody').innerHTML = html;
		bootstrap.Modal.getOrCreateInstance(document.getElementById('modalPickupDetails')).show();
	}

	document.getElementById('aoustPickupCrud').addEventListener('click', function (e) {
		var btn = e.target.closest('[data-action]');
		if (!btn) return;
		var act = btn.getAttribute('data-action');
		if (act === 'pickup-open-approve') {
			var id = btn.getAttribute('data-pickup-id');
			if (id) openApproveModal(id);
			return;
		}
		if (act === 'pickup-reject') {
			var rid = btn.getAttribute('data-pickup-id');
			if (rid) confirmReject(rid);
			return;
		}
		if (act === 'pickup-details') {
			openDetails(btn.getAttribute('data-detail'));
		}
	});

	var btnApprSubmit = document.getElementById('btnPickupApproveSubmit');
	if (btnApprSubmit) btnApprSubmit.addEventListener('click', submitApprove);
})();
</script>
