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

$pageTitle = 'Check In';

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('checkin_safe_begin')) {
    function checkin_safe_begin(PDO $pdo): bool
    {
        if ($pdo->inTransaction()) {
            return false;
        }
        return $pdo->beginTransaction();
    }
}

if (!function_exists('checkin_safe_commit')) {
    function checkin_safe_commit(PDO $pdo): void
    {
        if ($pdo->inTransaction()) {
            $pdo->commit();
        }
    }
}

if (!function_exists('checkin_safe_rollback')) {
    function checkin_safe_rollback(PDO $pdo): void
    {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
    }
}

if (!function_exists('folio_type_badge')) {
    function folio_type_badge(string $type): string
    {
        $type = strtolower(trim($type));

        switch ($type) {
            case 'master':
                return '<span class="badge text-bg-dark">Master</span>';
            case 'room':
                return '<span class="badge text-bg-primary">Room</span>';
            case 'guest':
                return '<span class="badge text-bg-info text-dark">Guest</span>';
            default:
                return '<span class="badge text-bg-secondary">' . h(ucfirst($type !== '' ? $type : 'Unknown')) . '</span>';
        }
    }
}

if (!function_exists('get_or_create_master_folio')) {
    function get_or_create_master_folio(PDO $pdo, int $orderId): int
    {
        $stmt = $pdo->prepare("
            SELECT id
            FROM folios
            WHERE order_id = :order_id
              AND folio_type = 'master'
            LIMIT 1
        ");
        $stmt->execute([':order_id' => $orderId]);
        $id = (int)($stmt->fetchColumn() ?: 0);
        if ($id > 0) {
            return $id;
        }

        $stmt = $pdo->prepare("
            SELECT property_id, order_no
            FROM orders
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            throw new RuntimeException('Booking not found while creating master folio.');
        }

        $stmt = $pdo->prepare("
            INSERT INTO folios
            (
                property_id,
                order_id,
                folio_no,
                folio_name,
                folio_type,
                status,
                total_charges,
                total_payments,
                balance
            )
            VALUES
            (
                :property_id,
                :order_id,
                :folio_no,
                :folio_name,
                'master',
                1,
                0,
                0,
                0
            )
        ");
        $stmt->execute([
            ':property_id' => (int)($order['property_id'] ?? 0),
            ':order_id'    => $orderId,
            ':folio_no'    => 'FOL-M-' . $orderId,
            ':folio_name'  => 'Master Folio - ' . ($order['order_no'] ?: ('Booking #' . $orderId)),
        ]);

        return (int)$pdo->lastInsertId();
    }
}

if (!function_exists('build_room_folio_holder_name')) {
    function build_room_folio_holder_name(array $occupants): string
    {
        if (!$occupants) {
            return 'Pending Check-in';
        }

        $primary = null;
        foreach ($occupants as $occ) {
            if ((int)($occ['is_primary'] ?? 0) === 1) {
                $primary = $occ;
                break;
            }
        }

        if ($primary) {
            $name = trim((string)($primary['first_name'] ?? '') . ' ' . (string)($primary['last_name'] ?? ''));
            return $name !== '' ? $name : 'Pending Check-in';
        }

        $first = $occupants[0];
        $name = trim((string)($first['first_name'] ?? '') . ' ' . (string)($first['last_name'] ?? ''));
        return $name !== '' ? $name : 'Pending Check-in';
    }
}

if (!function_exists('build_room_mix_for_order')) {
    function build_room_mix_for_order(PDO $pdo, int $orderId): string
    {
        $stmt = $pdo->prepare("
            SELECT
                rt.title,
                COUNT(*) AS qty_rooms
            FROM order_rooming rmg
            INNER JOIN room_types rt ON rt.id = rmg.room_type_id
            WHERE rmg.order_id = :order_id
            GROUP BY rmg.room_type_id, rt.title
            ORDER BY rt.title ASC
        ");
        $stmt->execute([':order_id' => $orderId]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!$rows) {
            return '';
        }

        $parts = [];
        foreach ($rows as $row) {
            $title = trim((string)($row['title'] ?? ''));
            if ($title === '') {
                continue;
            }
            $parts[] = $title . ' x ' . (int)($row['qty_rooms'] ?? 0);
        }

        return implode(', ', $parts);
    }
}

if (!function_exists('get_or_create_room_folio_from_rooming')) {
    function get_or_create_room_folio_from_rooming(PDO $pdo, int $orderId, array $rooming, string $folioHolderName): int
    {
        $roomingId = (int)($rooming['id'] ?? 0);
        if ($roomingId <= 0) {
            throw new RuntimeException('Invalid room slot for folio creation.');
        }

        $stmt = $pdo->prepare("
            SELECT property_id
            FROM orders
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $orderId]);
        $propertyId = (int)($stmt->fetchColumn() ?: 0);

        $roomNo = trim((string)($rooming['actual_room_no'] ?? $rooming['room_no'] ?? ''));
        if ($roomNo === '') {
            $roomNo = 'N/A';
        }

        $requestedType = trim((string)($rooming['room_type_title'] ?? ''));
        $folioName = 'Room ' . $roomNo;
        if ($requestedType !== '') {
            $folioName .= ' • ' . $requestedType;
        }
        $folioName .= ' - ' . $folioHolderName;

        $folioNo = 'FOL-R-' . $roomNo . '-' . $orderId;

        /*
           A rooming row may be deleted and recreated during room/date edits.
           In that case the existing room folio still has the correct unique
           folio_no, but its old rooming_id no longer matches. Looking up only by
           rooming_id then tries to INSERT the same folio_no again and triggers
           folios.uq_folio_no.

           Resolve both identities and reuse the existing folio number.
        */
        $stmt = $pdo->prepare("
            SELECT id
            FROM folios
            WHERE order_id = :order_id
              AND rooming_id = :rooming_id
              AND folio_type = 'room'
            ORDER BY id ASC
            LIMIT 1
            FOR UPDATE
        ");
        $stmt->execute([
            ':order_id'   => $orderId,
            ':rooming_id' => $roomingId,
        ]);
        $roomingFolioId = (int)($stmt->fetchColumn() ?: 0);

        $stmt = $pdo->prepare("
            SELECT id
            FROM folios
            WHERE folio_no = :folio_no
            LIMIT 1
            FOR UPDATE
        ");
        $stmt->execute([':folio_no' => $folioNo]);
        $numberFolioId = (int)($stmt->fetchColumn() ?: 0);

        /*
           Legacy fallback: reservation_form.php historically created room
           folios with room_id populated but rooming_id left NULL, and with a
           different folio number. Reuse that row instead of inserting another
           room folio at check-in.
        */
        $roomId = (int)($rooming['room_id'] ?? 0);
        $legacyRoomFolioId = 0;
        if ($roomId > 0) {
            $stmt = $pdo->prepare("
                SELECT id
                FROM folios
                WHERE order_id = :order_id
                  AND folio_type = 'room'
                  AND room_id = :room_id
                ORDER BY
                    CASE WHEN rooming_id IS NULL THEN 0 ELSE 1 END,
                    id ASC
                LIMIT 1
                FOR UPDATE
            " );
            $stmt->execute([
                ':order_id' => $orderId,
                ':room_id'  => $roomId,
            ]);
            $legacyRoomFolioId = (int)($stmt->fetchColumn() ?: 0);
        }

        // Prefer the already rooming-linked folio, then the physical-room
        // number folio, then the legacy room_id-only folio.
        $folioId = $roomingFolioId > 0
            ? $roomingFolioId
            : ($numberFolioId > 0 ? $numberFolioId : $legacyRoomFolioId);

        /*
           If more than one identity points to different folios, keep the
           selected folio, move all transactions to it, and retire the stale
           rows. This preserves history while preventing future duplicates.
        */
        $candidateIds = array_values(array_unique(array_filter([
            $roomingFolioId,
            $numberFolioId,
            $legacyRoomFolioId,
        ], static function ($id) use ($folioId) {
            return (int)$id > 0 && (int)$id !== (int)$folioId;
        })));

        foreach ($candidateIds as $staleFolioId) {
            try {
                $pdo->prepare("
                    UPDATE folio_transactions
                    SET folio_id = :keep_id
                    WHERE folio_id = :stale_id
                " )->execute([
                    ':keep_id'  => $folioId,
                    ':stale_id' => $staleFolioId,
                ]);
            } catch (Throwable $e) {
                // Do not block check-in when the transaction table is absent
                // or there are no transactions on the stale folio.
            }

            $retireSets = ["status = 0"];
            if (checkin_column_exists($pdo, 'folios', 'rooming_id')) {
                $retireSets[] = "rooming_id = NULL";
            }
            if (checkin_column_exists($pdo, 'folios', 'updated_at')) {
                $retireSets[] = "updated_at = NOW()";
            }
            $pdo->prepare("
                UPDATE folios
                SET " . implode(', ', $retireSets) . "
                WHERE id = :id
            " )->execute([':id' => $staleFolioId]);
        }

        if ($folioId > 0) {
            $stmt = $pdo->prepare("
                UPDATE folios
                SET property_id = :property_id,
                    order_id = :order_id,
                    room_id = :room_id,
                    rooming_id = :rooming_id,
                    folio_name = :folio_name,
                    folio_no = :folio_no,
                    folio_type = 'room',
                    status = 1,
                    updated_at = NOW()
                WHERE id = :id
            ");
            $stmt->execute([
                ':property_id' => $propertyId,
                ':order_id'    => $orderId,
                ':room_id'     => (int)($rooming['room_id'] ?? 0),
                ':rooming_id'  => $roomingId,
                ':folio_name'  => $folioName,
                ':folio_no'    => $folioNo,
                ':id'          => $folioId,
            ]);

            return $folioId;
        }

        /*
           Last race-condition guard: another request may have created this
           folio after our SELECT but before INSERT. On duplicate key, fetch and
           reuse it instead of failing the entire check-in.
        */
        try {
            $stmt = $pdo->prepare("
                INSERT INTO folios
                (
                    property_id,
                    order_id,
                    folio_no,
                    folio_name,
                    folio_type,
                    room_id,
                    rooming_id,
                    status,
                    total_charges,
                    total_payments,
                    balance
                )
                VALUES
                (
                    :property_id,
                    :order_id,
                    :folio_no,
                    :folio_name,
                    'room',
                    :room_id,
                    :rooming_id,
                    1,
                    0,
                    0,
                    0
                )
            ");
            $stmt->execute([
                ':property_id' => $propertyId,
                ':order_id'    => $orderId,
                ':folio_no'    => $folioNo,
                ':folio_name'  => $folioName,
                ':room_id'     => (int)($rooming['room_id'] ?? 0),
                ':rooming_id'  => $roomingId,
            ]);

            return (int)$pdo->lastInsertId();
        } catch (PDOException $e) {
            if ((string)$e->getCode() !== '23000') {
                throw $e;
            }

            $stmt = $pdo->prepare("
                SELECT id
                FROM folios
                WHERE folio_no = :folio_no
                LIMIT 1
            ");
            $stmt->execute([':folio_no' => $folioNo]);
            $folioId = (int)($stmt->fetchColumn() ?: 0);

            if ($folioId <= 0) {
                throw $e;
            }

            $pdo->prepare("
                UPDATE folios
                SET property_id = :property_id,
                    order_id = :order_id,
                    room_id = :room_id,
                    rooming_id = :rooming_id,
                    folio_name = :folio_name,
                    folio_type = 'room',
                    status = 1,
                    updated_at = NOW()
                WHERE id = :id
            ")->execute([
                ':property_id' => $propertyId,
                ':order_id'    => $orderId,
                ':room_id'     => (int)($rooming['room_id'] ?? 0),
                ':rooming_id'  => $roomingId,
                ':folio_name'  => $folioName,
                ':id'          => $folioId,
            ]);

            return $folioId;
        }
    }
}


if (!function_exists('checkin_column_exists')) {
    function checkin_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('checkin_guest_extra_columns')) {
    function checkin_guest_extra_columns(PDO $pdo): array
    {
        $columns = [
            'id_type',
            'id_number',
            'nationality',
            'gender',
            'date_of_birth',
            'phone',
            'email',
            'address',
            'signature_data',
            'registration_notes',
        ];

        $available = [];
        foreach ($columns as $column) {
            if (checkin_column_exists($pdo, 'order_rooming_guests', $column)) {
                $available[] = $column;
            }
        }
        return $available;
    }
}

if (!function_exists('insert_rooming_guest_registration')) {
    function insert_rooming_guest_registration(PDO $pdo, int $orderId, int $roomingId, array $guest, array $extraColumns): int
    {
        $columns = [
            'order_id',
            'rooming_id',
            'first_name',
            'last_name',
            'is_primary',
            'checked_in_at',
            'checked_out_at',
        ];

        $values = [
            ':order_id',
            ':rooming_id',
            ':first_name',
            ':last_name',
            ':is_primary',
            'NOW()',
            'NULL',
        ];

        $params = [
            ':order_id'   => $orderId,
            ':rooming_id' => $roomingId,
            ':first_name' => $guest['first_name'],
            ':last_name'  => $guest['last_name'],
            ':is_primary' => (int)$guest['is_primary'],
        ];

        foreach ($extraColumns as $column) {
            $columns[] = $column;
            $placeholder = ':' . $column;
            $values[] = $placeholder;
            $params[$placeholder] = $guest[$column] ?? null;
        }

        $sql = "
            INSERT INTO order_rooming_guests
            (" . implode(', ', $columns) . ")
            VALUES
            (" . implode(', ', $values) . ")
        ";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        return (int)$pdo->lastInsertId();
    }
}

if (!function_exists('checkin_ensure_room_occupants_table')) {
    function checkin_ensure_room_occupants_table(PDO $pdo): void
    {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS order_room_occupants (
                id INT UNSIGNED NOT NULL AUTO_INCREMENT,
                order_id INT UNSIGNED NOT NULL,
                rooming_id INT UNSIGNED NOT NULL,
                order_rooming_guest_id INT UNSIGNED NULL,
                guest_id INT UNSIGNED NULL,
                occupant_name VARCHAR(150) NOT NULL,
                first_name VARCHAR(100) NULL,
                last_name VARCHAR(100) NULL,
                is_primary TINYINT NOT NULL DEFAULT 0,
                status TINYINT NOT NULL DEFAULT 1,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY idx_order_rooming (order_id, rooming_id),
                KEY idx_rooming_status (rooming_id, status),
                KEY idx_guest_id (guest_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        " );

        /* If the table already existed before this feature, add the new columns safely. */
        $missingColumns = [
            'order_rooming_guest_id' => 'INT UNSIGNED NULL',
            'guest_id' => 'INT UNSIGNED NULL',
            'first_name' => 'VARCHAR(100) NULL',
            'last_name' => 'VARCHAR(100) NULL',
            'is_primary' => 'TINYINT NOT NULL DEFAULT 0',
            'status' => 'TINYINT NOT NULL DEFAULT 1',
            'created_at' => 'TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP',
            'updated_at' => 'TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
        ];

        foreach ($missingColumns as $column => $definition) {
            try {
                if (!checkin_column_exists($pdo, 'order_room_occupants', $column)) {
                    $pdo->exec("ALTER TABLE order_room_occupants ADD COLUMN {$column} {$definition}");
                }
            } catch (Throwable $e) {
                // Do not block check-in if an optional compatibility column cannot be added.
            }
        }
    }
}

if (!function_exists('checkin_ensure_folio_occupant_columns')) {
    function checkin_ensure_folio_occupant_columns(PDO $pdo): void
    {
        try {
            if (!checkin_column_exists($pdo, 'folios', 'guest_id')) {
                $pdo->exec("ALTER TABLE folios ADD COLUMN guest_id INT UNSIGNED NULL");
            }
        } catch (Throwable $e) {}

        try {
            if (!checkin_column_exists($pdo, 'folios', 'occupant_id')) {
                $pdo->exec("ALTER TABLE folios ADD COLUMN occupant_id INT UNSIGNED NULL");
            }
        } catch (Throwable $e) {}

        try {
            if (!checkin_column_exists($pdo, 'folios', 'occupant_name')) {
                $pdo->exec("ALTER TABLE folios ADD COLUMN occupant_name VARCHAR(150) NULL");
            }
        } catch (Throwable $e) {}
    }
}

if (!function_exists('insert_order_room_occupant')) {
    function insert_order_room_occupant(PDO $pdo, int $orderId, int $roomingId, int $roomingGuestId, array $guest): int
    {
        $firstName = trim((string)($guest['first_name'] ?? ''));
        $lastName  = trim((string)($guest['last_name'] ?? ''));
        $occupantName = trim($firstName . ' ' . $lastName);
        if ($occupantName === '') {
            $occupantName = 'Occupant';
        }

        $stmt = $pdo->prepare("
            INSERT INTO order_room_occupants
            (
                order_id, rooming_id, order_rooming_guest_id, guest_id, occupant_name,
                first_name, last_name, is_primary, status
            )
            VALUES
            (
                :order_id, :rooming_id, :order_rooming_guest_id, NULL, :occupant_name,
                :first_name, :last_name, :is_primary, 1
            )
        " );
        $stmt->execute([
            ':order_id' => $orderId,
            ':rooming_id' => $roomingId,
            ':order_rooming_guest_id' => $roomingGuestId > 0 ? $roomingGuestId : null,
            ':occupant_name' => $occupantName,
            ':first_name' => $firstName !== '' ? $firstName : null,
            ':last_name' => $lastName !== '' ? $lastName : null,
            ':is_primary' => (int)($guest['is_primary'] ?? 0),
        ]);

        return (int)$pdo->lastInsertId();
    }
}

if (!function_exists('get_or_create_guest_folio_from_occupant')) {
    function get_or_create_guest_folio_from_occupant(PDO $pdo, int $orderId, array $rooming, array $occupant): int
    {
        checkin_ensure_folio_occupant_columns($pdo);

        $occupantId = (int)($occupant['id'] ?? 0);
        $roomingId = (int)($rooming['id'] ?? 0);
        if ($occupantId <= 0 || $roomingId <= 0) {
            throw new RuntimeException('Invalid occupant folio target.');
        }

        $stmt = $pdo->prepare("
            SELECT property_id
            FROM orders
            WHERE id = :id
            LIMIT 1
        " );
        $stmt->execute([':id' => $orderId]);
        $propertyId = (int)($stmt->fetchColumn() ?: 0);

        $roomNo = trim((string)($rooming['actual_room_no'] ?? $rooming['room_no'] ?? ''));
        if ($roomNo === '') {
            $roomNo = 'N/A';
        }

        $occupantName = trim((string)($occupant['occupant_name'] ?? ''));
        if ($occupantName === '') {
            $occupantName = 'Occupant #' . $occupantId;
        }

        $roomType = trim((string)($rooming['room_type_title'] ?? ''));
        $folioNo = 'FOL-G-' . preg_replace('/[^A-Za-z0-9]+/', '', $roomNo) . '-' . $occupantId . '-' . $orderId;
        $folioName = $occupantName . ' - Room ' . $roomNo;
        if ($roomType !== '') {
            $folioName .= ' • ' . $roomType;
        }

        $stmt = $pdo->prepare("
            SELECT id
            FROM folios
            WHERE order_id = :order_id
              AND folio_type = 'guest'
              AND occupant_id = :occupant_id
            LIMIT 1
        " );
        $stmt->execute([
            ':order_id' => $orderId,
            ':occupant_id' => $occupantId,
        ]);
        $folioId = (int)($stmt->fetchColumn() ?: 0);

        if ($folioId > 0) {
            $stmt = $pdo->prepare("
                UPDATE folios
                SET property_id = :property_id,
                    room_id = :room_id,
                    rooming_id = :rooming_id,
                    guest_id = :guest_id,
                    occupant_id = :occupant_id,
                    occupant_name = :occupant_name,
                    folio_no = :folio_no,
                    folio_name = :folio_name,
                    status = 1,
                    updated_at = NOW()
                WHERE id = :id
            " );
            $stmt->execute([
                ':property_id' => $propertyId,
                ':room_id' => (int)($rooming['room_id'] ?? 0),
                ':rooming_id' => $roomingId,
                ':guest_id' => !empty($occupant['guest_id']) ? (int)$occupant['guest_id'] : null,
                ':occupant_id' => $occupantId,
                ':occupant_name' => $occupantName,
                ':folio_no' => $folioNo,
                ':folio_name' => $folioName,
                ':id' => $folioId,
            ]);
            return $folioId;
        }

        $stmt = $pdo->prepare("
            INSERT INTO folios
            (
                property_id, order_id, folio_no, folio_name, folio_type,
                room_id, rooming_id, guest_id, occupant_id, occupant_name,
                status, total_charges, total_payments, balance
            )
            VALUES
            (
                :property_id, :order_id, :folio_no, :folio_name, 'guest',
                :room_id, :rooming_id, :guest_id, :occupant_id, :occupant_name,
                1, 0, 0, 0
            )
        " );
        $stmt->execute([
            ':property_id' => $propertyId,
            ':order_id' => $orderId,
            ':folio_no' => $folioNo,
            ':folio_name' => $folioName,
            ':room_id' => (int)($rooming['room_id'] ?? 0),
            ':rooming_id' => $roomingId,
            ':guest_id' => !empty($occupant['guest_id']) ? (int)$occupant['guest_id'] : null,
            ':occupant_id' => $occupantId,
            ':occupant_name' => $occupantName,
        ]);

        return (int)$pdo->lastInsertId();
    }
}

$orderId = (int)($_GET['order_id'] ?? $_POST['order_id'] ?? 0);
$errors = [];
$success = '';

$order = null;
$roomingRows = [];
$occupantMap = [];
$folioMap = [];
$bookingFolios = [];
$roomMix = '';

$nationalities = [];
try {
    $stmtNat = $pdo->query("SELECT id, nationality FROM nationality ORDER BY nationality ASC");
    $nationalities = $stmtNat->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $nationalities = [];
}

$nationalityOptionsHtml = '<option value="">Select nationality</option>';
foreach ($nationalities as $nat) {
    $natName = (string)($nat['nationality'] ?? '');
    if ($natName === '') {
        continue;
    }
    $nationalityOptionsHtml .= '<option value="' . h($natName) . '">' . h($natName) . '</option>';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_room_checkin'])) {
    $orderId = (int)($_POST['order_id'] ?? 0);
    $roomingId = (int)($_POST['rooming_id'] ?? 0);

    $firstNames        = $_POST['occupant_first_name'] ?? [];
    $lastNames         = $_POST['occupant_last_name'] ?? [];
    $idTypes           = $_POST['occupant_id_type'] ?? [];
    $idNumbers         = $_POST['occupant_id_number'] ?? [];
    $nationalities     = $_POST['occupant_nationality'] ?? [];
    $genders           = $_POST['occupant_gender'] ?? [];
    $datesOfBirth      = $_POST['occupant_date_of_birth'] ?? [];
    $phones            = $_POST['occupant_phone'] ?? [];
    $emails            = $_POST['occupant_email'] ?? [];
    $addresses         = $_POST['occupant_address'] ?? [];
    $signatures        = $_POST['occupant_signature_data'] ?? [];
    $registrationNotes = $_POST['occupant_registration_notes'] ?? [];
    $primaryIndex = isset($_POST['primary_guest_index']) ? (int)$_POST['primary_guest_index'] : 0;

    if ($orderId <= 0 || $roomingId <= 0) {
        $errors[] = 'Invalid booking or room slot.';
    }

    /*
       SAME-DAY TURNOVER GUARD
       If the guest is checking INTO a physical room that another guest is due
       to check OUT of TODAY, and that departing guest has not been checked out
       yet, block this check-in. The room must be physically vacated first.
       Only applies to same-day, same-room turnover; different rooms or future
       departures are unaffected.
    */
    if (empty($errors) && checkin_column_exists($pdo, 'order_rooming', 'checked_out_status')) {
        try {
            // Resolve the physical room this check-in targets.
            $rmStmt = $pdo->prepare("SELECT room_id, check_in FROM order_rooming WHERE id = :rid AND order_id = :oid LIMIT 1");
            $rmStmt->execute([':rid' => $roomingId, ':oid' => $orderId]);
            $thisRow = $rmStmt->fetch(PDO::FETCH_ASSOC) ?: [];
            $thisRoomId = (int)($thisRow['room_id'] ?? 0);
            $today = date('Y-m-d');

            if ($thisRoomId > 0) {
                $clashStmt = $pdo->prepare("
                    SELECT rmg.id, rmg.order_id, o.order_no,
                           TRIM(CONCAT(COALESCE(g.firstname,''),' ',COALESCE(g.lastname,''))) AS guest_name
                    FROM order_rooming rmg
                    INNER JOIN orders o ON o.id = rmg.order_id
                    LEFT JOIN guests g ON g.id = o.guest_id
                    WHERE rmg.room_id = :room_id
                      AND rmg.id <> :self_rooming_id
                      AND DATE(rmg.check_out) = :today
                      AND COALESCE(rmg.checked_out_status, 0) = 0
                      AND COALESCE(rmg.checked_in_status, 0) = 1
                      AND COALESCE(o.status, 1) NOT IN (0, 5)
                    LIMIT 1
                ");
                $clashStmt->execute([
                    ':room_id' => $thisRoomId,
                    ':self_rooming_id' => $roomingId,
                    ':today' => $today,
                ]);
                $occupant = $clashStmt->fetch(PDO::FETCH_ASSOC);
                if ($occupant) {
                    $who = trim((string)($occupant['guest_name'] ?? '')) ?: ('Booking ' . ($occupant['order_no'] ?: ('#' . $occupant['order_id'])));
                    $errors[] = 'This room is still occupied by ' . $who
                        . ', who is due to check out today but has not been checked out yet. '
                        . 'Please complete their check-out before checking in the new guest.';
                }
            }
        } catch (Throwable $e) {
            // Guard is best-effort; never hard-fail check-in on a detection error.
        }
    }

    $cleanOccupants = [];
    $countRows = max(
        count($firstNames),
        count($lastNames),
        count($idTypes),
        count($idNumbers),
        count($nationalities),
        count($genders),
        count($datesOfBirth),
        count($phones),
        count($emails),
        count($addresses),
        count($signatures),
        count($registrationNotes)
    );

    for ($i = 0; $i < $countRows; $i++) {
        $fn = trim((string)($firstNames[$i] ?? ''));
        $ln = trim((string)($lastNames[$i] ?? ''));
        $idNumber = trim((string)($idNumbers[$i] ?? ''));

        if ($fn === '' && $ln === '' && $idNumber === '') {
            continue;
        }

        $dob = trim((string)($datesOfBirth[$i] ?? ''));
        if ($dob !== '' && strtotime($dob) === false) {
            $dob = '';
        }

        $cleanOccupants[] = [
            'first_name'         => $fn,
            'last_name'          => $ln,
            'is_primary'         => ($i === $primaryIndex ? 1 : 0),
            'id_type'            => trim((string)($idTypes[$i] ?? '')),
            'id_number'          => $idNumber,
            'nationality'        => trim((string)($nationalities[$i] ?? '')),
            'gender'             => trim((string)($genders[$i] ?? '')),
            'date_of_birth'      => $dob !== '' ? $dob : null,
            'phone'              => trim((string)($phones[$i] ?? '')),
            'email'              => trim((string)($emails[$i] ?? '')),
            'address'            => trim((string)($addresses[$i] ?? '')),
            'signature_data'     => trim((string)($signatures[$i] ?? '')),
            'registration_notes' => trim((string)($registrationNotes[$i] ?? '')),
        ];
    }

    if (!$errors && empty($cleanOccupants)) {
        $errors[] = 'Please enter at least one occupant for this room.';
    }

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("
                SELECT rmg.*, rm.room_no AS actual_room_no, rt.title AS room_type_title
                FROM order_rooming rmg
                LEFT JOIN rooms rm ON rm.id = rmg.room_id
                LEFT JOIN room_types rt ON rt.id = rmg.room_type_id
                WHERE rmg.id = :id
                  AND rmg.order_id = :order_id
                LIMIT 1
            ");
            $stmt->execute([
                ':id'       => $roomingId,
                ':order_id' => $orderId,
            ]);
            $rooming = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$rooming) {
                throw new RuntimeException('Room slot not found.');
            }

            /*
               Occupant control:
               The registration occupants for this room must not exceed the
               chargeable/registered room pax: Adults + Children.
               Kids 0-3 no charge are intentionally excluded from this limit.
            */
            $roomOccupantLimit = max(1, (int)($rooming['adults'] ?? 0) + (int)($rooming['children'] ?? 0));
            if (count($cleanOccupants) > $roomOccupantLimit) {
                throw new RuntimeException(
                    'This room allows only ' . $roomOccupantLimit .
                    ' registered occupant' . ($roomOccupantLimit === 1 ? '' : 's') .
                    ' based on adults plus children. Kids 0-3 no charge are excluded.'
                );
            }

            $hasPrimary = false;
            foreach ($cleanOccupants as $c) {
                if ((int)$c['is_primary'] === 1) {
                    $hasPrimary = true;
                    break;
                }
            }
            if (!$hasPrimary && !empty($cleanOccupants)) {
                $cleanOccupants[0]['is_primary'] = 1;
            }

            checkin_safe_begin($pdo);

            get_or_create_master_folio($pdo, $orderId);

            checkin_ensure_room_occupants_table($pdo);
            checkin_ensure_folio_occupant_columns($pdo);

            $pdo->prepare("
                DELETE FROM order_rooming_guests
                WHERE order_id = :order_id
                  AND rooming_id = :rooming_id
            ")->execute([
                ':order_id'   => $orderId,
                ':rooming_id' => $roomingId,
            ]);

            $pdo->prepare("
                UPDATE folios
                SET status = 0,
                    updated_at = NOW()
                WHERE order_id = :order_id
                  AND rooming_id = :rooming_id
                  AND folio_type = 'guest'
            ")->execute([
                ':order_id'   => $orderId,
                ':rooming_id' => $roomingId,
            ]);

            $pdo->prepare("
                DELETE FROM order_room_occupants
                WHERE order_id = :order_id
                  AND rooming_id = :rooming_id
            ")->execute([
                ':order_id'   => $orderId,
                ':rooming_id' => $roomingId,
            ]);

            $extraGuestColumns = checkin_guest_extra_columns($pdo);
            $savedOccupants = [];

            foreach ($cleanOccupants as $occ) {
                $roomingGuestId = insert_rooming_guest_registration($pdo, $orderId, $roomingId, $occ, $extraGuestColumns);
                $occupantId = insert_order_room_occupant($pdo, $orderId, $roomingId, $roomingGuestId, $occ);

                $occ['id'] = $occupantId;
                $occ['order_rooming_guest_id'] = $roomingGuestId;
                $occ['occupant_name'] = trim((string)$occ['first_name'] . ' ' . (string)$occ['last_name']);
                if ($occ['occupant_name'] === '') {
                    $occ['occupant_name'] = 'Occupant #' . $occupantId;
                }
                $savedOccupants[] = $occ;
            }

            $folioHolderName = build_room_folio_holder_name($cleanOccupants);
            $roomFolioId = get_or_create_room_folio_from_rooming($pdo, $orderId, $rooming, $folioHolderName);

            foreach ($savedOccupants as $savedOcc) {
                get_or_create_guest_folio_from_occupant($pdo, $orderId, $rooming, $savedOcc);
            }

            $pdo->prepare("
                UPDATE order_rooming
                SET checked_in_status = 1,
                    checked_in_at = NOW(),
                    checked_out_status = 0,
                    checked_out_at = NULL,
                    folio_holder_guest_id = NULL
                WHERE id = :id
                  AND order_id = :order_id
            ")->execute([
                ':id'       => $roomingId,
                ':order_id' => $orderId,
            ]);

            /*
               Keep the physical room card in sync for Housekeeping.
               Housekeeping also reads order_rooming.checked_in_status, but updating
               rooms.status makes the room immediately look occupied on older screens too.
            */
            $checkedInRoomId = (int)($rooming['room_id'] ?? 0);
            if ($checkedInRoomId > 0) {
                try {
                    $pdo->prepare("
                        UPDATE rooms
                        SET status = 'Occupied'
                        WHERE id = :room_id
                    ")->execute([
                        ':room_id' => $checkedInRoomId,
                    ]);
                } catch (Throwable $e) {
                    // Do not block check-in if the room status sync fails.
                }
            }

            $pdo->prepare("
                UPDATE folios
                SET status = 1,
                    updated_at = NOW()
                WHERE id = :id
            ")->execute([
                ':id' => $roomFolioId,
            ]);

            checkin_safe_commit($pdo);

            header('Location: checkin.php?order_id=' . $orderId . '&saved=1');
            exit;
        } catch (Throwable $e) {
            checkin_safe_rollback($pdo);
            $errors[] = $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_booking_checkin'])) {
    $orderId = (int)($_POST['order_id'] ?? 0);

    if ($orderId <= 0) {
        $errors[] = 'Invalid booking selected.';
    }

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM order_rooming
                WHERE order_id = :order_id
                  AND COALESCE(checked_in_status,0) = 0
            ");
            $stmt->execute([':order_id' => $orderId]);
            $pendingCount = (int)$stmt->fetchColumn();

            if ($pendingCount > 0) {
                throw new RuntimeException('Some room slots are not yet checked in. Please capture occupants for all rooms first.');
            }

            checkin_safe_begin($pdo);

            $pdo->prepare("
                UPDATE orders
                SET status = 3
                WHERE id = :id
            ")->execute([
                ':id' => $orderId,
            ]);

            checkin_safe_commit($pdo);

            header('Location: checkin.php?order_id=' . $orderId . '&booking_checked_in=1');
            exit;
        } catch (Throwable $e) {
            checkin_safe_rollback($pdo);
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Room checked in successfully. Room and individual guest folios were updated.';
}
if (isset($_GET['booking_checked_in']) && (int)$_GET['booking_checked_in'] === 1) {
    $success = 'Booking check-in completed successfully.';
}

if ($orderId > 0) {
    $stmt = $pdo->prepare("
        SELECT
            o.*,
            g.firstname,
            g.lastname,
            rt.title AS room_type,
            p.name AS property_name,
            p.code AS property_code,
            TRIM(CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,''))) AS agent_name
        FROM orders o
        LEFT JOIN guests g ON g.id = o.guest_id
        LEFT JOIN room_types rt ON rt.id = o.room_type_id
        LEFT JOIN properties p ON p.id = o.property_id
        LEFT JOIN agents a ON a.id = o.agent_id
        WHERE o.id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        $errors[] = 'Booking not found.';
        $orderId = 0;
    } else {
        $roomMix = build_room_mix_for_order($pdo, $orderId);

        $stmt = $pdo->prepare("
            SELECT rmg.*, rm.room_no AS actual_room_no, rt.title AS room_type_title
            FROM order_rooming rmg
            LEFT JOIN rooms rm ON rm.id = rmg.room_id
            LEFT JOIN room_types rt ON rt.id = rmg.room_type_id
            WHERE rmg.order_id = :order_id
            ORDER BY rmg.room_no ASC, rmg.id ASC
        ");
        $stmt->execute([':order_id' => $orderId]);
        $roomingRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($roomingRows) {
            $roomingIds = array_map(function ($r) {
                return (int)$r['id'];
            }, $roomingRows);

            $placeholders = implode(',', array_fill(0, count($roomingIds), '?'));

            $stmt = $pdo->prepare("
                SELECT *
                FROM order_rooming_guests
                WHERE rooming_id IN ($placeholders)
                ORDER BY rooming_id ASC, is_primary DESC, id ASC
            ");
            $stmt->execute($roomingIds);
            $guestRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($guestRows as $gr) {
                $rid = (int)$gr['rooming_id'];
                if (!isset($occupantMap[$rid])) {
                    $occupantMap[$rid] = [];
                }
                $occupantMap[$rid][] = $gr;
            }
        }

        $stmt = $pdo->prepare("
            SELECT *
            FROM folios
            WHERE order_id = :order_id
            ORDER BY
                CASE folio_type
                    WHEN 'master' THEN 1
                    WHEN 'room' THEN 2
                    WHEN 'guest' THEN 3
                    ELSE 9
                END,
                id ASC
        ");
        $stmt->execute([':order_id' => $orderId]);
        $bookingFolios = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($bookingFolios as $fr) {
            $rid = (int)($fr['rooming_id'] ?? 0);
            if ($rid > 0) {
                $folioMap[$rid] = $fr;
            }
        }
    }
}

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-door-open"></i> Arrival Desk</div>
            <div class="hero-title mt-2">Check In</div>
            <div class="hero-subtitle mt-2">
                Capture actual occupants for each room slot and automatically update room folios with the correct client names.
            </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>Back to Reservations
            </a>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo h($success); ?></div>
<?php endif; ?>

<?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; ?>

<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-8">
                <label class="form-label">Booking ID</label>
                <input type="number" name="order_id" class="form-control" value="<?php echo (int)$orderId; ?>" placeholder="Enter booking ID">
            </div>
            <div class="col-md-4 d-grid">
                <button class="btn btn-primary">Load Booking</button>
            </div>
        </form>
    </div>
</div>

<?php if ($order): ?>
    <?php
    $guestName = trim(($order['firstname'] ?? '') . ' ' . ($order['lastname'] ?? ''));
    if ($guestName === '') {
        $guestName = 'Guest';
    }

    $agentName = trim((string)($order['agent_name'] ?? ''));
    if ($agentName === '') {
        $agentName = 'Direct';
    }

    $propertyName = trim((string)($order['property_name'] ?? ''));
    if ($propertyName === '') {
        $propertyName = 'Not set';
    }
    $propertyLabel = $propertyName;
    if (!empty($order['property_code'])) {
        $propertyLabel .= ' (' . $order['property_code'] . ')';
    }

    $allRoomsCheckedIn = true;
    foreach ($roomingRows as $rr) {
        if ((int)($rr['checked_in_status'] ?? 0) !== 1) {
            $allRoomsCheckedIn = false;
            break;
        }
    }
    ?>

    <div class="row g-4 mb-4">
        <div class="col-xl-4">
            <div class="form-section booking-summary-card compact-summary">
                <div class="form-section-title">
                    <i class="bi bi-journal-text"></i>
                    Booking Summary
                </div>

                <div class="summary-grid">
                    <div class="mini-stat summary-wide"><span>Property</span><strong><?php echo h($propertyLabel); ?></strong></div>
                    <div class="mini-stat"><span>Booking</span><strong><?php echo h($order['order_no'] ?: ('#' . $order['id'])); ?></strong></div>
                    <div class="mini-stat"><span>Lead Guest</span><strong><?php echo h($guestName); ?></strong></div>
                    <div class="mini-stat"><span>Agent</span><strong><?php echo h($agentName); ?></strong></div>
                    <div class="mini-stat"><span>Total Rooms</span><strong><?php echo (int)($order['totalrooms'] ?? 1); ?></strong></div>
                    <div class="mini-stat"><span>Adults / Children</span><strong><?php echo (int)($order['adults'] ?? 0); ?>A / <?php echo (int)($order['kids'] ?? 0); ?>C</strong></div>
                    <div class="mini-stat summary-wide"><span>Stay</span><strong><?php echo h($order['check_in']); ?> to <?php echo h($order['check_out']); ?></strong></div>
                    <div class="mini-stat summary-wide"><span>Room Mix</span><strong><?php echo h($roomMix !== '' ? $roomMix : ($order['room_type'] ?: 'Not set')); ?></strong></div>
                </div>

                <div class="soft-divider"></div>

                <div class="summary-grid status-grid">
                    <div class="mini-stat summary-wide"><span>All Rooms Checked In</span><strong class="<?php echo $allRoomsCheckedIn ? 'balance-zero' : 'status-warning'; ?>"><?php echo $allRoomsCheckedIn ? 'Yes' : 'No'; ?></strong></div>
                </div>
            </div>

            <div class="form-section mt-3 checkin-action-section">
                <div class="form-section-title">
                    <i class="bi bi-check2-circle"></i>
                    Complete Booking Check-In
                </div>

                <div class="mb-3 text-muted small">
                    Use this after all room slots have occupants captured and their room folios are already updated.
                </div>

                <div class="registration-actions mb-3">
                    <a href="/rooms/modules/reservations/guest_registration_pdf.php?order_id=<?php echo (int)$order['id']; ?>"
                       target="_blank"
                       class="btn btn-dark w-100 mb-2">
                        <i class="bi bi-file-earmark-pdf me-2"></i>Open Registration Form
                    </a>
                    <a href="/rooms/modules/reservations/guest_registration_pdf.php?order_id=<?php echo (int)$order['id']; ?>&download=1"
                       class="btn btn-outline-dark w-100">
                        <i class="bi bi-download me-2"></i>Download Registration PDF
                    </a>
                </div>

                <form method="post">
                    <input type="hidden" name="order_id" value="<?php echo (int)$order['id']; ?>">
                    <div class="d-grid">
                        <button type="submit" name="complete_booking_checkin" value="1" class="btn btn-success btn-lg">
                            <i class="bi bi-check2-square me-2"></i>Complete Booking Check-In
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="col-xl-8">
            <div class="card panel-card">
                <div class="card-header">
                    <h5 class="mb-0">Room Check-In Control</h5>
                </div>
                <div class="card-body">
                    <?php if (!$roomingRows): ?>
                        <div class="text-center text-muted py-4">No room slots found for this booking.</div>
                    <?php else: ?>
                        <div class="accordion" id="checkinAccordion">
                            <?php foreach ($roomingRows as $idx => $room): ?>
                                <?php
                                $rid = (int)$room['id'];
                                $roomFolio = $folioMap[$rid] ?? null;
                                $occupants = $occupantMap[$rid] ?? [];
                                $collapseId = 'roomCollapse' . $rid;
                                $headingId = 'roomHeading' . $rid;
                                $isOpen = $idx === 0 ? 'show' : '';
                                $btnState = $idx === 0 ? '' : 'collapsed';
                                $checkedIn = (int)($room['checked_in_status'] ?? 0) === 1;
                                $occupantLimit = max(1, (int)($room['adults'] ?? 0) + (int)($room['children'] ?? 0));
                                ?>

                                <div class="accordion-item mb-3 border rounded-3 overflow-hidden">
                                    <h2 class="accordion-header" id="<?php echo $headingId; ?>">
                                        <button class="accordion-button <?php echo $btnState; ?>" type="button"
                                                data-bs-toggle="collapse"
                                                data-bs-target="#<?php echo $collapseId; ?>"
                                                aria-expanded="<?php echo $idx === 0 ? 'true' : 'false'; ?>"
                                                aria-controls="<?php echo $collapseId; ?>">
                                            <div class="w-100 d-flex justify-content-between align-items-center pe-3">
                                                <div>
                                                    <strong>Room <?php echo h($room['actual_room_no'] ?: 'Unassigned'); ?></strong>
                                                    <div class="small text-muted">
                                                        Requested Type:
                                                        <?php echo h((string)($room['room_type_title'] ?? 'Not set')); ?>
                                                        • Assigned Room:
                                                        <?php echo !empty($room['actual_room_no']) ? h($room['actual_room_no']) : 'Unassigned'; ?>
                                                        • <?php echo (int)($room['adults'] ?? 0); ?>A /
                                                        <?php echo (int)($room['children'] ?? 0); ?>C
                                                        • Max occupants: <?php echo (int)$occupantLimit; ?>
                                                    </div>
                                                </div>
                                                <div class="text-end">
                                                    <?php if ($checkedIn): ?>
                                                        <span class="badge text-bg-success">Checked In</span>
                                                    <?php else: ?>
                                                        <span class="badge text-bg-warning text-dark">Pending</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </button>
                                    </h2>

                                    <div id="<?php echo $collapseId; ?>"
                                         class="accordion-collapse collapse <?php echo $isOpen; ?>"
                                         aria-labelledby="<?php echo $headingId; ?>"
                                         data-bs-parent="#checkinAccordion">
                                        <div class="accordion-body">
                                            <div class="row g-4">
                                                <div class="col-lg-7">
                                                    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
                                                        <h6 class="mb-0">Guest Registration / Occupants</h6>
                                                        <span class="badge text-bg-light border text-dark">
                                                            Limit: <?php echo (int)$occupantLimit; ?> occupant<?php echo $occupantLimit === 1 ? '' : 's'; ?>
                                                            <small class="text-muted">(Adults + Children only)</small>
                                                        </span>
                                                    </div>

                                                    <form method="post"
                                                          class="room-checkin-form"
                                                          data-rooming-id="<?php echo $rid; ?>"
                                                          data-max-occupants="<?php echo (int)$occupantLimit; ?>">
                                                        <input type="hidden" name="order_id" value="<?php echo (int)$order['id']; ?>">
                                                        <input type="hidden" name="rooming_id" value="<?php echo $rid; ?>">

                                                        <div class="occupants-wrap" id="occupants_wrap_<?php echo $rid; ?>">
                                                            <?php
                                                            if (!$occupants) {
                                                                $occupants = [
                                                                    [
                                                                        'first_name' => '',
                                                                        'last_name' => '',
                                                                        'id_type' => '',
                                                                        'id_number' => '',
                                                                        'nationality' => '',
                                                                        'gender' => '',
                                                                        'date_of_birth' => '',
                                                                        'phone' => '',
                                                                        'email' => '',
                                                                        'address' => '',
                                                                        'signature_data' => '',
                                                                        'registration_notes' => '',
                                                                        'is_primary' => 1
                                                                    ]
                                                                ];
                                                            }
                                                            foreach ($occupants as $i => $occ):
                                                            ?>
                                                                <div class="border rounded-3 p-3 mb-3 bg-light occupant-row">
                                                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                                                        <div class="fw-bold text-primary">
                                                                            <i class="bi bi-person-vcard me-2"></i>Guest Registration
                                                                        </div>
                                                                        <div class="form-check">
                                                                            <input class="form-check-input primary-radio"
                                                                                   type="radio"
                                                                                   name="primary_guest_index"
                                                                                   value="<?php echo $i; ?>"
                                                                                   <?php echo !empty($occ['is_primary']) ? 'checked' : ''; ?>>
                                                                            <label class="form-check-label">Primary guest</label>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row g-3">
                                                                        <div class="col-md-6">
                                                                            <label class="form-label">First Name</label>
                                                                            <input type="text"
                                                                                   name="occupant_first_name[]"
                                                                                   class="form-control"
                                                                                   value="<?php echo h($occ['first_name'] ?? ''); ?>">
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <label class="form-label">Last Name</label>
                                                                            <input type="text"
                                                                                   name="occupant_last_name[]"
                                                                                   class="form-control"
                                                                                   value="<?php echo h($occ['last_name'] ?? ''); ?>">
                                                                        </div>

                                                                        <div class="col-md-4">
                                                                            <label class="form-label">ID Type</label>
                                                                            <select name="occupant_id_type[]" class="form-select">
                                                                                <?php $idType = (string)($occ['id_type'] ?? ''); ?>
                                                                                <option value="" <?php echo $idType === '' ? 'selected' : ''; ?>>Select</option>
                                                                                <option value="National ID" <?php echo $idType === 'National ID' ? 'selected' : ''; ?>>National ID</option>
                                                                                <option value="Passport" <?php echo $idType === 'Passport' ? 'selected' : ''; ?>>Passport</option>
                                                                                <option value="Driver Licence" <?php echo $idType === 'Driver Licence' ? 'selected' : ''; ?>>Driver Licence</option>
                                                                                <option value="Other" <?php echo $idType === 'Other' ? 'selected' : ''; ?>>Other</option>
                                                                            </select>
                                                                        </div>
                                                                        <div class="col-md-4">
                                                                            <label class="form-label">ID / Passport No.</label>
                                                                            <input type="text"
                                                                                   name="occupant_id_number[]"
                                                                                   class="form-control"
                                                                                   value="<?php echo h($occ['id_number'] ?? ''); ?>">
                                                                        </div>
                                                                        <div class="col-md-4">
                                                                            <label class="form-label">Nationality</label>
                                                                            <?php $selectedNationality = (string)($occ['nationality'] ?? ''); ?>
                                                                            <select name="occupant_nationality[]" class="form-select">
                                                                                <option value="" <?php echo $selectedNationality === '' ? 'selected' : ''; ?>>Select nationality</option>
                                                                                <?php foreach ($nationalities as $nat): ?>
                                                                                    <?php $natName = (string)($nat['nationality'] ?? ''); ?>
                                                                                    <?php if ($natName === '') continue; ?>
                                                                                    <option value="<?php echo h($natName); ?>" <?php echo $selectedNationality === $natName ? 'selected' : ''; ?>><?php echo h($natName); ?></option>
                                                                                <?php endforeach; ?>
                                                                            </select>
                                                                        </div>

                                                                        <div class="col-md-4">
                                                                            <label class="form-label">Gender</label>
                                                                            <?php $gender = (string)($occ['gender'] ?? ''); ?>
                                                                            <select name="occupant_gender[]" class="form-select">
                                                                                <option value="" <?php echo $gender === '' ? 'selected' : ''; ?>>Select</option>
                                                                                <option value="Male" <?php echo $gender === 'Male' ? 'selected' : ''; ?>>Male</option>
                                                                                <option value="Female" <?php echo $gender === 'Female' ? 'selected' : ''; ?>>Female</option>
                                                                                <option value="Other" <?php echo $gender === 'Other' ? 'selected' : ''; ?>>Other</option>
                                                                            </select>
                                                                        </div>
                                                                        <div class="col-md-4">
                                                                            <label class="form-label">Date of Birth</label>
                                                                            <input type="date"
                                                                                   name="occupant_date_of_birth[]"
                                                                                   class="form-control"
                                                                                   value="<?php echo h($occ['date_of_birth'] ?? ''); ?>">
                                                                        </div>
                                                                        <div class="col-md-4">
                                                                            <label class="form-label">Phone</label>
                                                                            <input type="text"
                                                                                   name="occupant_phone[]"
                                                                                   class="form-control"
                                                                                   value="<?php echo h($occ['phone'] ?? ''); ?>">
                                                                        </div>

                                                                        <div class="col-md-6">
                                                                            <label class="form-label">Email</label>
                                                                            <input type="email"
                                                                                   name="occupant_email[]"
                                                                                   class="form-control"
                                                                                   value="<?php echo h($occ['email'] ?? ''); ?>">
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <label class="form-label">Address</label>
                                                                            <input type="text"
                                                                                   name="occupant_address[]"
                                                                                   class="form-control"
                                                                                   value="<?php echo h($occ['address'] ?? ''); ?>">
                                                                        </div>

                                                                        <div class="col-12">
                                                                            <label class="form-label">Registration Notes</label>
                                                                            <textarea name="occupant_registration_notes[]" class="form-control" rows="2"><?php echo h($occ['registration_notes'] ?? ''); ?></textarea>
                                                                        </div>

                                                                        <div class="col-12">
                                                                            <label class="form-label">Guest Signature</label>
                                                                            <input type="hidden" name="occupant_signature_data[]" class="signature-data" value="<?php echo h($occ['signature_data'] ?? ''); ?>">
                                                                            <canvas class="signature-pad" width="520" height="130"></canvas>
                                                                            <div class="d-flex gap-2 mt-2">
                                                                                <button type="button" class="btn btn-sm btn-outline-secondary btn-clear-signature">Clear Signature</button>
                                                                                <?php if (!empty($occ['signature_data'])): ?>
                                                                                    <span class="badge text-bg-success align-self-center">Signature saved</span>
                                                                                <?php endif; ?>
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-12 text-end">
                                                                            <button type="button" class="btn btn-sm btn-outline-danger btn-remove-occupant">
                                                                                <i class="bi bi-trash me-1"></i>Remove Guest
                                                                            </button>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            <?php endforeach; ?>
                                                        </div>

                                                        <div class="d-flex gap-2 mb-3">
                                                            <button type="button"
                                                                    class="btn btn-outline-secondary btn-add-occupant"
                                                                    data-target="#occupants_wrap_<?php echo $rid; ?>"
                                                                    data-max-occupants="<?php echo (int)$occupantLimit; ?>">
                                                                <i class="bi bi-plus-circle me-2"></i>Add Occupant
                                                            </button>
                                                            <div class="small text-muted align-self-center occupant-limit-text">
                                                                Max <?php echo (int)$occupantLimit; ?> occupant<?php echo $occupantLimit === 1 ? '' : 's'; ?> for this room.
                                                            </div>
                                                        </div>

                                                        <div class="d-grid">
                                                            <button type="submit" name="save_room_checkin" value="1" class="btn btn-primary">
                                                                <i class="bi bi-save me-2"></i>Save Room Check-In
                                                            </button>
                                                        </div>
                                                    </form>
                                                </div>

                                                <div class="col-lg-5">
                                                    <h6 class="mb-3">Room Folio</h6>

                                                    <div class="registration-actions mb-3">
                                                        <a href="/rooms/modules/reservations/guest_registration_pdf.php?order_id=<?php echo (int)$order['id']; ?>&rooming_id=<?php echo (int)$rid; ?>"
                                                           target="_blank"
                                                           class="btn btn-outline-primary w-100 mb-2">
                                                            <i class="bi bi-printer me-2"></i>Print This Room Registration
                                                        </a>
                                                        <a href="/rooms/modules/reservations/guest_registration_pdf.php?order_id=<?php echo (int)$order['id']; ?>&rooming_id=<?php echo (int)$rid; ?>&download=1"
                                                           class="btn btn-outline-secondary w-100">
                                                            <i class="bi bi-download me-2"></i>Download This Room PDF
                                                        </a>
                                                    </div>

                                                    <div class="folio-box mb-3">
                                                        <div class="folio-line"><span>Folio</span><strong><?php echo $roomFolio ? h($roomFolio['folio_no']) : 'Not created yet'; ?></strong></div>
                                                        <div class="folio-line"><span>Type</span><strong><?php echo $roomFolio ? strip_tags(folio_type_badge((string)$roomFolio['folio_type'])) : '—'; ?></strong></div>
                                                        <div class="folio-line"><span>Requested Type</span><strong><?php echo h((string)($room['room_type_title'] ?? 'Not set')); ?></strong></div>
                                                        <div class="folio-line"><span>Folio Name</span><strong><?php echo $roomFolio ? h($roomFolio['folio_name']) : 'Will be created from primary occupant'; ?></strong></div>
                                                        <div class="folio-line"><span>Charges</span><strong><?php echo money_fmt($roomFolio['total_charges'] ?? 0); ?></strong></div>
                                                        <div class="folio-line"><span>Payments</span><strong><?php echo money_fmt($roomFolio['total_payments'] ?? 0); ?></strong></div>
                                                        <div class="folio-line"><span>Balance</span><strong><?php echo money_fmt($roomFolio['balance'] ?? 0); ?></strong></div>
                                                    </div>

                                                    <?php if ($roomFolio): ?>
                                                        <div class="d-grid gap-2 mb-3">
                                                            <a href="/rooms/modules/payments/folio_view.php?folio_id=<?php echo (int)$roomFolio['id']; ?>" class="btn btn-outline-primary">
                                                                <i class="bi bi-receipt me-2"></i>Open Room Folio
                                                            </a>
                                                        </div>
                                                    <?php endif; ?>

                                                    <?php
                                                    $guestFoliosForRoom = [];
                                                    foreach ($bookingFolios as $gf) {
                                                        if ((string)($gf['folio_type'] ?? '') === 'guest' && (int)($gf['rooming_id'] ?? 0) === $rid) {
                                                            $guestFoliosForRoom[] = $gf;
                                                        }
                                                    }
                                                    ?>
                                                    <?php if ($guestFoliosForRoom): ?>
                                                        <h6 class="mb-2">Individual Guest Folios</h6>
                                                        <div class="list-group guest-folio-list">
                                                            <?php foreach ($guestFoliosForRoom as $gf): ?>
                                                                <a href="/rooms/modules/payments/folio_view.php?folio_id=<?php echo (int)$gf['id']; ?>"
                                                                   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                                                    <span>
                                                                        <strong><?php echo h($gf['occupant_name'] ?: $gf['folio_name']); ?></strong><br>
                                                                        <small class="text-muted"><?php echo h($gf['folio_no']); ?></small>
                                                                    </span>
                                                                    <span class="badge text-bg-light border text-dark"><?php echo money_fmt($gf['balance'] ?? 0); ?></span>
                                                                </a>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="alert alert-light border small mb-0">
                                                            Save this room check-in to create individual guest folios for POS/bar charges.
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($bookingFolios): ?>
                <div class="card panel-card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0">Booking Folio Summary</h5>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-modern align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>Folio</th>
                                        <th>Type</th>
                                        <th class="text-end">Charges</th>
                                        <th class="text-end">Payments</th>
                                        <th class="text-end">Balance</th>
                                        <th class="text-end">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($bookingFolios as $bf): ?>
                                        <tr>
                                            <td>
                                                <div class="data-stack">
                                                    <strong><?php echo h($bf['folio_no']); ?></strong>
                                                    <small><?php echo h($bf['folio_name']); ?></small>
                                                </div>
                                            </td>
                                            <td><?php echo folio_type_badge((string)$bf['folio_type']); ?></td>
                                            <td class="text-end"><?php echo money_fmt($bf['total_charges']); ?></td>
                                            <td class="text-end"><?php echo money_fmt($bf['total_payments']); ?></td>
                                            <td class="text-end"><?php echo money_fmt($bf['balance']); ?></td>
                                            <td class="text-end">
                                                <a href="/rooms/modules/payments/folio_view.php?folio_id=<?php echo (int)$bf['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                    Open
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

        </div>
    </div>

    <style>
        .form-section {
            height: auto !important;
            min-height: 0 !important;
            padding: 14px 16px !important;
            border-radius: 18px;
            background: #fff;
            border: 1px solid #eef2f7;
            box-shadow: 0 10px 28px rgba(15, 23, 42, 0.055);
        }

        .form-section-title {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 10px;
            font-size: 14px;
            font-weight: 800;
            color: #111827;
            letter-spacing: -0.01em;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 6px;
        }

        .mini-stat {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 7px 0;
            margin-bottom: 0 !important;
            border-bottom: 1px dashed #edf1f5;
            line-height: 1.25;
        }

        .summary-grid .mini-stat {
            padding: 7px 8px;
            border: 1px solid #f1f5f9;
            border-radius: 12px;
            background: #fbfdff;
        }

        .mini-stat:last-child {
            margin-bottom: 0 !important;
        }

        .mini-stat span {
            color: #6b7280;
            font-size: 12px;
            font-weight: 600;
            white-space: nowrap;
        }

        .mini-stat strong {
            font-size: 13px;
            font-weight: 800;
            color: #111827;
            text-align: right;
        }

        .soft-divider {
            height: 1px;
            background: linear-gradient(to right, transparent, #dfe5ec, transparent);
            margin: 9px 0;
        }

        .checkin-action-section {
            margin-top: 12px !important;
        }

        .checkin-action-section .text-muted.small,
        .checkin-action-section .registration-actions {
            margin-bottom: 10px !important;
        }

        @media (min-width: 1400px) {
            .booking-summary-card .summary-grid {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }

            .booking-summary-card .summary-wide {
                grid-column: 1 / -1;
            }
        }

        @media (min-width: 1200px) {
            .col-xl-4 > .form-section:first-child {
                position: sticky;
                top: 92px;
            }
        }

        .balance-zero {
            color: #16a34a !important;
        }

        .status-warning {
            color: #d97706 !important;
        }

        .folio-box{
            border:1px solid #e9ecef;
            border-radius:16px;
            padding:14px 16px;
            background:#fff;
        }
        .folio-line{
            display:flex;
            justify-content:space-between;
            gap:16px;
            padding:7px 0;
            border-bottom:1px dashed #eef2f7;
        }
        .folio-line:last-child{
            border-bottom:none;
        }
        .folio-line span{
            color:#6b7280;
        }
        .guest-folio-list .list-group-item{
            border-radius: 12px;
            margin-bottom: 8px;
            border: 1px solid #e5e7eb;
        }

        .signature-pad{
            width:100%;
            max-width:520px;
            height:130px;
            border:1px dashed #cbd5e1;
            border-radius:14px;
            background:#fff;
            touch-action:none;
            display:block;
        }
    </style>

    <script>
    var nationalityOptionsHtml = <?php echo json_encode($nationalityOptionsHtml, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    document.addEventListener('DOMContentLoaded', function () {
        function refreshPrimaryIndexes(form) {
            var rows = form.querySelectorAll('.occupant-row');
            rows.forEach(function (row, index) {
                var radio = row.querySelector('.primary-radio');
                if (radio) {
                    radio.value = index;
                }
            });

            var checked = form.querySelector('.primary-radio:checked');
            if (!checked) {
                var firstRadio = form.querySelector('.primary-radio');
                if (firstRadio) {
                    firstRadio.checked = true;
                }
            }

            refreshOccupantLimitState(form);
        }

        function getMaxOccupants(form) {
            var max = parseInt(form.getAttribute('data-max-occupants') || '0', 10);
            return max > 0 ? max : 999;
        }

        function refreshOccupantLimitState(form) {
            var max = getMaxOccupants(form);
            var count = form.querySelectorAll('.occupant-row').length;
            var addBtn = form.querySelector('.btn-add-occupant');
            var limitText = form.querySelector('.occupant-limit-text');

            if (addBtn) {
                addBtn.disabled = count >= max;
                addBtn.classList.toggle('disabled', count >= max);
                addBtn.title = count >= max
                    ? 'Maximum occupants reached for this room. Kids 0-3 no charge are excluded.'
                    : '';
            }

            if (limitText) {
                limitText.textContent = count + ' of ' + max + ' occupants captured. Kids 0-3 no charge are excluded.';
                limitText.classList.toggle('text-danger', count > max);
            }
        }

        function setupSignaturePad(canvas) {
            if (!canvas || canvas.dataset.ready === '1') return;
            canvas.dataset.ready = '1';

            var row = canvas.closest('.occupant-row');
            var input = row ? row.querySelector('.signature-data') : null;
            var ctx = canvas.getContext('2d');
            var drawing = false;
            var hasDrawn = false;

            function resizeCanvas() {
                var rect = canvas.getBoundingClientRect();
                var ratio = window.devicePixelRatio || 1;
                var currentValue = input ? input.value : '';
                canvas.width = Math.max(320, Math.floor(rect.width * ratio));
                canvas.height = Math.floor(130 * ratio);
                ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
                ctx.lineWidth = 2;
                ctx.lineCap = 'round';
                ctx.strokeStyle = '#111827';

                if (currentValue) {
                    var img = new Image();
                    img.onload = function () {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        ctx.drawImage(img, 0, 0, rect.width, 130);
                    };
                    img.src = currentValue;
                }
            }

            function point(e) {
                var rect = canvas.getBoundingClientRect();
                var t = e.touches && e.touches.length ? e.touches[0] : e;
                return { x: t.clientX - rect.left, y: t.clientY - rect.top };
            }

            function start(e) {
                e.preventDefault();
                drawing = true;
                var p = point(e);
                ctx.beginPath();
                ctx.moveTo(p.x, p.y);
            }

            function move(e) {
                if (!drawing) return;
                e.preventDefault();
                var p = point(e);
                ctx.lineTo(p.x, p.y);
                ctx.stroke();
                hasDrawn = true;
            }

            function end() {
                if (!drawing) return;
                drawing = false;
                if (input && hasDrawn) {
                    input.value = canvas.toDataURL('image/png');
                }
            }

            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);
            canvas.addEventListener('mousedown', start);
            canvas.addEventListener('mousemove', move);
            canvas.addEventListener('mouseup', end);
            canvas.addEventListener('mouseleave', end);
            canvas.addEventListener('touchstart', start, { passive:false });
            canvas.addEventListener('touchmove', move, { passive:false });
            canvas.addEventListener('touchend', end);
        }

        function setupSignaturePads(scope) {
            (scope || document).querySelectorAll('.signature-pad').forEach(setupSignaturePad);
        }

        setupSignaturePads(document);

        document.querySelectorAll('.room-checkin-form').forEach(function (form) {
            refreshPrimaryIndexes(form);

            form.addEventListener('submit', function (e) {
                var maxOccupants = getMaxOccupants(form);
                var currentCount = form.querySelectorAll('.occupant-row').length;
                if (currentCount > maxOccupants) {
                    e.preventDefault();
                    alert('This room allows only ' + maxOccupants + ' registered occupant' + (maxOccupants === 1 ? '' : 's') + ' based on adults plus children. Kids 0-3 no charge are excluded.');
                    return false;
                }

                form.querySelectorAll('.signature-pad').forEach(function (canvas) {
                    var row = canvas.closest('.occupant-row');
                    var input = row ? row.querySelector('.signature-data') : null;
                    if (input && !input.value) {
                        try { input.value = canvas.toDataURL('image/png'); } catch (e) {}
                    }
                });
            });

            form.addEventListener('click', function (e) {
                if (e.target.closest('.btn-add-occupant')) {
                    var btn = e.target.closest('.btn-add-occupant');
                    var targetSel = btn.getAttribute('data-target');
                    var wrap = document.querySelector(targetSel);
                    if (!wrap) return;

                    var rowCount = wrap.querySelectorAll('.occupant-row').length;
                    var maxOccupants = getMaxOccupants(form);
                    if (rowCount >= maxOccupants) {
                        alert('This room allows only ' + maxOccupants + ' registered occupant' + (maxOccupants === 1 ? '' : 's') + ' based on adults plus children. Kids 0-3 no charge are excluded.');
                        refreshOccupantLimitState(form);
                        return;
                    }

                    var row = document.createElement('div');
                    row.className = 'border rounded-3 p-3 mb-3 bg-light occupant-row';
                    row.innerHTML = ''
                        + '<div class="d-flex justify-content-between align-items-center mb-3">'
                        + '  <div class="fw-bold text-primary"><i class="bi bi-person-vcard me-2"></i>Guest Registration</div>'
                        + '  <div class="form-check">'
                        + '    <input class="form-check-input primary-radio" type="radio" name="primary_guest_index" value="' + rowCount + '">'
                        + '    <label class="form-check-label">Primary guest</label>'
                        + '  </div>'
                        + '</div>'
                        + '<div class="row g-3">'
                        + '  <div class="col-md-6"><label class="form-label">First Name</label><input type="text" name="occupant_first_name[]" class="form-control" value=""></div>'
                        + '  <div class="col-md-6"><label class="form-label">Last Name</label><input type="text" name="occupant_last_name[]" class="form-control" value=""></div>'
                        + '  <div class="col-md-4"><label class="form-label">ID Type</label><select name="occupant_id_type[]" class="form-select"><option value="">Select</option><option value="National ID">National ID</option><option value="Passport">Passport</option><option value="Driver Licence">Driver Licence</option><option value="Other">Other</option></select></div>'
                        + '  <div class="col-md-4"><label class="form-label">ID / Passport No.</label><input type="text" name="occupant_id_number[]" class="form-control" value=""></div>'
                        + '  <div class="col-md-4"><label class="form-label">Nationality</label><select name="occupant_nationality[]" class="form-select">' + nationalityOptionsHtml + '</select></div>'
                        + '  <div class="col-md-4"><label class="form-label">Gender</label><select name="occupant_gender[]" class="form-select"><option value="">Select</option><option value="Male">Male</option><option value="Female">Female</option><option value="Other">Other</option></select></div>'
                        + '  <div class="col-md-4"><label class="form-label">Date of Birth</label><input type="date" name="occupant_date_of_birth[]" class="form-control" value=""></div>'
                        + '  <div class="col-md-4"><label class="form-label">Phone</label><input type="text" name="occupant_phone[]" class="form-control" value=""></div>'
                        + '  <div class="col-md-6"><label class="form-label">Email</label><input type="email" name="occupant_email[]" class="form-control" value=""></div>'
                        + '  <div class="col-md-6"><label class="form-label">Address</label><input type="text" name="occupant_address[]" class="form-control" value=""></div>'
                        + '  <div class="col-12"><label class="form-label">Registration Notes</label><textarea name="occupant_registration_notes[]" class="form-control" rows="2"></textarea></div>'
                        + '  <div class="col-12"><label class="form-label">Guest Signature</label><input type="hidden" name="occupant_signature_data[]" class="signature-data" value=""><canvas class="signature-pad" width="520" height="130"></canvas><div class="d-flex gap-2 mt-2"><button type="button" class="btn btn-sm btn-outline-secondary btn-clear-signature">Clear Signature</button></div></div>'
                        + '  <div class="col-12 text-end"><button type="button" class="btn btn-sm btn-outline-danger btn-remove-occupant"><i class="bi bi-trash me-1"></i>Remove Guest</button></div>'
                        + '</div>';

                    wrap.appendChild(row);
                    refreshPrimaryIndexes(form);
                    setupSignaturePads(row);
                }

                if (e.target.closest('.btn-clear-signature')) {
                    var sigRow = e.target.closest('.occupant-row');
                    if (sigRow) {
                        var canvas = sigRow.querySelector('.signature-pad');
                        var input = sigRow.querySelector('.signature-data');
                        if (canvas) {
                            var ctx = canvas.getContext('2d');
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                        }
                        if (input) input.value = '';
                    }
                }

                if (e.target.closest('.btn-remove-occupant')) {
                    var removeBtn = e.target.closest('.btn-remove-occupant');
                    var wrap = removeBtn.closest('.occupants-wrap');
                    var rows = wrap.querySelectorAll('.occupant-row');

                    if (rows.length <= 1) {
                        rows[0].querySelectorAll('input[type="text"], input[type="email"], input[type="date"], input[type="hidden"], textarea').forEach(function (el) {
                            el.value = '';
                        });
                        rows[0].querySelectorAll('select').forEach(function (el) {
                            el.selectedIndex = 0;
                        });
                        rows[0].querySelectorAll('.signature-pad').forEach(function (canvas) {
                            var ctx = canvas.getContext('2d');
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                        });
                        var radio = rows[0].querySelector('.primary-radio');
                        if (radio) radio.checked = true;
                    } else {
                        removeBtn.closest('.occupant-row').remove();
                    }

                    refreshPrimaryIndexes(form);
                }
            });
        });
    });
    </script>
<?php endif; ?>

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