<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Guests';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount): string
    {
        return number_format((float)$amount, 2);
    }
}

if (!function_exists('guest_column_exists')) {
    function guest_column_exists(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];
        $key = $table . '.' . $column;

        if (array_key_exists($key, $cache)) {
            return $cache[$key];
        }

        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = :table_name
                  AND COLUMN_NAME = :column_name
            ");
            $stmt->execute([
                ':table_name'  => $table,
                ':column_name' => $column,
            ]);
            $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$key] = false;
        }

        return $cache[$key];
    }
}

if (!function_exists('guest_table_exists')) {
    function guest_table_exists(PDO $pdo, string $table): bool
    {
        static $cache = [];

        if (array_key_exists($table, $cache)) {
            return $cache[$table];
        }

        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = :table_name
            ");
            $stmt->execute([':table_name' => $table]);
            $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            $cache[$table] = false;
        }

        return $cache[$table];
    }
}

if (!function_exists('guest_initials')) {
    function guest_initials(string $name): string
    {
        $name = trim($name);
        if ($name === '') {
            return 'G';
        }

        $parts = preg_split('/\s+/', $name);
        $initials = '';

        foreach ($parts as $part) {
            if ($part !== '') {
                $initials .= strtoupper(substr($part, 0, 1));
            }
            if (strlen($initials) >= 2) {
                break;
            }
        }

        return $initials !== '' ? $initials : 'G';
    }
}

$errors = [];
$q = trim((string)($_GET['q'] ?? ''));
$propertyId = (int)($_GET['property_id'] ?? 0);
$statusFilter = trim((string)($_GET['status'] ?? ''));
$from = trim((string)($_GET['from'] ?? ''));
$to = trim((string)($_GET['to'] ?? ''));

