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

$pageTitle = 'Channel Mapping';

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

if (!function_exists('map_table_exists')) {
    function map_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('map_column_exists')) {
    function map_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $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' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('map_flash')) {
    function map_flash(string $type, string $message): void {
        $_SESSION['channel_mapping_flash'][] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('map_get_flash')) {
    function map_get_flash(): array {
        $items = $_SESSION['channel_mapping_flash'] ?? [];
        unset($_SESSION['channel_mapping_flash']);
        return $items;
    }
}

$errors = [];

try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS channel_connections (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            provider ENUM('nightsbridge','booking_com','expedia','airbnb','custom') NOT NULL DEFAULT 'nightsbridge',
            connection_name VARCHAR(150) NOT NULL,
            property_id INT UNSIGNED NULL,
            external_property_id VARCHAR(120) NULL,
            api_base_url VARCHAR(255) NULL,
            api_username VARCHAR(150) NULL,
            api_password_enc TEXT NULL,
            api_token_enc TEXT NULL,
            webhook_secret_enc TEXT NULL,
            sync_mode ENUM('manual','scheduled','webhook') NOT NULL DEFAULT 'manual',
            sync_direction ENUM('pull_only','push_only','two_way') NOT NULL DEFAULT 'two_way',
            push_rates TINYINT(1) NOT NULL DEFAULT 1,
            push_availability TINYINT(1) NOT NULL DEFAULT 1,
            pull_bookings TINYINT(1) NOT NULL DEFAULT 1,
            auto_confirm_imported TINYINT(1) NOT NULL DEFAULT 0,
            prevent_overbooking TINYINT(1) NOT NULL DEFAULT 1,
            last_sync_at DATETIME NULL,
            last_sync_status VARCHAR(30) NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            notes TEXT NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_channel_provider (provider),
            INDEX idx_channel_property (property_id),
            INDEX idx_channel_active (is_active)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS channel_room_mapping (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            connection_id INT UNSIGNED NOT NULL,
            property_id INT UNSIGNED NULL,
            room_type_id INT UNSIGNED NOT NULL,
            external_room_id VARCHAR(120) NOT NULL,
            external_room_name VARCHAR(180) NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_channel_room_map (connection_id, room_type_id, external_room_id),
            INDEX idx_channel_room_connection (connection_id),
            INDEX idx_channel_room_type (room_type_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS channel_rate_mapping (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            connection_id INT UNSIGNED NOT NULL,
            room_type_id INT UNSIGNED NOT NULL,
            rate_plan_id INT UNSIGNED NULL,
            external_rate_id VARCHAR(120) NOT NULL,
            external_rate_name VARCHAR(180) NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_channel_rate_map (connection_id, room_type_id, external_rate_id),
            INDEX idx_channel_rate_connection (connection_id),
            INDEX idx_channel_rate_room_type (room_type_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS channel_sync_log (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            connection_id INT UNSIGNED NULL,
            provider VARCHAR(50) NOT NULL,
            sync_type VARCHAR(80) NOT NULL,
            sync_direction VARCHAR(30) NOT NULL,
            status VARCHAR(30) NOT NULL,
            request_payload MEDIUMTEXT NULL,
            response_payload MEDIUMTEXT NULL,
            message TEXT NULL,
            started_at DATETIME NOT NULL,
            completed_at DATETIME NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_channel_log_connection (connection_id),
            INDEX idx_channel_log_provider (provider),
            INDEX idx_channel_log_status (status),
            INDEX idx_channel_log_started (started_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare mapping tables: ' . $e->getMessage();
}

$connections = [];
$properties = [];
$roomTypes = [];
$ratePlans = [];

try {
    $connections = $pdo->query("
        SELECT
            cc.*,
            p.name AS property_name,
            p.code AS property_code
        FROM channel_connections cc
        LEFT JOIN properties p ON p.id = cc.property_id
        ORDER BY cc.is_active DESC, cc.provider ASC, cc.connection_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $connections = [];
}

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

try {
    if (map_table_exists($pdo, 'room_types')) {
        $roomTypes = $pdo->query("
            SELECT
                rt.id,
                rt.title,
                rt.property_id,
                p.name AS property_name
            FROM room_types rt
            LEFT JOIN properties p ON p.id = rt.property_id
            ORDER BY p.name ASC, rt.title ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {}

try {
    if (map_table_exists($pdo, 'room_type_rate_plans')) {
        $ratePlans = $pdo->query("
            SELECT
                rp.id,
                rp.title,
                rp.room_type_id,
                rt.title AS room_type,
                p.name AS property_name
            FROM room_type_rate_plans rp
            LEFT JOIN room_types rt ON rt.id = rp.room_type_id
            LEFT JOIN properties p ON p.id = rt.property_id
            ORDER BY p.name ASC, rt.title ASC, rp.title ASC
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save_room_mapping') {
            $id = (int)($_POST['id'] ?? 0);
            $connectionId = (int)($_POST['connection_id'] ?? 0);
            $propertyId = (int)($_POST['property_id'] ?? 0);
            $roomTypeId = (int)($_POST['room_type_id'] ?? 0);
            $externalRoomId = trim((string)($_POST['external_room_id'] ?? ''));
            $externalRoomName = trim((string)($_POST['external_room_name'] ?? ''));
            $isActive = isset($_POST['is_active']) ? 1 : 0;

            if ($connectionId <= 0) throw new RuntimeException('Please select a channel connection.');
            if ($roomTypeId <= 0) throw new RuntimeException('Please select a PMS room type.');
            if ($externalRoomId === '') throw new RuntimeException('External room ID is required.');

            $params = [
                ':connection_id' => $connectionId,
                ':property_id' => $propertyId > 0 ? $propertyId : null,
                ':room_type_id' => $roomTypeId,
                ':external_room_id' => $externalRoomId,
                ':external_room_name' => $externalRoomName !== '' ? $externalRoomName : null,
                ':is_active' => $isActive,
            ];

            if ($id > 0) {
                $params[':id'] = $id;
                $stmt = $pdo->prepare("
                    UPDATE channel_room_mapping
                    SET connection_id = :connection_id,
                        property_id = :property_id,
                        room_type_id = :room_type_id,
                        external_room_id = :external_room_id,
                        external_room_name = :external_room_name,
                        is_active = :is_active
                    WHERE id = :id
                ");
                $stmt->execute($params);
                map_flash('success', 'Room mapping updated.');
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO channel_room_mapping
                    (connection_id, property_id, room_type_id, external_room_id, external_room_name, is_active)
                    VALUES
                    (:connection_id, :property_id, :room_type_id, :external_room_id, :external_room_name, :is_active)
                ");
                $stmt->execute($params);
                map_flash('success', 'Room mapping created.');
            }

            header('Location: channel_mapping.php?connection_id=' . $connectionId);
            exit;
        }

        if ($action === 'save_rate_mapping') {
            $id = (int)($_POST['id'] ?? 0);
            $connectionId = (int)($_POST['connection_id'] ?? 0);
            $roomTypeId = (int)($_POST['room_type_id'] ?? 0);
            $ratePlanId = (int)($_POST['rate_plan_id'] ?? 0);
            $externalRateId = trim((string)($_POST['external_rate_id'] ?? ''));
            $externalRateName = trim((string)($_POST['external_rate_name'] ?? ''));
            $isActive = isset($_POST['is_active']) ? 1 : 0;

            if ($connectionId <= 0) throw new RuntimeException('Please select a channel connection.');
            if ($roomTypeId <= 0) throw new RuntimeException('Please select a PMS room type.');
            if ($externalRateId === '') throw new RuntimeException('External rate ID is required.');

            $params = [
                ':connection_id' => $connectionId,
                ':room_type_id' => $roomTypeId,
                ':rate_plan_id' => $ratePlanId > 0 ? $ratePlanId : null,
                ':external_rate_id' => $externalRateId,
                ':external_rate_name' => $externalRateName !== '' ? $externalRateName : null,
                ':is_active' => $isActive,
            ];

            if ($id > 0) {
                $params[':id'] = $id;
                $stmt = $pdo->prepare("
                    UPDATE channel_rate_mapping
                    SET connection_id = :connection_id,
                        room_type_id = :room_type_id,
                        rate_plan_id = :rate_plan_id,
                        external_rate_id = :external_rate_id,
                        external_rate_name = :external_rate_name,
                        is_active = :is_active
                    WHERE id = :id
                ");
                $stmt->execute($params);
                map_flash('success', 'Rate mapping updated.');
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO channel_rate_mapping
                    (connection_id, room_type_id, rate_plan_id, external_rate_id, external_rate_name, is_active)
                    VALUES
                    (:connection_id, :room_type_id, :rate_plan_id, :external_rate_id, :external_rate_name, :is_active)
                ");
                $stmt->execute($params);
                map_flash('success', 'Rate mapping created.');
            }

            header('Location: channel_mapping.php?connection_id=' . $connectionId);
            exit;
        }

        if ($action === 'toggle_room_mapping') {
            $id = (int)($_POST['id'] ?? 0);
            $connectionId = (int)($_POST['connection_id'] ?? 0);
            $stmt = $pdo->prepare("UPDATE channel_room_mapping SET is_active = CASE WHEN is_active=1 THEN 0 ELSE 1 END WHERE id=:id");
            $stmt->execute([':id' => $id]);
            map_flash('success', 'Room mapping status updated.');
            header('Location: channel_mapping.php?connection_id=' . $connectionId);
            exit;
        }

        if ($action === 'toggle_rate_mapping') {
            $id = (int)($_POST['id'] ?? 0);
            $connectionId = (int)($_POST['connection_id'] ?? 0);
            $stmt = $pdo->prepare("UPDATE channel_rate_mapping SET is_active = CASE WHEN is_active=1 THEN 0 ELSE 1 END WHERE id=:id");
            $stmt->execute([':id' => $id]);
            map_flash('success', 'Rate mapping status updated.');
            header('Location: channel_mapping.php?connection_id=' . $connectionId);
            exit;
        }

        if ($action === 'delete_room_mapping') {
            $id = (int)($_POST['id'] ?? 0);
            $connectionId = (int)($_POST['connection_id'] ?? 0);
            $stmt = $pdo->prepare("DELETE FROM channel_room_mapping WHERE id=:id");
            $stmt->execute([':id' => $id]);
            map_flash('success', 'Room mapping deleted.');
            header('Location: channel_mapping.php?connection_id=' . $connectionId);
            exit;
        }

        if ($action === 'delete_rate_mapping') {
            $id = (int)($_POST['id'] ?? 0);
            $connectionId = (int)($_POST['connection_id'] ?? 0);
            $stmt = $pdo->prepare("DELETE FROM channel_rate_mapping WHERE id=:id");
            $stmt->execute([':id' => $id]);
            map_flash('success', 'Rate mapping deleted.');
            header('Location: channel_mapping.php?connection_id=' . $connectionId);
            exit;
        }

    } catch (Throwable $e) {
        map_flash('danger', $e->getMessage());
        header('Location: channel_mapping.php' . (!empty($_POST['connection_id']) ? '?connection_id=' . (int)$_POST['connection_id'] : ''));
        exit;
    }
}

$selectedConnectionId = (int)($_GET['connection_id'] ?? 0);
if ($selectedConnectionId <= 0 && $connections) {
    $selectedConnectionId = (int)$connections[0]['id'];
}

$selectedConnection = null;
foreach ($connections as $conn) {
    if ((int)$conn['id'] === $selectedConnectionId) {
        $selectedConnection = $conn;
        break;
    }
}

$editRoomId = (int)($_GET['edit_room_id'] ?? 0);
$editRateId = (int)($_GET['edit_rate_id'] ?? 0);
$editRoomMapping = null;
$editRateMapping = null;

if ($editRoomId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM channel_room_mapping WHERE id=:id LIMIT 1");
    $stmt->execute([':id' => $editRoomId]);
    $editRoomMapping = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

if ($editRateId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM channel_rate_mapping WHERE id=:id LIMIT 1");
    $stmt->execute([':id' => $editRateId]);
    $editRateMapping = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$roomMappings = [];
$rateMappings = [];

if ($selectedConnectionId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                crm.*,
                p.name AS property_name,
                p.code AS property_code,
                rt.title AS room_type
            FROM channel_room_mapping crm
            LEFT JOIN properties p ON p.id = crm.property_id
            LEFT JOIN room_types rt ON rt.id = crm.room_type_id
            WHERE crm.connection_id = :connection_id
            ORDER BY crm.is_active DESC, rt.title ASC, crm.external_room_name ASC
        ");
        $stmt->execute([':connection_id' => $selectedConnectionId]);
        $roomMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {}

    try {
        $stmt = $pdo->prepare("
            SELECT
                crm.*,
                rt.title AS room_type,
                rp.title AS rate_plan
            FROM channel_rate_mapping crm
            LEFT JOIN room_types rt ON rt.id = crm.room_type_id
            LEFT JOIN room_type_rate_plans rp ON rp.id = crm.rate_plan_id
            WHERE crm.connection_id = :connection_id
            ORDER BY crm.is_active DESC, rt.title ASC, crm.external_rate_name ASC
        ");
        $stmt->execute([':connection_id' => $selectedConnectionId]);
        $rateMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {}
}

$mappedRoomTypeIds = array_map(fn($r) => (int)$r['room_type_id'], $roomMappings);
$unmappedRoomTypes = [];
foreach ($roomTypes as $rt) {
    if (!in_array((int)$rt['id'], $mappedRoomTypeIds, true)) {
        $unmappedRoomTypes[] = $rt;
    }
}

$flashes = map_get_flash();

$providerLabels = [
    'nightsbridge' => 'NightsBridge',
    'booking_com' => 'Booking.com',
    'expedia' => 'Expedia',
    'airbnb' => 'Airbnb',
    'custom' => 'Custom API',
];

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-diagram-3"></i> Channel Manager</div>
            <div class="hero-title mt-2">Channel Mapping</div>
            <div class="hero-subtitle mt-2">
                Link your PMS room types and rate plans to external channel room and rate IDs.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="channel_settings.php" class="btn btn-light me-2">
                <i class="bi bi-gear me-2"></i>Settings
            </a>
            <a href="channel_sync_log.php" class="btn btn-outline-light">
                <i class="bi bi-clock-history me-2"></i>Sync Log
            </a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

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

<?php if (!$connections): ?>
    <div class="alert alert-warning">
        No channel connection exists yet. Create one first in <a href="channel_settings.php">Channel Settings</a>.
    </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-9">
                <label class="form-label">Channel Connection</label>
                <select name="connection_id" class="form-select" onchange="this.form.submit()">
                    <?php foreach ($connections as $connection): ?>
                        <?php $providerLabel = $providerLabels[$connection['provider']] ?? ucwords(str_replace('_', ' ', $connection['provider'])); ?>
                        <option value="<?php echo (int)$connection['id']; ?>" <?php echo $selectedConnectionId === (int)$connection['id'] ? 'selected' : ''; ?>>
                            <?php echo h($connection['connection_name']); ?> — <?php echo h($providerLabel); ?> — <?php echo h($connection['property_name'] ?: 'Property'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 d-grid">
                <a href="channel_settings.php" class="btn btn-outline-primary">
                    <i class="bi bi-plus-circle me-2"></i>Add Connection
                </a>
            </div>
        </form>
    </div>
</div>

<?php if ($selectedConnection): ?>
<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-plug"></i></div>
            <div>
                <div class="metric-label">Provider</div>
                <div class="metric-value small-value"><?php echo h($providerLabels[$selectedConnection['provider']] ?? $selectedConnection['provider']); ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-door-open"></i></div>
            <div>
                <div class="metric-label">Room Mappings</div>
                <div class="metric-value"><?php echo count($roomMappings); ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-tags"></i></div>
            <div>
                <div class="metric-label">Rate Mappings</div>
                <div class="metric-value"><?php echo count($rateMappings); ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle"></i></div>
            <div>
                <div class="metric-label">Unmapped Rooms</div>
                <div class="metric-value"><?php echo count($unmappedRoomTypes); ?></div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><?php echo $editRoomMapping ? 'Edit Room Mapping' : 'Add Room Mapping'; ?></h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_room_mapping">
                    <input type="hidden" name="id" value="<?php echo (int)($editRoomMapping['id'] ?? 0); ?>">
                    <input type="hidden" name="connection_id" value="<?php echo (int)$selectedConnectionId; ?>">

                    <div class="mb-3">
                        <label class="form-label">Property</label>
                        <select name="property_id" class="form-select">
                            <option value="0">Use connection property</option>
                            <?php foreach ($properties as $property): ?>
                                <option value="<?php echo (int)$property['id']; ?>" <?php echo (int)($editRoomMapping['property_id'] ?? 0) === (int)$property['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($property['name']); ?> - <?php echo h($property['code']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">PMS Room Type</label>
                        <select name="room_type_id" class="form-select" required>
                            <option value="">Select room type</option>
                            <?php foreach ($roomTypes as $rt): ?>
                                <option value="<?php echo (int)$rt['id']; ?>" <?php echo (int)($editRoomMapping['room_type_id'] ?? 0) === (int)$rt['id'] ? 'selected' : ''; ?>>
                                    <?php echo h(($rt['property_name'] ? $rt['property_name'] . ' - ' : '') . $rt['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">External Room ID</label>
                        <input type="text" name="external_room_id" class="form-control" required value="<?php echo h($editRoomMapping['external_room_id'] ?? ''); ?>" placeholder="Channel room ID">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">External Room Name</label>
                        <input type="text" name="external_room_name" class="form-control" value="<?php echo h($editRoomMapping['external_room_name'] ?? ''); ?>" placeholder="Deluxe Room on Booking.com">
                    </div>

                    <label class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="is_active" value="1" <?php echo (int)($editRoomMapping['is_active'] ?? 1) === 1 ? 'checked' : ''; ?>>
                        <span class="form-check-label">Active mapping</span>
                    </label>

                    <div class="d-grid gap-2">
                        <button class="btn btn-primary">
                            <i class="bi bi-save me-2"></i><?php echo $editRoomMapping ? 'Update Room Mapping' : 'Save Room Mapping'; ?>
                        </button>
                        <?php if ($editRoomMapping): ?>
                            <a href="channel_mapping.php?connection_id=<?php echo (int)$selectedConnectionId; ?>" class="btn btn-outline-secondary">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0"><?php echo $editRateMapping ? 'Edit Rate Mapping' : 'Add Rate Mapping'; ?></h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_rate_mapping">
                    <input type="hidden" name="id" value="<?php echo (int)($editRateMapping['id'] ?? 0); ?>">
                    <input type="hidden" name="connection_id" value="<?php echo (int)$selectedConnectionId; ?>">

                    <div class="mb-3">
                        <label class="form-label">PMS Room Type</label>
                        <select name="room_type_id" class="form-select" required>
                            <option value="">Select room type</option>
                            <?php foreach ($roomTypes as $rt): ?>
                                <option value="<?php echo (int)$rt['id']; ?>" <?php echo (int)($editRateMapping['room_type_id'] ?? 0) === (int)$rt['id'] ? 'selected' : ''; ?>>
                                    <?php echo h(($rt['property_name'] ? $rt['property_name'] . ' - ' : '') . $rt['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">PMS Rate Plan</label>
                        <select name="rate_plan_id" class="form-select">
                            <option value="0">No specific PMS rate plan</option>
                            <?php foreach ($ratePlans as $rp): ?>
                                <option value="<?php echo (int)$rp['id']; ?>" <?php echo (int)($editRateMapping['rate_plan_id'] ?? 0) === (int)$rp['id'] ? 'selected' : ''; ?>>
                                    <?php echo h(($rp['property_name'] ? $rp['property_name'] . ' - ' : '') . ($rp['room_type'] ? $rp['room_type'] . ' - ' : '') . $rp['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (!$ratePlans): ?>
                            <div class="small text-muted mt-1">No PMS rate plan table found or no rate plans exist yet.</div>
                        <?php endif; ?>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">External Rate ID</label>
                        <input type="text" name="external_rate_id" class="form-control" required value="<?php echo h($editRateMapping['external_rate_id'] ?? ''); ?>" placeholder="Channel rate ID">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">External Rate Name</label>
                        <input type="text" name="external_rate_name" class="form-control" value="<?php echo h($editRateMapping['external_rate_name'] ?? ''); ?>" placeholder="Standard Rate / BAR">
                    </div>

                    <label class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="is_active" value="1" <?php echo (int)($editRateMapping['is_active'] ?? 1) === 1 ? 'checked' : ''; ?>>
                        <span class="form-check-label">Active mapping</span>
                    </label>

                    <div class="d-grid gap-2">
                        <button class="btn btn-primary">
                            <i class="bi bi-save me-2"></i><?php echo $editRateMapping ? 'Update Rate Mapping' : 'Save Rate Mapping'; ?>
                        </button>
                        <?php if ($editRateMapping): ?>
                            <a href="channel_mapping.php?connection_id=<?php echo (int)$selectedConnectionId; ?>" class="btn btn-outline-secondary">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Room Type Mappings</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>PMS Room Type</th>
                            <th>Property</th>
                            <th>External Room</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$roomMappings): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No room mappings yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($roomMappings as $row): ?>
                                <tr>
                                    <td><strong><?php echo h($row['room_type']); ?></strong></td>
                                    <td>
                                        <?php echo h($row['property_name'] ?: ($selectedConnection['property_name'] ?? 'Connection Property')); ?>
                                        <div class="small text-muted"><?php echo h($row['property_code'] ?? ''); ?></div>
                                    </td>
                                    <td>
                                        <strong><?php echo h($row['external_room_id']); ?></strong>
                                        <div class="small text-muted"><?php echo h($row['external_room_name'] ?: 'No external name'); ?></div>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo (int)$row['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>">
                                            <?php echo (int)$row['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a class="btn btn-outline-primary" href="channel_mapping.php?connection_id=<?php echo (int)$selectedConnectionId; ?>&edit_room_id=<?php echo (int)$row['id']; ?>">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="toggle_room_mapping">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <input type="hidden" name="connection_id" value="<?php echo (int)$selectedConnectionId; ?>">
                                                <button class="btn btn-outline-secondary"><i class="bi bi-toggle-on"></i></button>
                                            </form>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Delete this room mapping?');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_room_mapping">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <input type="hidden" name="connection_id" value="<?php echo (int)$selectedConnectionId; ?>">
                                                <button class="btn btn-outline-danger"><i class="bi bi-trash"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card panel-card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Rate Plan Mappings</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>PMS Room Type</th>
                            <th>PMS Rate Plan</th>
                            <th>External Rate</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$rateMappings): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No rate mappings yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($rateMappings as $row): ?>
                                <tr>
                                    <td><strong><?php echo h($row['room_type']); ?></strong></td>
                                    <td><?php echo h($row['rate_plan'] ?: 'No specific PMS rate plan'); ?></td>
                                    <td>
                                        <strong><?php echo h($row['external_rate_id']); ?></strong>
                                        <div class="small text-muted"><?php echo h($row['external_rate_name'] ?: 'No external name'); ?></div>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo (int)$row['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>">
                                            <?php echo (int)$row['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a class="btn btn-outline-primary" href="channel_mapping.php?connection_id=<?php echo (int)$selectedConnectionId; ?>&edit_rate_id=<?php echo (int)$row['id']; ?>">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="toggle_rate_mapping">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <input type="hidden" name="connection_id" value="<?php echo (int)$selectedConnectionId; ?>">
                                                <button class="btn btn-outline-secondary"><i class="bi bi-toggle-on"></i></button>
                                            </form>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Delete this rate mapping?');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_rate_mapping">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <input type="hidden" name="connection_id" value="<?php echo (int)$selectedConnectionId; ?>">
                                                <button class="btn btn-outline-danger"><i class="bi bi-trash"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <?php if ($unmappedRoomTypes): ?>
            <div class="card panel-card">
                <div class="card-header">
                    <h5 class="mb-0">Unmapped PMS Room Types</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex flex-wrap gap-2">
                        <?php foreach ($unmappedRoomTypes as $rt): ?>
                            <span class="badge rounded-pill text-bg-light border p-2">
                                <?php echo h(($rt['property_name'] ? $rt['property_name'] . ' - ' : '') . $rt['title']); ?>
                            </span>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
</style>

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