<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-stay-thumb {
		width: 36px;
		height: 36px;
		object-fit: cover;
		border-radius: 8px;
		border: 1px solid rgba(0,0,0,0.08);
		vertical-align: middle;
	}
	.aoust-stay-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';
	$accommodators = isset($accommodators) && is_array($accommodators) ? $accommodators : array();
	$stays = isset($stays) && is_array($stays) ? $stays : array();
	$hasAccommodators = count($accommodators) > 0;

	function aoust_stay_is_pending($row) {
		$s = isset($row['status']) ? strtolower(trim((string) $row['status'])) : '';
		return $s === 'pending';
	}
	function aoust_stay_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>';
		if ($s === 'denied') return '<span class="badge bg-secondary-subtle text-secondary border">Denied</span>';
		return '<span class="badge bg-light text-dark border">' . htmlspecialchars($status !== '' ? $status : '—') . '</span>';
	}
	function aoust_stay_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="aoustStayCrud">
	<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 — Stay Requests'; ?></h1>
				<p class="ca-sub mb-0">Firestore <strong>Stay</strong> · Pending: pick an accommodator, approve or reject (same flow as pickup).</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_accommodator'); ?>">Accommodators</a>
					<a class="btn btn-primary" href="<?php echo base_url('aoust_stay'); ?>">Stay</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-bed me-2 text-success"></i>Stay Requests</h5>
				<p class="mb-0">Approve copies accommodator fields onto the stay and sets <strong>lat</strong> / <strong>lon</strong>.</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($stays); ?></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_stay'); ?>">All</a>
					<a class="btn btn-sm <?php echo $filter === 'pending' ? 'btn-primary' : 'btn-light border'; ?>" href="<?php echo base_url('aoust_stay' . $q('pending')); ?>">Pending</a>
					<a class="btn btn-sm <?php echo $filter === 'approved' ? 'btn-primary' : 'btn-light border'; ?>" href="<?php echo base_url('aoust_stay' . $q('approved')); ?>">Approved</a>
					<a class="btn btn-sm <?php echo $filter === 'rejected' ? 'btn-primary' : 'btn-light border'; ?>" href="<?php echo base_url('aoust_stay' . $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>Guest</th>
							<th>Location</th>
							<th>Stay dates</th>
							<th>Accommodator</th>
							<th>Status</th>
							<th class="text-end" style="min-width: 200px;">Actions</th>
						</tr>
					</thead>
					<tbody>
					<?php if (!empty($stays)): ?>
						<?php foreach ($stays as $s): ?>
							<?php
								$sid = isset($s['id']) ? $s['id'] : '';
								$fullName = isset($s['fullName']) ? $s['fullName'] : '';
								$city = isset($s['city']) ? $s['city'] : '';
								$country = isset($s['country']) ? $s['country'] : '';
								$checkIn = isset($s['checkIn']) ? $s['checkIn'] : null;
								$checkOut = isset($s['checkOut']) ? $s['checkOut'] : null;
								$isPending = aoust_stay_is_pending($s);
								$an = isset($s['accommodatorName']) ? $s['accommodatorName'] : '';
								$ap = isset($s['accommodatorNumber']) ? $s['accommodatorNumber'] : '';
								$ai = isset($s['accommodatorImage']) && $s['accommodatorImage'] !== null ? trim((string) $s['accommodatorImage']) : '';
								$aid = isset($s['accommodatorId']) ? $s['accommodatorId'] : '';
								$detail = array(
									'id' => $sid,
									'uid' => isset($s['uid']) ? (string) $s['uid'] : '',
									'userId' => isset($s['userId']) ? (string) $s['userId'] : '',
									'fullName' => $fullName,
									'age' => isset($s['age']) ? (string) $s['age'] : '',
									'nationality' => isset($s['nationality']) ? (string) $s['nationality'] : '',
									'phone' => isset($s['phone']) ? (string) $s['phone'] : '',
									'city' => $city,
									'country' => $country,
									'preferredLocation' => isset($s['preferredLocation']) ? (string) $s['preferredLocation'] : '',
									'purpose' => isset($s['purpose']) ? (string) $s['purpose'] : '',
									'checkIn' => $checkIn,
									'checkOut' => $checkOut,
									'checkInLabel' => aoust_stay_fmt_ms($checkIn),
									'checkOutLabel' => aoust_stay_fmt_ms($checkOut),
									'status' => isset($s['status']) ? (string) $s['status'] : '',
									'lat' => isset($s['lat']) ? $s['lat'] : '',
									'lon' => isset($s['lon']) ? $s['lon'] : '',
									'range' => isset($s['range']) ? $s['range'] : '',
									'accommodatorId' => (string) $aid,
									'accommodatorName' => (string) $an,
									'accommodatorNumber' => (string) $ap,
									'accommodatorAddress' => isset($s['accommodatorAddress']) ? (string) $s['accommodatorAddress'] : '',
									'accommodatorImage' => (string) $ai,
									'createdAt' => isset($s['createdAt']) ? $s['createdAt'] : '',
									'createdAtLabel' => aoust_stay_fmt_ms(isset($s['createdAt']) ? $s['createdAt'] : null),
									'updatedAt' => isset($s['updatedAt']) ? $s['updatedAt'] : '',
									'updatedAtLabel' => aoust_stay_fmt_ms(isset($s['updatedAt']) ? $s['updatedAt'] : null),
								);
								$detailJson = htmlspecialchars(json_encode($detail, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
							?>
							<tr>
								<td class="small">
									<div class="fw-semibold"><?php echo htmlspecialchars($fullName !== '' ? $fullName : '—'); ?></div>
									<div class="aoust-muted"><?php echo htmlspecialchars(isset($s['phone']) ? $s['phone'] : ''); ?></div>
								</td>
								<td class="small text-muted">
									<div><?php echo htmlspecialchars(trim($city . ($city && $country ? ', ' : '') . $country)); ?></div>
									<div class="text-truncate" style="max-width: 180px;" title="<?php echo htmlspecialchars(isset($s['preferredLocation']) ? $s['preferredLocation'] : ''); ?>"><?php echo htmlspecialchars(isset($s['preferredLocation']) ? $s['preferredLocation'] : ''); ?></div>
								</td>
								<td class="small">
									<div><?php echo htmlspecialchars(aoust_stay_fmt_ms($checkIn)); ?></div>
									<div class="aoust-muted">→ <?php echo htmlspecialchars(aoust_stay_fmt_ms($checkOut)); ?></div>
								</td>
								<td class="small">
									<?php if ($an !== '' || $ap !== '' || $ai !== ''): ?>
										<div class="d-flex align-items-center gap-2">
											<?php if ($ai !== ''): ?>
												<img class="aoust-stay-thumb" src="<?php echo htmlspecialchars($ai); ?>" alt="">
											<?php endif; ?>
											<div>
												<div class="fw-semibold"><?php echo htmlspecialchars($an); ?></div>
												<div class="aoust-muted"><?php echo htmlspecialchars($ap); ?></div>
												<?php if ($aid !== ''): ?>
													<div class="aoust-muted" style="font-size: 0.75rem;">ID: <?php echo htmlspecialchars($aid); ?></div>
												<?php endif; ?>
											</div>
										</div>
									<?php else: ?>
										<span class="aoust-muted">—</span>
									<?php endif; ?>
								</td>
								<td><?php echo aoust_stay_badge(isset($s['status']) ? $s['status'] : ''); ?></td>
								<td class="text-end aoust-stay-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="stay-details" data-detail="<?php echo $detailJson; ?>" title="Details">
											<i class="fa-regular fa-eye"></i>
										</button>
										<?php if ($isPending): ?>
											<button type="button" class="btn btn-sm btn-success" data-action="stay-open-approve" data-stay-id="<?php echo htmlspecialchars($sid); ?>" <?php echo $hasAccommodators ? '' : 'disabled title="Add accommodators first"'; ?>>
												Approve
											</button>
											<button type="button" class="btn btn-sm btn-outline-danger" data-action="stay-reject" data-stay-id="<?php echo htmlspecialchars($sid); ?>">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 stays in this view</div>
								<div class="aoust-muted small">Change the filter or create requests from the app.</div>
							</td>
						</tr>
					<?php endif; ?>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="modalStayApprove" 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 stay</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				<input type="hidden" id="stay_approve_modal_stay_id" value="">
				<label class="form-label">Select accommodator</label>
				<select class="form-select" id="stay_approve_modal_acc_id" <?php echo $hasAccommodators ? '' : 'disabled'; ?>>
					<option value=""><?php echo $hasAccommodators ? '— Choose —' : 'Add accommodators first'; ?></option>
					<?php foreach ($accommodators as $ac): ?>
						<?php
							$acid = isset($ac['id']) ? $ac['id'] : '';
							$acn = isset($ac['name']) ? $ac['name'] : '';
							$acp = isset($ac['phone']) ? $ac['phone'] : '';
							$acaddr = isset($ac['address']) ? $ac['address'] : '';
							$label = $acn . ($acp !== '' ? ' · ' . $acp : '');
						?>
						<option value="<?php echo htmlspecialchars($acid); ?>" title="<?php echo htmlspecialchars($acaddr); ?>"><?php echo htmlspecialchars($label); ?></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="btnStayApproveSubmit">Submit</button>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="modalStayDetails" 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">Stay 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="stayDetailsBody"></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="formStayApproveHidden" method="post" action="<?php echo base_url('aoust_stay/approve'); ?>" class="d-none">
	<input type="hidden" name="stay_id" id="hidden_stay_approve_id" value="">
	<input type="hidden" name="accommodator_id" id="hidden_stay_acc_id" value="">
</form>
<form id="formStayRejectHidden" method="post" action="<?php echo base_url('aoust_stay/reject'); ?>" class="d-none">
	<input type="hidden" name="stay_id" id="hidden_stay_reject_id" value="">
</form>

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

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

	function openStayApproveModal(stayId) {
		if (!hasAcc) {
			Swal.fire({ icon: 'info', title: 'No accommodators', text: 'Add records under Accommodators first.' });
			return;
		}
		document.getElementById('stay_approve_modal_stay_id').value = stayId;
		document.getElementById('stay_approve_modal_acc_id').value = '';
		bootstrap.Modal.getOrCreateInstance(document.getElementById('modalStayApprove')).show();
	}

	function submitStayApprove() {
		var sid = document.getElementById('stay_approve_modal_stay_id').value.trim();
		var acc = document.getElementById('stay_approve_modal_acc_id').value.trim();
		if (!sid || !acc) {
			Swal.fire({ icon: 'warning', title: 'Select an accommodator' });
			return;
		}
		var m = document.getElementById('modalStayApprove');
		var mi = bootstrap.Modal.getInstance(m);
		if (mi) mi.hide();
		showProcessing('Approving stay…');
		document.getElementById('hidden_stay_approve_id').value = sid;
		document.getElementById('hidden_stay_acc_id').value = acc;
		document.getElementById('formStayApproveHidden').submit();
	}

	function confirmStayReject(stayId) {
		Swal.fire({
			icon: 'warning',
			title: 'Reject this stay request?',
			text: 'Status will be set to rejected.',
			showCancelButton: true,
			confirmButtonText: 'Yes, reject',
			cancelButtonText: 'Cancel',
			confirmButtonColor: '#dc3545'
		}).then(function (res) {
			if (!res.isConfirmed) return;
			showProcessing('Rejecting…');
			document.getElementById('hidden_stay_reject_id').value = stayId;
			document.getElementById('formStayRejectHidden').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 openStayDetails(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('Full name', d.fullName);
		html += rowDetail('Age', d.age);
		html += rowDetail('Nationality', d.nationality);
		html += rowDetail('Phone', d.phone);
		html += rowDetail('City', d.city);
		html += rowDetail('Country', d.country);
		html += rowDetail('Preferred location', d.preferredLocation);
		html += rowDetail('Purpose', d.purpose);
		html += rowDetail('Check-in', d.checkInLabel || d.checkIn);
		html += rowDetail('Check-out', d.checkOutLabel || d.checkOut);
		html += rowDetail('Status', d.status);
		html += rowDetail('Lat', d.lat);
		html += rowDetail('Lon', d.lon);
		html += rowDetail('Range', d.range);
		html += rowDetail('Accommodator ID', d.accommodatorId);
		html += rowDetail('Accommodator name', d.accommodatorName);
		html += rowDetail('Accommodator phone', d.accommodatorNumber);
		html += rowDetail('Accommodator address', d.accommodatorAddress);
		html += rowDetail('Accommodator image URL', d.accommodatorImage);
		html += rowDetail('Created', d.createdAtLabel || d.createdAt);
		html += rowDetail('Updated', d.updatedAtLabel || d.updatedAt);
		document.getElementById('stayDetailsBody').innerHTML = html;
		bootstrap.Modal.getOrCreateInstance(document.getElementById('modalStayDetails')).show();
	}

	document.getElementById('aoustStayCrud').addEventListener('click', function (e) {
		var btn = e.target.closest('[data-action]');
		if (!btn) return;
		var act = btn.getAttribute('data-action');
		if (act === 'stay-open-approve') {
			var id = btn.getAttribute('data-stay-id');
			if (id) openStayApproveModal(id);
			return;
		}
		if (act === 'stay-reject') {
			var rid = btn.getAttribute('data-stay-id');
			if (rid) confirmStayReject(rid);
			return;
		}
		if (act === 'stay-details') openStayDetails(btn.getAttribute('data-detail'));
	});

	document.getElementById('btnStayApproveSubmit').addEventListener('click', submitStayApprove);
})();
</script>