$properties = [];
try {
    $stmt = $pdo->query("
        SELECT id, name, code
        FROM properties
        WHERE is_active = 1
        ORDER BY name ASC
    ");
    $properties = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
} catch (Throwable $e) {
    $properties = [];
}

$hasGuestsTable = guest_table_exists($pdo, 'guests');
$hasGuestId = guest_column_exists($pdo, 'order_rooming_guests', 'guest_id');

$optionalGuestColumns = [
    'id_type',
    'id_number',
    'nationality',
    'gender',
    'date_of_birth',
    'phone',
    'email',
    'address',
    'signature_data',
    'registration_notes',
    'checked_in_at',
    'checked_out_at',
    'is_primary',
];

$availableOrgColumns = [];
foreach ($optionalGuestColumns as $column) {
    $availableOrgColumns[$column] = guest_column_exists($pdo, 'order_rooming_guests', $column);
}

$selects = [
    'org.id AS stay_guest_id',
    'org.order_id',
    'org.rooming_id',
    'org.first_name',
    'org.last_name',
];

foreach ($optionalGuestColumns as $column) {
    $selects[] = $availableOrgColumns[$column] ? ('org.' . $column) : ('NULL AS ' . $column);
}

$selects[] = $hasGuestId ? 'org.guest_id' : 'NULL AS guest_id';

$guestJoin = '';
if ($hasGuestsTable && $hasGuestId) {
    $guestJoin = " LEFT JOIN guests gprof ON gprof.id = org.guest_id ";
    $selects[] = "gprof.firstname AS profile_firstname";
    $selects[] = "gprof.lastname AS profile_lastname";
    $selects[] = guest_column_exists($pdo, 'guests', 'email') ? "gprof.email AS profile_email" : "NULL AS profile_email";
    $selects[] = guest_column_exists($pdo, 'guests', 'phone') ? "gprof.phone AS profile_phone" : "NULL AS profile_phone";
} else {
    $selects[] = "NULL AS profile_firstname";
    $selects[] = "NULL AS profile_lastname";
    $selects[] = "NULL AS profile_email";
    $selects[] = "NULL AS profile_phone";
}

$selects[] = "o.order_no";
$selects[] = "o.check_in";
$selects[] = "o.check_out";
$selects[] = "o.status AS booking_status";
$selects[] = "p.id AS property_id";
$selects[] = "p.name AS property_name";
$selects[] = "p.code AS property_code";
$selects[] = "rm.room_no AS actual_room_no";
$selects[] = "rt.title AS room_type_title";
$selects[] = "COALESCE(folio_totals.total_charges, 0) AS booking_charges";
$selects[] = "COALESCE(folio_totals.total_payments, 0) AS booking_payments";
$selects[] = "COALESCE(folio_totals.balance, 0) AS booking_balance";

$sql = "
    SELECT
        " . implode(",\n        ", $selects) . "
    FROM order_rooming_guests org
    INNER JOIN orders o ON o.id = org.order_id
    LEFT JOIN properties p ON p.id = o.property_id
    LEFT JOIN order_rooming rmg ON rmg.id = org.rooming_id
    LEFT JOIN rooms rm ON rm.id = rmg.room_id
    LEFT JOIN room_types rt ON rt.id = rmg.room_type_id
    {$guestJoin}
    LEFT JOIN (
        SELECT
            order_id,
            COALESCE(SUM(total_charges), 0) AS total_charges,
            COALESCE(SUM(total_payments), 0) AS total_payments,
            COALESCE(SUM(balance), 0) AS balance
        FROM folios
        GROUP BY order_id
    ) folio_totals ON folio_totals.order_id = o.id
    WHERE 1=1
";

$params = [];

if ($propertyId > 0) {
    $sql .= " AND o.property_id = :property_id ";
    $params[':property_id'] = $propertyId;
}

if ($statusFilter !== '') {
    if ($statusFilter === 'in_house') {
        /*
           Do not compare DATETIME fields to an empty string.
           MySQL strict mode raises: Incorrect DATETIME value: ''
        */
        $sql .= "
            AND org.checked_in_at IS NOT NULL
            AND org.checked_out_at IS NULL
        ";
    } elseif ($statusFilter === 'checked_out') {
        $sql .= " AND org.checked_out_at IS NOT NULL ";
    } elseif ($statusFilter === 'future') {
        $sql .= " AND DATE(o.check_in) > CURDATE() ";
    }
}

if ($from !== '') {
    $sql .= " AND DATE(o.check_in) >= :from_date ";
    $params[':from_date'] = $from;
}

if ($to !== '') {
    $sql .= " AND DATE(o.check_in) <= :to_date ";
    $params[':to_date'] = $to;
}

if ($q !== '') {
    $searchValue = '%' . $q . '%';

    $searchParts = [
        "org.first_name LIKE :q_first_name",
        "org.last_name LIKE :q_last_name",
        "o.order_no LIKE :q_order_no",
        "COALESCE(p.name,'') LIKE :q_property",
        "COALESCE(rm.room_no,'') LIKE :q_room_no",
        "COALESCE(rt.title,'') LIKE :q_room_type",
    ];

    $params[':q_first_name'] = $searchValue;
    $params[':q_last_name']  = $searchValue;
    $params[':q_order_no']   = $searchValue;
    $params[':q_property']   = $searchValue;
    $params[':q_room_no']    = $searchValue;
    $params[':q_room_type']  = $searchValue;

    if ($availableOrgColumns['id_number']) {
        $searchParts[] = "COALESCE(org.id_number,'') LIKE :q_id_number";
        $params[':q_id_number'] = $searchValue;
    }

    if ($availableOrgColumns['email']) {
        $searchParts[] = "COALESCE(org.email,'') LIKE :q_email";
        $params[':q_email'] = $searchValue;
    }

    if ($availableOrgColumns['phone']) {
        $searchParts[] = "COALESCE(org.phone,'') LIKE :q_phone";
        $params[':q_phone'] = $searchValue;
    }

    if ($availableOrgColumns['nationality']) {
        $searchParts[] = "COALESCE(org.nationality,'') LIKE :q_nationality";
        $params[':q_nationality'] = $searchValue;
    }

    $sql .= " AND (" . implode(" OR ", $searchParts) . ") ";
}

$sql .= "
    ORDER BY
        COALESCE(org.checked_in_at, o.check_in) DESC,
        org.id DESC
    LIMIT 500
";

$rows = [];
try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
    $rows = [];
}

