<?php
// preload_tomorrow_guest_names.php
// Place in /rooms/modules/reservations/
// Preloads room-limited guest names into order_rooming_guests for tomorrow arrivals.

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

$pageTitle = 'Preload Check-In Details';

function ptg_e($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function ptg_table_exists(PDO $pdo, string $table): bool {
    static $cache = [];
    if (array_key_exists($table, $cache)) return $cache[$table];
    try {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $s->execute([':t'=>$table]);
        return $cache[$table] = ((int)$s->fetchColumn() > 0);
    } catch (Throwable $e) { return $cache[$table] = false; }
}

function ptg_column_exists(PDO $pdo, string $table, string $column): bool {
    static $cache = [];
    $key = $table.'.'.$column;
    if (array_key_exists($key, $cache)) return $cache[$key];
    try {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
        $s->execute([':t'=>$table, ':c'=>$column]);
        return $cache[$key] = ((int)$s->fetchColumn() > 0);
    } catch (Throwable $e) { return $cache[$key] = false; }
}

function ptg_add_col(PDO $pdo, string $table, string $column, string $ddl): void {
    if (!ptg_column_exists($pdo, $table, $column)) {
        try { $pdo->exec($ddl); } catch (Throwable $e) {}
    }
}

function ptg_link_col(PDO $pdo): string {
    if (ptg_column_exists($pdo, 'order_rooming_guests', 'rooming_id')) return 'rooming_id';
    if (ptg_column_exists($pdo, 'order_rooming_guests', 'order_rooming_id')) return 'order_rooming_id';
    return 'rooming_id';
}

function ptg_ensure_schema(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS order_rooming_guests (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        order_id BIGINT UNSIGNED NULL,
        rooming_id BIGINT UNSIGNED NULL,
        first_name VARCHAR(120) NULL,
        last_name VARCHAR(120) NULL,
        is_primary TINYINT(1) NOT NULL DEFAULT 0,
        checked_in_at DATETIME NULL,
        checked_out_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_org_rooming(rooming_id),
        INDEX idx_org_order(order_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    ptg_add_col($pdo, 'order_rooming_guests', 'order_id', "ALTER TABLE order_rooming_guests ADD COLUMN order_id BIGINT UNSIGNED NULL AFTER id");
    if (!ptg_column_exists($pdo, 'order_rooming_guests', 'rooming_id') && !ptg_column_exists($pdo, 'order_rooming_guests', 'order_rooming_id')) {
        ptg_add_col($pdo, 'order_rooming_guests', 'rooming_id', "ALTER TABLE order_rooming_guests ADD COLUMN rooming_id BIGINT UNSIGNED NULL AFTER order_id");
    }
    if (!ptg_column_exists($pdo, 'order_rooming_guests', 'first_name') && !ptg_column_exists($pdo, 'order_rooming_guests', 'firstname')) {
        ptg_add_col($pdo, 'order_rooming_guests', 'first_name', "ALTER TABLE order_rooming_guests ADD COLUMN first_name VARCHAR(120) NULL");
    }
    if (!ptg_column_exists($pdo, 'order_rooming_guests', 'last_name') && !ptg_column_exists($pdo, 'order_rooming_guests', 'lastname')) {
        ptg_add_col($pdo, 'order_rooming_guests', 'last_name', "ALTER TABLE order_rooming_guests ADD COLUMN last_name VARCHAR(120) NULL");
    }
    ptg_add_col($pdo, 'order_rooming_guests', 'is_primary', "ALTER TABLE order_rooming_guests ADD COLUMN is_primary TINYINT(1) NOT NULL DEFAULT 0");

    ptg_add_col($pdo, 'order_rooming_guests', 'id_type', "ALTER TABLE order_rooming_guests ADD COLUMN id_type VARCHAR(60) NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'id_number', "ALTER TABLE order_rooming_guests ADD COLUMN id_number VARCHAR(120) NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'nationality', "ALTER TABLE order_rooming_guests ADD COLUMN nationality VARCHAR(120) NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'gender', "ALTER TABLE order_rooming_guests ADD COLUMN gender VARCHAR(30) NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'date_of_birth', "ALTER TABLE order_rooming_guests ADD COLUMN date_of_birth DATE NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'phone', "ALTER TABLE order_rooming_guests ADD COLUMN phone VARCHAR(80) NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'email', "ALTER TABLE order_rooming_guests ADD COLUMN email VARCHAR(180) NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'address', "ALTER TABLE order_rooming_guests ADD COLUMN address TEXT NULL");
    ptg_add_col($pdo, 'order_rooming_guests', 'registration_notes', "ALTER TABLE order_rooming_guests ADD COLUMN registration_notes TEXT NULL");

    if (ptg_table_exists($pdo, 'order_rooming')) {
        ptg_add_col($pdo, 'order_rooming', 'bed_configuration', "ALTER TABLE order_rooming ADD COLUMN bed_configuration VARCHAR(80) NULL");
        ptg_add_col($pdo, 'order_rooming', 'special_room_request', "ALTER TABLE order_rooming ADD COLUMN special_room_request TEXT NULL");
    }
}

function ptg_date($v, string $format='d M Y'): string {
    if (!$v) return '';
    $ts = strtotime((string)$v);
    return $ts ? date($format, $ts) : (string)$v;
}

function ptg_properties(PDO $pdo): array {
    if (!ptg_table_exists($pdo,'properties')) return [];
    try {
        return $pdo->query("SELECT id,name,code FROM properties WHERE COALESCE(is_active,1)=1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) { return []; }
}


function ptg_nationalities(PDO $pdo): array {
    if (!ptg_table_exists($pdo, 'nationality')) return [];
    try {
        return $pdo->query("SELECT nationality FROM nationality ORDER BY nationality ASC")->fetchAll(PDO::FETCH_COLUMN) ?: [];
    } catch (Throwable $e) { return []; }
}

function ptg_rooming_note_cols(PDO $pdo): array {
    return [
        'bed_configuration' => ptg_column_exists($pdo, 'order_rooming', 'bed_configuration') ? 'bed_configuration' : null,
        'special_room_request' => ptg_column_exists($pdo, 'order_rooming', 'special_room_request') ? 'special_room_request' : (ptg_column_exists($pdo, 'order_rooming', 'notes') ? 'notes' : null),
    ];
}

function ptg_fetch_arrivals(PDO $pdo, int $propertyId, string $date): array {
    if (!ptg_table_exists($pdo,'orders') || !ptg_table_exists($pdo,'order_rooming')) {
        throw new RuntimeException('orders and order_rooming tables are required.');
    }

    $guestSql = "''";
    if (ptg_table_exists($pdo,'guests') && ptg_column_exists($pdo,'orders','guest_id')) {
        if (ptg_column_exists($pdo,'guests','firstname') && ptg_column_exists($pdo,'guests','lastname')) {
            $guestSql = "(SELECT TRIM(CONCAT(COALESCE(g.firstname,''),' ',COALESCE(g.lastname,''))) FROM guests g WHERE g.id=o.guest_id LIMIT 1)";
        } elseif (ptg_column_exists($pdo,'guests','first_name') && ptg_column_exists($pdo,'guests','last_name')) {
            $guestSql = "(SELECT TRIM(CONCAT(COALESCE(g.first_name,''),' ',COALESCE(g.last_name,''))) FROM guests g WHERE g.id=o.guest_id LIMIT 1)";
        }
    }

    $roomJoin = ptg_table_exists($pdo,'rooms') ? "LEFT JOIN rooms rm ON rm.id=rmg.room_id" : "";
    $roomSql  = ptg_table_exists($pdo,'rooms') ? "COALESCE(rm.room_no,rmg.room_no)" : "rmg.room_no";
    $rtJoin   = ptg_table_exists($pdo,'room_types') ? "LEFT JOIN room_types rt ON rt.id=rmg.room_type_id" : "";
    $rtSql    = ptg_table_exists($pdo,'room_types') ? "COALESCE(rt.title,'')" : "''";

    $propJoin = "";
    $propSql  = "'' AS property_name, '' AS property_code";
    if (ptg_table_exists($pdo,'properties') && ptg_column_exists($pdo,'orders','property_id')) {
        $propJoin = "LEFT JOIN properties p ON p.id=o.property_id";
        $propSql = "p.name AS property_name, p.code AS property_code";
    }

    $orderNo = ptg_column_exists($pdo,'orders','order_no') ? "o.order_no" : "CAST(o.id AS CHAR)";
    $checkedIn = ptg_column_exists($pdo,'order_rooming','checked_in_status') ? "COALESCE(rmg.checked_in_status,0)" : "0";
    $checkedOut = ptg_column_exists($pdo,'order_rooming','checked_out_status') ? "COALESCE(rmg.checked_out_status,0)" : "0";

    $where = "WHERE rmg.check_in=:date AND {$checkedIn}=0 AND {$checkedOut}=0";
    $params = [':date'=>$date];

    if (ptg_column_exists($pdo,'orders','status')) {
        $where .= " AND LOWER(TRIM(CAST(o.status AS CHAR))) NOT IN ('0','cancelled','canceled','void','deleted','no_show','noshow','4','checked_out','checkout','completed')";
    }
    if ($propertyId > 0 && ptg_column_exists($pdo,'orders','property_id')) {
        $where .= " AND o.property_id=:property_id";
        $params[':property_id'] = $propertyId;
    }

    $sql = "SELECT o.id AS order_id, {$orderNo} AS order_no, {$guestSql} AS lead_guest_name,
                   {$propSql}, rmg.id AS rooming_id, rmg.check_in, rmg.check_out,
                   {$roomSql} AS room_no, {$rtSql} AS room_type,
                   COALESCE(rmg.adults,0) AS adults, COALESCE(rmg.children,0) AS children,
                   " . (ptg_column_exists($pdo,'order_rooming','bed_configuration') ? "COALESCE(rmg.bed_configuration,'')" : "''") . " AS bed_configuration,
                   " . (ptg_column_exists($pdo,'order_rooming','special_room_request') ? "COALESCE(rmg.special_room_request,'')" : (ptg_column_exists($pdo,'order_rooming','notes') ? "COALESCE(rmg.notes,'')" : "''")) . " AS special_room_request
            FROM order_rooming rmg
            INNER JOIN orders o ON o.id=rmg.order_id
            {$roomJoin}
            {$rtJoin}
            {$propJoin}
            {$where}
            ORDER BY property_name ASC, CAST({$roomSql} AS UNSIGNED) ASC, {$roomSql} ASC, lead_guest_name ASC, o.id ASC, rmg.id ASC";

    $s = $pdo->prepare($sql);
    $s->execute($params);
    return $s->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

function ptg_fetch_guests(PDO $pdo, array $roomingIds): array {
    if (!$roomingIds || !ptg_table_exists($pdo,'order_rooming_guests')) return [];
    $link = ptg_link_col($pdo);
    $firstCol = ptg_column_exists($pdo,'order_rooming_guests','first_name') ? 'first_name' : 'firstname';
    $lastCol  = ptg_column_exists($pdo,'order_rooming_guests','last_name') ? 'last_name' : 'lastname';
    $ph = implode(',', array_fill(0, count($roomingIds), '?'));

    $optionalCols = [];
    foreach (['id_type','id_number','nationality','gender','date_of_birth','phone','email','address','registration_notes'] as $c) {
        $optionalCols[] = ptg_column_exists($pdo, 'order_rooming_guests', $c) ? "COALESCE(`{$c}`,'') AS {$c}" : "'' AS {$c}";
    }

    $s = $pdo->prepare("SELECT id, `{$link}` AS rooming_id, COALESCE(`{$firstCol}`,'') AS first_name, COALESCE(`{$lastCol}`,'') AS last_name, COALESCE(is_primary,0) AS is_primary, " . implode(',', $optionalCols) . "
                        FROM order_rooming_guests
                        WHERE `{$link}` IN ($ph)
                        ORDER BY `{$link}` ASC, is_primary DESC, id ASC");
    $s->execute(array_values($roomingIds));

    $out = [];
    foreach ($s->fetchAll(PDO::FETCH_ASSOC) ?: [] as $r) {
        $rid = (int)$r['rooming_id'];
        $out[$rid][] = $r;
    }
    return $out;
}

function ptg_split_name(string $name): array {
    $name = trim($name);
    if ($name === '') return ['', ''];
    $parts = preg_split('/\s+/', $name);
    $first = array_shift($parts);
    return [$first, trim(implode(' ', $parts))];
}

function ptg_save_slot(PDO $pdo, int $orderId, int $roomingId, int $existingId, int $slot, array $guest): void {
    $name = trim((string)($guest['name'] ?? ''));
    [$first, $last] = ptg_split_name($name);
    $link = ptg_link_col($pdo);
    $firstCol = ptg_column_exists($pdo,'order_rooming_guests','first_name') ? 'first_name' : 'firstname';
    $lastCol  = ptg_column_exists($pdo,'order_rooming_guests','last_name') ? 'last_name' : 'lastname';
    $primary = $slot === 1 ? 1 : 0;

    $optional = [
        'id_type' => trim((string)($guest['id_type'] ?? '')),
        'id_number' => trim((string)($guest['id_number'] ?? '')),
        'nationality' => trim((string)($guest['nationality'] ?? '')),
        'gender' => trim((string)($guest['gender'] ?? '')),
        'date_of_birth' => trim((string)($guest['date_of_birth'] ?? '')),
        'phone' => trim((string)($guest['phone'] ?? '')),
        'email' => trim((string)($guest['email'] ?? '')),
        'address' => trim((string)($guest['address'] ?? '')),
        'registration_notes' => trim((string)($guest['registration_notes'] ?? '')),
    ];

    if ($optional['date_of_birth'] !== '' && strtotime($optional['date_of_birth']) === false) $optional['date_of_birth'] = '';

    $hasAnyDetail = ($name !== '');
    foreach ($optional as $v) { if (trim((string)$v) !== '') { $hasAnyDetail = true; break; } }

    if ($existingId > 0) {
        if (!$hasAnyDetail) {
            $pdo->prepare("DELETE FROM order_rooming_guests WHERE id=:id")->execute([':id'=>$existingId]);
            return;
        }

        $sets = ["`{$firstCol}`=:first", "`{$lastCol}`=:last", "is_primary=:primary"];
        $params = [':first'=>$first, ':last'=>$last, ':primary'=>$primary, ':id'=>$existingId];

        if (ptg_column_exists($pdo,'order_rooming_guests','order_id')) {
            $sets[] = "order_id=:order_id";
            $params[':order_id'] = $orderId;
        }

        foreach ($optional as $col => $value) {
            if (ptg_column_exists($pdo, 'order_rooming_guests', $col)) {
                $sets[] = "`{$col}`=:{$col}";
                $params[":{$col}"] = $value !== '' ? $value : null;
            }
        }

        $pdo->prepare("UPDATE order_rooming_guests SET ".implode(',',$sets)." WHERE id=:id")->execute($params);
        return;
    }

    if (!$hasAnyDetail) return;

    $cols = [$link, $firstCol, $lastCol, 'is_primary'];
    $vals = [':rooming_id', ':first', ':last', ':primary'];
    $params = [':rooming_id'=>$roomingId, ':first'=>$first, ':last'=>$last, ':primary'=>$primary];

    if (ptg_column_exists($pdo,'order_rooming_guests','order_id')) {
        array_unshift($cols, 'order_id');
        array_unshift($vals, ':order_id');
        $params[':order_id'] = $orderId;
    }

    foreach ($optional as $col => $value) {
        if (ptg_column_exists($pdo, 'order_rooming_guests', $col)) {
            $cols[] = $col;
            $vals[] = ":{$col}";
            $params[":{$col}"] = $value !== '' ? $value : null;
        }
    }

    $sql = "INSERT INTO order_rooming_guests (`".implode('`,`',$cols)."`) VALUES (".implode(',',$vals).")";
    $pdo->prepare($sql)->execute($params);
}

function ptg_save_room_config(PDO $pdo, int $roomingId, string $bedConfig, string $specialRequest): void {
    if ($roomingId <= 0 || !ptg_table_exists($pdo, 'order_rooming')) return;

    $cols = ptg_rooming_note_cols($pdo);
    $sets = [];
    $params = [':rooming_id' => $roomingId];

    if ($cols['bed_configuration']) {
        $sets[] = "`{$cols['bed_configuration']}` = :bed_configuration";
        $params[':bed_configuration'] = trim($bedConfig) !== '' ? trim($bedConfig) : null;
    }

    if ($cols['special_room_request']) {
        $sets[] = "`{$cols['special_room_request']}` = :special_room_request";
        $params[':special_room_request'] = trim($specialRequest) !== '' ? trim($specialRequest) : null;
    }

    if (!$sets) return;
    $pdo->prepare("UPDATE order_rooming SET ".implode(', ', $sets)." WHERE id=:rooming_id")->execute($params);
}

$errors = [];
$success = '';

try { ptg_ensure_schema($pdo); } catch (Throwable $e) { $errors[] = $e->getMessage(); }

$properties = ptg_properties($pdo);
$nationalities = ptg_nationalities($pdo);
$tomorrow = date('Y-m-d', strtotime('+1 day'));
$arrivalDate = trim((string)($_GET['date'] ?? $_POST['date'] ?? $tomorrow));
$arrivalDate = strtotime($arrivalDate) ? date('Y-m-d', strtotime($arrivalDate)) : $tomorrow;
$propertyId = (int)($_GET['property_id'] ?? $_POST['property_id'] ?? 0);
if ($propertyId <= 0 && count($properties) === 1) $propertyId = (int)$properties[0]['id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_guest_names'])) {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $roomingIds = $_POST['rooming_id'] ?? [];
        $orderIds = $_POST['order_id'] ?? [];
        $guestIds = $_POST['guest_id'] ?? [];
        $guestNames = $_POST['guest_name'] ?? [];
        $guestIdTypes = $_POST['guest_id_type'] ?? [];
        $guestIdNumbers = $_POST['guest_id_number'] ?? [];
        $guestNationalities = $_POST['guest_nationality'] ?? [];
        $guestGenders = $_POST['guest_gender'] ?? [];
        $guestDobs = $_POST['guest_date_of_birth'] ?? [];
        $guestPhones = $_POST['guest_phone'] ?? [];
        $guestEmails = $_POST['guest_email'] ?? [];
        $guestAddresses = $_POST['guest_address'] ?? [];
        $guestNotes = $_POST['guest_registration_notes'] ?? [];
        $bedConfigurations = $_POST['bed_configuration'] ?? [];
        $specialRoomRequests = $_POST['special_room_request'] ?? [];
        $roomLimits = $_POST['room_limit'] ?? [];

        $pdo->beginTransaction();
        foreach ($roomingIds as $ridRaw) {
            $rid = (int)$ridRaw;
            $oid = (int)($orderIds[$rid] ?? 0);
            if ($rid <= 0 || $oid <= 0) continue;

            ptg_save_room_config(
                $pdo,
                $rid,
                (string)($bedConfigurations[$rid] ?? ''),
                (string)($specialRoomRequests[$rid] ?? '')
            );

            /*
               Match normal checkin.php:
               occupant limit per room = Adults + Children.
               Kids 0-3 no charge are intentionally excluded.
            */
            $roomOccupantLimit = max(1, (int)($roomLimits[$rid] ?? 1));

            for ($slot=1; $slot<=$roomOccupantLimit; $slot++) {
                ptg_save_slot(
                    $pdo,
                    $oid,
                    $rid,
                    (int)($guestIds[$rid][$slot] ?? 0),
                    $slot,
                    [
                        'name' => (string)($guestNames[$rid][$slot] ?? ''),
                        'id_type' => (string)($guestIdTypes[$rid][$slot] ?? ''),
                        'id_number' => (string)($guestIdNumbers[$rid][$slot] ?? ''),
                        'nationality' => (string)($guestNationalities[$rid][$slot] ?? ''),
                        'gender' => (string)($guestGenders[$rid][$slot] ?? ''),
                        'date_of_birth' => (string)($guestDobs[$rid][$slot] ?? ''),
                        'phone' => (string)($guestPhones[$rid][$slot] ?? ''),
                        'email' => (string)($guestEmails[$rid][$slot] ?? ''),
                        'address' => (string)($guestAddresses[$rid][$slot] ?? ''),
                        'registration_notes' => (string)($guestNotes[$rid][$slot] ?? ''),
                    ]
                );
            }

            // Remove stale guests above the current room limit if the room pax was reduced.
            for ($slot=$roomOccupantLimit + 1; $slot<=8; $slot++) {
                $extraId = (int)($guestIds[$rid][$slot] ?? 0);
                if ($extraId > 0) {
                    $pdo->prepare("DELETE FROM order_rooming_guests WHERE id=:id")->execute([':id'=>$extraId]);
                }
            }
        }
        $pdo->commit();

        header('Location: preload_tomorrow_guest_names.php?' . http_build_query([
            'date'=>$arrivalDate,
            'property_id'=>$propertyId,
            'saved'=>1
        ]));
        exit;
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Pre-check-in details saved successfully.';
}

$rows = [];
$guestMap = [];
try {
    $rows = ptg_fetch_arrivals($pdo, $propertyId, $arrivalDate);
    $guestMap = ptg_fetch_guests($pdo, array_map(static fn($r)=>(int)$r['rooming_id'], $rows));
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

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

<div class="hero-band mb-3" style="padding:12px 16px!important;border-radius:16px;">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
            <div class="page-eyebrow text-white-50"><i class="bi bi-people"></i> Daily Reports</div>
            <div class="hero-title" style="font-size:1.2rem;">Preload Check-In Details</div>
            <div class="hero-subtitle" style="font-size:.82rem;">Enter guest details and special room requests before arrival.</div>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="front_office_daily_reports.php<?php echo $propertyId > 0 ? '?property_id='.(int)$propertyId : ''; ?>" class="btn btn-sm btn-outline-light">
                <i class="bi bi-arrow-left me-1"></i>Daily Reports
            </a>
            <a href="bulk_guest_registration_tomorrow.php?<?php echo http_build_query(['property_id'=>$propertyId,'date'=>$arrivalDate]); ?>" class="btn btn-sm btn-light">
                <i class="bi bi-printer me-1"></i>Bulk Guest Reg
            </a>
        </div>
    </div>
</div>

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

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <strong>Please fix:</strong>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?><li><?php echo ptg_e($err); ?></li><?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card panel-card mb-3">
    <div class="card-body">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label">Arrival Date</label>
                <input type="date" name="date" class="form-control form-control-sm" value="<?php echo ptg_e($arrivalDate); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">Property</label>
                <select name="property_id" class="form-select form-select-sm">
                    <option value="0">All properties</option>
                    <?php foreach ($properties as $p): ?>
                        <option value="<?php echo (int)$p['id']; ?>" <?php echo $propertyId === (int)$p['id'] ? 'selected' : ''; ?>>
                            <?php echo ptg_e($p['name']); ?><?php echo !empty($p['code']) ? ' - '.ptg_e($p['code']) : ''; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-5 d-flex gap-2">
                <button class="btn btn-sm btn-primary"><i class="bi bi-search me-1"></i>Load Arrivals</button>
                <a class="btn btn-sm btn-outline-secondary" href="preload_tomorrow_guest_names.php?<?php echo http_build_query(['date'=>$tomorrow,'property_id'=>$propertyId]); ?>">Tomorrow</a>
            </div>
        </form>
    </div>
</div>

<form method="post">
    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
    <input type="hidden" name="date" value="<?php echo ptg_e($arrivalDate); ?>">
    <input type="hidden" name="property_id" value="<?php echo (int)$propertyId; ?>">

    <div class="card panel-card">
        <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <h5 class="mb-0">Arrivals for <?php echo ptg_e(ptg_date($arrivalDate)); ?></h5>
                <small class="text-muted"><?php echo count($rows); ?> rooming record<?php echo count($rows) === 1 ? '' : 's'; ?> ready for pre-check-in.</small>
            </div>
            <?php if ($rows): ?>
                <button type="submit" name="save_guest_names" value="1" class="btn btn-sm btn-success">
                    <i class="bi bi-save me-1"></i>Save Pre-Check-In Details
                </button>
            <?php endif; ?>
        </div>

        <div class="card-body p-0">
            <div class="precheckin-toolbar p-3 border-bottom d-flex flex-wrap gap-2 align-items-center justify-content-between">
                <div class="small text-muted">
                    Smart mode: only one room opens at a time. Capture room request and guest details, then move to the next room.
                </div>
                <div class="d-flex flex-wrap gap-2">
                    <button type="button" class="btn btn-sm btn-outline-primary" id="openFirstIncomplete">
                        <i class="bi bi-magic me-1"></i>Open First Incomplete
                    </button>
                    <button type="submit" name="save_guest_names" value="1" class="btn btn-sm btn-success">
                        <i class="bi bi-save me-1"></i>Save All Details
                    </button>
                </div>
            </div>

            <div class="accordion precheckin-accordion p-3" id="precheckinAccordion">
                <?php if (!$rows): ?>
                    <div class="text-center text-muted py-4">No unchecked-in arrivals found for this date.</div>
                <?php else: ?>
                    <?php foreach ($rows as $rowIndex => $r): ?>
                        <?php
                        $rid = (int)$r['rooming_id'];
                        $existing = $guestMap[$rid] ?? [];
                        $slots = [];
                        $filledCount = 0;
                        $adults = (int)($r['adults'] ?? 0);
                        $children = (int)($r['children'] ?? 0);

                        /*
                           Same as normal checkin.php:
                           room occupant limit = adults + children.
                           Kids 0-3 no charge are excluded from this registration limit.
                        */
                        $occupantLimit = max(1, $adults + $children);
                        $expected = $occupantLimit;

                        for ($i=1; $i<=$occupantLimit; $i++) {
                            $g = $existing[$i-1] ?? [];
                            $name = trim((string)($g['first_name'] ?? '') . ' ' . (string)($g['last_name'] ?? ''));
                            if ($i === 1 && $name === '' && !empty($r['lead_guest_name'])) $name = (string)$r['lead_guest_name'];
                            if ($name !== '') $filledCount++;
                            $slots[$i] = [
                                'id'=>(int)($g['id'] ?? 0),
                                'name'=>$name,
                                'id_type'=>(string)($g['id_type'] ?? ''),
                                'id_number'=>(string)($g['id_number'] ?? ''),
                                'nationality'=>(string)($g['nationality'] ?? ''),
                                'gender'=>(string)($g['gender'] ?? ''),
                                'date_of_birth'=>(string)($g['date_of_birth'] ?? ''),
                                'phone'=>(string)($g['phone'] ?? ''),
                                'email'=>(string)($g['email'] ?? ''),
                                'address'=>(string)($g['address'] ?? ''),
                                'registration_notes'=>(string)($g['registration_notes'] ?? ''),
                            ];
                        }
                        $complete = $filledCount >= $expected;
                        $collapseId = 'precheckinRoom' . $rid;
                        $headingId = 'precheckinHeading' . $rid;
                        ?>
                        <div class="accordion-item mb-3 border rounded-3 overflow-hidden precheckin-room <?php echo $complete ? 'is-complete' : 'is-incomplete'; ?>">
                            <h2 class="accordion-header" id="<?php echo $headingId; ?>">
                                <button class="accordion-button <?php echo $rowIndex === 0 ? '' : 'collapsed'; ?>" type="button"
                                        data-bs-toggle="collapse"
                                        data-bs-target="#<?php echo $collapseId; ?>"
                                        aria-expanded="<?php echo $rowIndex === 0 ? 'true' : 'false'; ?>"
                                        aria-controls="<?php echo $collapseId; ?>">
                                    <div class="w-100 d-flex justify-content-between align-items-center pe-3 gap-3">
                                        <div>
                                            <strong>
                                                Room <?php echo ptg_e((string)($r['room_no'] ?: 'Unassigned')); ?>
                                                <span class="text-muted">•</span>
                                                <?php echo ptg_e($r['order_no'] ?? ('#'.$r['order_id'])); ?>
                                            </strong>
                                            <div class="small text-muted">
                                                <?php echo ptg_e((string)($r['lead_guest_name'] ?: 'Guest')); ?>
                                                • <?php echo ptg_e((string)($r['room_type'] ?? '')); ?>
                                                • <?php echo $adults; ?>A / <?php echo $children; ?>C
                                                • Max guests: <?php echo (int)$occupantLimit; ?>
                                                • <?php echo ptg_e(ptg_date($r['check_in'])); ?> to <?php echo ptg_e(ptg_date($r['check_out'])); ?>
                                            </div>
                                        </div>
                                        <span class="badge <?php echo $complete ? 'text-bg-success' : 'text-bg-warning text-dark'; ?>">
                                            <?php echo $complete ? 'Looks complete' : 'Needs details'; ?>
                                        </span>
                                    </div>
                                </button>
                            </h2>

                            <div id="<?php echo $collapseId; ?>"
                                 class="accordion-collapse collapse <?php echo $rowIndex === 0 ? 'show' : ''; ?>"
                                 aria-labelledby="<?php echo $headingId; ?>"
                                 data-bs-parent="#precheckinAccordion">
                                <div class="accordion-body bg-light">
                                    <input type="hidden" name="rooming_id[]" value="<?php echo $rid; ?>">
                                    <input type="hidden" name="order_id[<?php echo $rid; ?>]" value="<?php echo (int)$r['order_id']; ?>">
                                    <input type="hidden" name="room_limit[<?php echo $rid; ?>]" value="<?php echo (int)$occupantLimit; ?>">

                                    <div class="row g-3 mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label small fw-bold">Bed / Room Configuration</label>
                                            <?php $bedConfig = (string)($r['bed_configuration'] ?? ''); ?>
                                            <select name="bed_configuration[<?php echo $rid; ?>]" class="form-select form-select-sm">
                                                <option value="" <?php echo $bedConfig === '' ? 'selected' : ''; ?>>Not specified</option>
                                                <?php foreach (['Single','Double','Twin','Triple','Family'] as $bc): ?>
                                                    <option value="<?php echo ptg_e($bc); ?>" <?php echo $bedConfig === $bc ? 'selected' : ''; ?>><?php echo ptg_e($bc); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-8">
                                            <label class="form-label small fw-bold">Special Room Configuration Request</label>
                                            <input type="text" name="special_room_request[<?php echo $rid; ?>]" class="form-control form-control-sm"
                                                   value="<?php echo ptg_e($r['special_room_request'] ?? ''); ?>"
                                                   placeholder="e.g. honeymoon setup, twin beds, baby cot, ground floor">
                                        </div>
                                    </div>

                                    <div class="alert alert-info py-2 small mb-3">
                                        This room allows <strong><?php echo (int)$occupantLimit; ?></strong>
                                        registered guest<?php echo $occupantLimit === 1 ? '' : 's'; ?> based on Adults + Children.
                                        Kids 0-3 no charge are excluded, same as normal check-in.
                                    </div>

                                    <?php for ($i=1; $i<=$occupantLimit; $i++): ?>
                                        <?php $slot = $slots[$i]; ?>
                                        <div class="guest-preload-card mb-3">
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <strong><i class="bi bi-person-vcard me-1"></i>Guest <?php echo $i; ?></strong>
                                                <?php if ($i === 1): ?><span class="badge text-bg-primary">Primary</span><?php endif; ?>
                                            </div>
                                            <input type="hidden" name="guest_id[<?php echo $rid; ?>][<?php echo $i; ?>]" value="<?php echo (int)$slot['id']; ?>">
                                            <div class="row g-2">
                                                <div class="col-md-4"><label class="form-label small">Full Name</label><input type="text" name="guest_name[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-control form-control-sm" value="<?php echo ptg_e($slot['name']); ?>" placeholder="Guest full name"></div>
                                                <div class="col-md-2"><label class="form-label small">ID Type</label><select name="guest_id_type[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-select form-select-sm"><?php $idType = $slot['id_type']; ?><option value="">Select</option><?php foreach (['National ID','Passport','Driver Licence','Other'] as $opt): ?><option value="<?php echo ptg_e($opt); ?>" <?php echo $idType === $opt ? 'selected' : ''; ?>><?php echo ptg_e($opt); ?></option><?php endforeach; ?></select></div>
                                                <div class="col-md-3"><label class="form-label small">ID / Passport No.</label><input type="text" name="guest_id_number[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-control form-control-sm" value="<?php echo ptg_e($slot['id_number']); ?>"></div>
                                                <div class="col-md-3"><label class="form-label small">Nationality</label><select name="guest_nationality[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-select form-select-sm"><option value="">Select</option><?php foreach ($nationalities as $nat): ?><option value="<?php echo ptg_e($nat); ?>" <?php echo $slot['nationality'] === $nat ? 'selected' : ''; ?>><?php echo ptg_e($nat); ?></option><?php endforeach; ?></select></div>
                                                <div class="col-md-2"><label class="form-label small">Gender</label><?php $gender = $slot['gender']; ?><select name="guest_gender[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-select form-select-sm"><option value="">Select</option><?php foreach (['Male','Female','Other'] as $opt): ?><option value="<?php echo ptg_e($opt); ?>" <?php echo $gender === $opt ? 'selected' : ''; ?>><?php echo ptg_e($opt); ?></option><?php endforeach; ?></select></div>
                                                <div class="col-md-2"><label class="form-label small">DOB</label><input type="date" name="guest_date_of_birth[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-control form-control-sm" value="<?php echo ptg_e(substr((string)$slot['date_of_birth'],0,10)); ?>"></div>
                                                <div class="col-md-3"><label class="form-label small">Phone</label><input type="text" name="guest_phone[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-control form-control-sm" value="<?php echo ptg_e($slot['phone']); ?>"></div>
                                                <div class="col-md-5"><label class="form-label small">Email</label><input type="email" name="guest_email[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-control form-control-sm" value="<?php echo ptg_e($slot['email']); ?>"></div>
                                                <div class="col-md-6"><label class="form-label small">Address</label><input type="text" name="guest_address[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-control form-control-sm" value="<?php echo ptg_e($slot['address']); ?>"></div>
                                                <div class="col-md-6"><label class="form-label small">Registration Notes</label><input type="text" name="guest_registration_notes[<?php echo $rid; ?>][<?php echo $i; ?>]" class="form-control form-control-sm" value="<?php echo ptg_e($slot['registration_notes']); ?>"></div>
                                            </div>
                                        </div>
                                    <?php endfor; ?>

                                    <div class="d-flex justify-content-between gap-2">
                                        <button type="button" class="btn btn-sm btn-outline-secondary btn-prev-room"><i class="bi bi-chevron-up me-1"></i>Previous Room</button>
                                        <div class="d-flex gap-2">
                                            <button type="submit" name="save_guest_names" value="1" class="btn btn-sm btn-success"><i class="bi bi-save me-1"></i>Save</button>
                                            <button type="button" class="btn btn-sm btn-primary btn-next-room">Next Room <i class="bi bi-chevron-down ms-1"></i></button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <?php if ($rows): ?>
                <div class="card-footer text-end">
                    <button type="submit" name="save_guest_names" value="1" class="btn btn-success">
                        <i class="bi bi-save me-1"></i>Save Pre-Check-In Details
                    </button>
                </div>
            <?php endif; ?>
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const accordion = document.getElementById('precheckinAccordion');
    if (!accordion || typeof bootstrap === 'undefined') return;

    function roomItems() { return Array.from(accordion.querySelectorAll('.accordion-item')); }
    function showItem(item) {
        if (!item) return;
        const target = item.querySelector('.accordion-collapse');
        if (!target) return;
        bootstrap.Collapse.getOrCreateInstance(target, {toggle:false}).show();
        setTimeout(function(){ item.scrollIntoView({behavior:'smooth', block:'start'}); }, 120);
    }

    document.querySelectorAll('.btn-next-room').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const items = roomItems();
            const current = btn.closest('.accordion-item');
            const idx = items.indexOf(current);
            showItem(items[idx + 1] || items[0]);
        });
    });
    document.querySelectorAll('.btn-prev-room').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const items = roomItems();
            const current = btn.closest('.accordion-item');
            const idx = items.indexOf(current);
            showItem(items[idx - 1] || items[items.length - 1]);
        });
    });
    const openFirstIncomplete = document.getElementById('openFirstIncomplete');
    if (openFirstIncomplete) {
        openFirstIncomplete.addEventListener('click', function () {
            showItem(accordion.querySelector('.accordion-item.is-incomplete') || accordion.querySelector('.accordion-item'));
        });
    }
    if (window.location.search.indexOf('saved=1') !== -1) {
        setTimeout(function () {
            showItem(accordion.querySelector('.accordion-item.is-incomplete') || accordion.querySelector('.accordion-item'));
        }, 250);
    }
});
</script>

<style>
.precheckin-accordion .accordion-button{padding:.75rem 1rem}
.guest-preload-card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:12px}
.precheckin-room.is-complete{border-color:#bbf7d0!important}
.precheckin-room.is-incomplete{border-color:#fde68a!important}
.precheckin-toolbar{background:#f8fafc}
</style>

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