$guestCards = [];
$totalStays = 0;
$inHouseCount = 0;
$checkedOutCount = 0;

foreach ($rows as $row) {
    $firstName = trim((string)($row['profile_firstname'] ?: ($row['first_name'] ?? '')));
    $lastName  = trim((string)($row['profile_lastname'] ?: ($row['last_name'] ?? '')));
    $name = trim($firstName . ' ' . $lastName);
    if ($name === '') {
        $name = 'Guest';
    }

    $email = trim((string)($row['profile_email'] ?: ($row['email'] ?? '')));
    $phone = trim((string)($row['profile_phone'] ?: ($row['phone'] ?? '')));
    $idNumber = trim((string)($row['id_number'] ?? ''));

    if (!empty($row['guest_id'])) {
        $identityKey = 'gid:' . (int)$row['guest_id'];
    } elseif ($idNumber !== '') {
        $identityKey = 'id:' . strtolower($idNumber);
    } elseif ($email !== '') {
        $identityKey = 'email:' . strtolower($email);
    } elseif ($phone !== '') {
        $identityKey = 'phone:' . strtolower($phone);
    } else {
        $identityKey = 'name:' . strtolower($name);
    }

    if (!isset($guestCards[$identityKey])) {
        $guestCards[$identityKey] = [
            'identity_key' => $identityKey,
            'guest_id' => (int)($row['guest_id'] ?? 0),
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'id_number' => $idNumber,
            'id_type' => trim((string)($row['id_type'] ?? '')),
            'nationality' => trim((string)($row['nationality'] ?? '')),
            'gender' => trim((string)($row['gender'] ?? '')),
            'stays' => [],
            'total_stays' => 0,
            'last_checkin' => '',
            'last_checkout' => '',
            'last_booking_id' => 0,
            'last_order_no' => '',
            'total_balance' => 0.0,
            'in_house' => false,
        ];
    }

    $checkedInAt = trim((string)($row['checked_in_at'] ?? ''));
    $checkedOutAt = trim((string)($row['checked_out_at'] ?? ''));

    $isInHouse = ($checkedInAt !== '' && $checkedOutAt === '');

    $guestCards[$identityKey]['stays'][] = $row;
    $guestCards[$identityKey]['total_stays']++;
    $guestCards[$identityKey]['total_balance'] += (float)($row['booking_balance'] ?? 0);

    if ($isInHouse) {
        $guestCards[$identityKey]['in_house'] = true;
    }

    $sortDate = $checkedInAt !== '' ? $checkedInAt : (string)($row['check_in'] ?? '');
    if ($guestCards[$identityKey]['last_checkin'] === '' || strtotime($sortDate) > strtotime($guestCards[$identityKey]['last_checkin'])) {
        $guestCards[$identityKey]['last_checkin'] = $sortDate;
        $guestCards[$identityKey]['last_checkout'] = $checkedOutAt !== '' ? $checkedOutAt : (string)($row['check_out'] ?? '');
        $guestCards[$identityKey]['last_booking_id'] = (int)($row['order_id'] ?? 0);
        $guestCards[$identityKey]['last_order_no'] = (string)($row['order_no'] ?? '');
    }

    $totalStays++;
    if ($isInHouse) {
        $inHouseCount++;
    } elseif ($checkedOutAt !== '') {
        $checkedOutCount++;
    }
}

$guestCards = array_values($guestCards);
usort($guestCards, function ($a, $b) {
    return strtotime($b['last_checkin'] ?: '1970-01-01') <=> strtotime($a['last_checkin'] ?: '1970-01-01');
});

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-people"></i> Guest CRM</div>
            <div class="hero-title mt-2">Guests</div>
            <div class="hero-subtitle mt-2">
                Guest profiles built from actual check-in occupants, stay history, folios, and room assignments.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="/rooms/modules/reservations/reservation_list.php" class="btn btn-outline-light">
                <i class="bi bi-arrow-left me-2"></i>Reservations
            </a>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!$hasGuestId): ?>
    <div class="alert alert-warning">
        <strong>Guest profile link not yet enabled.</strong>
        This page is grouping guests from check-in occupant details. Later you can add <code>guest_id</code> to <code>order_rooming_guests</code> for permanent CRM linking.
    </div>
<?php endif; ?>

<div class="row g-3 mb-4">
    <div class="col-sm-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-person-lines-fill"></i></div>
            <div>
                <div class="metric-label">Guests</div>
                <div class="metric-value"><?php echo number_format(count($guestCards)); ?></div>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-door-open"></i></div>
            <div>
                <div class="metric-label">In House</div>
                <div class="metric-value"><?php echo number_format($inHouseCount); ?></div>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-calendar-check"></i></div>
            <div>
                <div class="metric-label">Stay Records</div>
                <div class="metric-value"><?php echo number_format($totalStays); ?></div>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-box-arrow-right"></i></div>
            <div>
                <div class="metric-label">Checked Out</div>
                <div class="metric-value"><?php echo number_format($checkedOutCount); ?></div>
            </div>
        </div>
    </div>
</div>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label">Property</label>
                <select name="property_id" class="form-select">
                    <option value="0">All properties</option>
                    <?php foreach ($properties as $property): ?>
                        <option value="<?php echo (int)$property['id']; ?>" <?php echo $propertyId === (int)$property['id'] ? 'selected' : ''; ?>>
                            <?php echo h($property['name']); ?><?php echo !empty($property['code']) ? ' - ' . h($property['code']) : ''; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">All</option>
                    <option value="in_house" <?php echo $statusFilter === 'in_house' ? 'selected' : ''; ?>>In House</option>
                    <option value="checked_out" <?php echo $statusFilter === 'checked_out' ? 'selected' : ''; ?>>Checked Out</option>
                    <option value="future" <?php echo $statusFilter === 'future' ? 'selected' : ''; ?>>Future</option>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">From</label>
                <input type="date" name="from" class="form-control" value="<?php echo h($from); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">To</label>
                <input type="date" name="to" class="form-control" value="<?php echo h($to); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($q); ?>" placeholder="Name, phone, email, ID, room...">
            </div>

            <div class="col-md-1 d-grid">
                <button class="btn btn-primary">Go</button>
            </div>
        </form>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h5 class="mb-0">Guest Register</h5>
            <small>Showing latest 500 checked-in guest occupant records, grouped into guest cards.</small>
        </div>
    </div>

    <div class="card-body p-0">
        <div class="table-responsive guest-table-scroll">
            <table class="table table-modern align-middle mb-0">
                <thead>
                    <tr>
                        <th>Guest</th>
                        <th>Contact / ID</th>
                        <th>Nationality</th>
                        <th>Last Stay</th>
                        <th class="text-end">Stays</th>
                        <th class="text-end">Balance</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$guestCards): ?>
                        <tr>
                            <td colspan="8" class="text-center text-muted py-5">No guests found from check-in records yet.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($guestCards as $guest): ?>
                            <?php
                            $lastBookingId = (int)$guest['last_booking_id'];
                            $lastOrderNo = trim((string)$guest['last_order_no']);
                            $statusLabel = $guest['in_house'] ? 'In House' : 'Not In House';
                            $statusClass = $guest['in_house'] ? 'text-bg-success' : 'text-bg-light text-dark border';
                            ?>
                            <tr>
                                <td>
                                    <div class="guest-cell">
                                        <div class="guest-avatar"><?php echo h(guest_initials($guest['name'])); ?></div>
                                        <div>
                                            <div class="fw-bold"><?php echo h($guest['name']); ?></div>
                                            <div class="small text-muted">
                                                <?php echo $guest['guest_id'] > 0 ? 'Profile #' . (int)$guest['guest_id'] : 'Check-in profile'; ?>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="data-stack">
                                        <strong><?php echo h($guest['phone'] !== '' ? $guest['phone'] : ($guest['email'] !== '' ? $guest['email'] : '—')); ?></strong>
                                        <small>
                                            <?php
                                            $idText = trim(($guest['id_type'] !== '' ? $guest['id_type'] . ': ' : '') . $guest['id_number']);
                                            echo h($idText !== '' ? $idText : ($guest['email'] !== '' ? $guest['email'] : 'No ID captured'));
                                            ?>
                                        </small>
                                    </div>
                                </td>
                                <td>
                                    <div class="data-stack">
                                        <strong><?php echo h($guest['nationality'] !== '' ? $guest['nationality'] : '—'); ?></strong>
                                        <small><?php echo h($guest['gender'] !== '' ? $guest['gender'] : ''); ?></small>
                                    </div>
                                </td>
                                <td>
                                    <div class="data-stack">
                                        <strong><?php echo h($guest['last_checkin'] !== '' ? $guest['last_checkin'] : '—'); ?></strong>
                                        <small><?php echo h($lastOrderNo !== '' ? $lastOrderNo : ($lastBookingId > 0 ? '#' . $lastBookingId : 'No booking')); ?></small>
                                    </div>
                                </td>
                                <td class="text-end fw-bold"><?php echo number_format((int)$guest['total_stays']); ?></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($guest['total_balance']); ?></td>
                                <td><span class="badge <?php echo h($statusClass); ?>"><?php echo h($statusLabel); ?></span></td>
                                <td class="text-end">
                                    <div class="d-inline-flex gap-2 flex-wrap justify-content-end">
                                        <?php if ($lastBookingId > 0): ?>
                                            <a href="/rooms/modules/reservations/reservation_view.php?order_id=<?php echo $lastBookingId; ?>" class="btn btn-sm btn-outline-primary">View</a>
                                            <a href="/rooms/modules/payments/folio_view.php?order_id=<?php echo $lastBookingId; ?>" class="btn btn-sm btn-outline-secondary">Folio</a>
                                        <?php else: ?>
                                            <span class="text-muted small">No action</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>

                            <?php if (!empty($guest['stays']) && count($guest['stays']) > 1): ?>
                                <tr class="guest-history-row">
                                    <td colspan="8">
                                        <details>
                                            <summary>Stay history for <?php echo h($guest['name']); ?></summary>
                                            <div class="table-responsive mt-2">
                                                <table class="table table-sm table-bordered mb-0">
                                                    <thead>
                                                        <tr>
                                                            <th>Booking</th>
                                                            <th>Property</th>
                                                            <th>Room</th>
                                                            <th>Room Type</th>
                                                            <th>Check In</th>
                                                            <th>Check Out</th>
                                                            <th class="text-end">Balance</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($guest['stays'] as $stay): ?>
                                                            <tr>
                                                                <td><?php echo h($stay['order_no'] ?: ('#' . (int)$stay['order_id'])); ?></td>
                                                                <td><?php echo h($stay['property_name'] ?? ''); ?></td>
                                                                <td><?php echo h($stay['actual_room_no'] ?: 'Unassigned'); ?></td>
                                                                <td><?php echo h($stay['room_type_title'] ?: ''); ?></td>
                                                                <td><?php echo h($stay['checked_in_at'] ?: $stay['check_in']); ?></td>
                                                                <td><?php echo h($stay['checked_out_at'] ?: $stay['check_out']); ?></td>
                                                                <td class="text-end"><?php echo money_fmt($stay['booking_balance'] ?? 0); ?></td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </details>
                                    </td>
                                </tr>
                            <?php endif; ?>

                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>

/* COMPACT UX + FROZEN HEADER */
.hero-band {
    padding: 14px 18px !important;
    margin-bottom: 12px !important;
}
.hero-band .row {
    --bs-gutter-y: .5rem !important;
}
.page-eyebrow {
    font-size: .74rem !important;
    margin-bottom: 2px !important;
}
.hero-title {
    font-size: 1.45rem !important;
    line-height: 1.1 !important;
    margin-top: 2px !important;
}
.hero-subtitle {
    font-size: .84rem !important;
    line-height: 1.25 !important;
    margin-top: 4px !important;
}
.metric-card {
    padding: 10px 12px !important;
    gap: 10px !important;
    min-height: auto !important;
}
.metric-icon {
    width: 34px !important;
    height: 34px !important;
    font-size: 14px !important;
    border-radius: 11px !important;
}
.metric-label {
    font-size: .72rem !important;
}
.metric-value {
    font-size: 1.08rem !important;
    line-height: 1.1 !important;
}
.row.g-3.mb-4 {
    margin-bottom: 10px !important;
}
.card.panel-card {
    margin-bottom: 10px !important;
    border-radius: 16px !important;
}
.panel-card .card-body {
    padding: 10px 12px !important;
}
.panel-card .card-header {
    padding: 10px 12px !important;
}
.panel-card .card-header h5 {
    font-size: .95rem !important;
}
.panel-card .card-header small {
    font-size: .72rem !important;
}
.form-label {
    font-size: .72rem !important;
    margin-bottom: 2px !important;
    font-weight: 700 !important;
}
.form-control,
.form-select {
    min-height: 34px !important;
    height: 34px !important;
    padding-top: 4px !important;
    padding-bottom: 4px !important;
    font-size: .84rem !important;
}
.btn {
    padding-top: .36rem !important;
    padding-bottom: .36rem !important;
}
.guest-table-scroll {
    max-height: calc(100vh - 255px);
    overflow: auto;
    border-radius: 0 0 16px 16px;
}
.table-modern {
    font-size: .84rem !important;
    border-collapse: separate;
    border-spacing: 0;
}
.table-modern thead th {
    position: sticky;
    top: 0;
    z-index: 30;
    background: linear-gradient(180deg, #ffffff, #f8fafc) !important;
    border-bottom: 2px solid #e5e7eb !important;
    box-shadow: 0 2px 0 rgba(15,23,42,.04);
    padding: 8px 10px !important;
    font-size: .72rem !important;
    white-space: nowrap;
}
.table-modern tbody td {
    padding: 7px 10px !important;
    vertical-align: middle;
}
.table-modern tbody tr {
    height: auto !important;
}
.data-stack strong {
    font-size: .84rem !important;
}
.data-stack small {
    font-size: .69rem !important;
    line-height: 1.2 !important;
}
.guest-history-row details {
    padding: 2px 6px !important;
}
.guest-history-row .table-sm th,
.guest-history-row .table-sm td {
    padding: 5px 7px !important;
    font-size: .78rem !important;
}
@media (max-width: 991.98px) {
    .guest-table-scroll {
        max-height: calc(100vh - 300px);
    }
}

.guest-cell{
    display:flex;
    align-items:center;
    gap:8px;
}
.guest-avatar{
    width:30px;
    height:30px;
    border-radius:10px;
    background:linear-gradient(135deg,#0d6efd,#6610f2);
    color:#fff;
    display:flex;
    align-items:center;
    justify-content:center;
    font-weight:800;
    font-size:.7rem;
    box-shadow:0 8px 18px rgba(13,110,253,.2);
}
.guest-history-row td{
    background:#fbfdff;
}
.guest-history-row details{
    padding:4px 8px;
}
.guest-history-row summary{
    cursor:pointer;
    font-weight:700;
    color:#334155;
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
