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

$pageTitle = 'Room Types';

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('slugify_room_type')) {
    function slugify_room_type(string $text): string
    {
        $text = trim($text);
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9]+/i', '-', $text);
        $text = trim((string)$text, '-');
        return $text !== '' ? $text : 'room-type';
    }
}

if (!function_exists('unique_room_type_slug')) {
    function unique_room_type_slug(PDO $pdo, int $propertyId, string $baseSlug, int $excludeId = 0): string
    {
        $slug = $baseSlug !== '' ? $baseSlug : 'room-type';
        $try = $slug;
        $i = 2;

        while (true) {
            $stmt = $pdo->prepare("
                SELECT id
                FROM room_types
                WHERE property_id = :property_id
                  AND slug = :slug
                  AND id <> :id
                LIMIT 1
            ");
            $stmt->execute([
                ':property_id' => $propertyId,
                ':slug'        => $try,
                ':id'          => $excludeId,
            ]);

            if (!$stmt->fetch(PDO::FETCH_ASSOC)) {
                return $try;
            }

            $try = $slug . '-' . $i;
            $i++;
        }
    }
}

$form = [
    'id'                => 0,
    'property_id'       => '',
    'title'             => '',
    'slug'              => '',
    'shortcode'         => '',
    'description'       => '',
    'base_occupancy'    => '',
    'higher_occupancy'  => '',
    'extra_bed'         => '0',
    'extra_beds'        => '',
    'kids_occupancy'    => '',
    'base_price'        => '',
    'additional_person' => '',
    'extra_bed_price'   => '',
];

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

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Room type saved successfully.';
}
if (isset($_GET['deleted']) && (int)$_GET['deleted'] === 1) {
    $success = 'Room type deleted successfully.';
}

$properties = $pdo->query("
    SELECT id, name, code, currency_code
    FROM properties
    WHERE is_active = 1
    ORDER BY name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$propertyFilter = (int)($_GET['property_id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_room_type'])) {
    $form['id']                = (int)($_POST['id'] ?? 0);
    $form['property_id']       = trim((string)($_POST['property_id'] ?? ''));
    $form['title']             = trim((string)($_POST['title'] ?? ''));
    $form['slug']              = trim((string)($_POST['slug'] ?? ''));
    $form['shortcode']         = trim((string)($_POST['shortcode'] ?? ''));
    $form['description']       = trim((string)($_POST['description'] ?? ''));
    $form['base_occupancy']    = trim((string)($_POST['base_occupancy'] ?? ''));
    $form['higher_occupancy']  = trim((string)($_POST['higher_occupancy'] ?? ''));
    $form['extra_bed']         = (string)((int)($_POST['extra_bed'] ?? 0));
    $form['extra_beds']        = trim((string)($_POST['extra_beds'] ?? ''));
    $form['kids_occupancy']    = trim((string)($_POST['kids_occupancy'] ?? ''));
    $form['base_price']        = trim((string)($_POST['base_price'] ?? ''));
    $form['additional_person'] = trim((string)($_POST['additional_person'] ?? ''));
    $form['extra_bed_price']   = trim((string)($_POST['extra_bed_price'] ?? ''));

    $editing = $form['id'] > 0;
    $propertyFilter = (int)$form['property_id'];

    if ($form['property_id'] === '' || (int)$form['property_id'] <= 0) {
        $errors[] = 'Please select a property.';
    }
    if ($form['title'] === '') {
        $errors[] = 'Title is required.';
    }
    if ($form['shortcode'] === '') {
        $errors[] = 'Shortcode is required.';
    }
    if ($form['base_occupancy'] === '') {
        $errors[] = 'Base occupancy is required.';
    }
    if ($form['higher_occupancy'] === '') {
        $errors[] = 'Higher occupancy is required.';
    }
    if ($form['kids_occupancy'] === '') {
        $errors[] = 'Kids occupancy is required.';
    }
    if ($form['base_price'] === '' || !is_numeric($form['base_price'])) {
        $errors[] = 'Base price must be a valid number.';
    }
    if ($form['additional_person'] === '' || !is_numeric($form['additional_person'])) {
        $errors[] = 'Additional person price must be a valid number.';
    }
    if ($form['extra_bed_price'] === '' || !is_numeric($form['extra_bed_price'])) {
        $errors[] = 'Extra bed price must be a valid number.';
    }

    $rawSlug = $form['slug'] !== '' ? $form['slug'] : $form['title'];
    $slug = slugify_room_type($rawSlug);

    if ((int)$form['property_id'] > 0) {
        $slug = unique_room_type_slug($pdo, (int)$form['property_id'], $slug, (int)$form['id']);
    }

    try {
        $stmt = $pdo->prepare("
            SELECT id
            FROM room_types
            WHERE property_id = :property_id
              AND shortcode = :shortcode
              AND id <> :id
            LIMIT 1
        ");
        $stmt->execute([
            ':property_id' => (int)$form['property_id'],
            ':shortcode'   => $form['shortcode'],
            ':id'          => (int)$form['id'],
        ]);
        if ($stmt->fetch(PDO::FETCH_ASSOC)) {
            $errors[] = 'A room type with that shortcode already exists for this property.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }

    if (!$errors) {
        try {
            if ($editing) {
                $stmt = $pdo->prepare("
                    UPDATE room_types
                    SET property_id = :property_id,
                        title = :title,
                        slug = :slug,
                        shortcode = :shortcode,
                        description = :description,
                        base_occupancy = :base_occupancy,
                        higher_occupancy = :higher_occupancy,
                        extra_bed = :extra_bed,
                        extra_beds = :extra_beds,
                        kids_occupancy = :kids_occupancy,
                        base_price = :base_price,
                        additional_person = :additional_person,
                        extra_bed_price = :extra_bed_price
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':property_id'       => (int)$form['property_id'],
                    ':title'             => $form['title'],
                    ':slug'              => $slug,
                    ':shortcode'         => $form['shortcode'],
                    ':description'       => $form['description'] !== '' ? $form['description'] : null,
                    ':base_occupancy'    => $form['base_occupancy'],
                    ':higher_occupancy'  => $form['higher_occupancy'],
                    ':extra_bed'         => (int)$form['extra_bed'],
                    ':extra_beds'        => $form['extra_beds'] !== '' ? $form['extra_beds'] : null,
                    ':kids_occupancy'    => $form['kids_occupancy'],
                    ':base_price'        => round((float)$form['base_price'], 2),
                    ':additional_person' => round((float)$form['additional_person'], 2),
                    ':extra_bed_price'   => round((float)$form['extra_bed_price'], 2),
                    ':id'                => (int)$form['id'],
                ]);
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO room_types
                    (
                        property_id,
                        title,
                        slug,
                        shortcode,
                        description,
                        base_occupancy,
                        higher_occupancy,
                        extra_bed,
                        extra_beds,
                        kids_occupancy,
                        base_price,
                        additional_person,
                        extra_bed_price
                    )
                    VALUES
                    (
                        :property_id,
                        :title,
                        :slug,
                        :shortcode,
                        :description,
                        :base_occupancy,
                        :higher_occupancy,
                        :extra_bed,
                        :extra_beds,
                        :kids_occupancy,
                        :base_price,
                        :additional_person,
                        :extra_bed_price
                    )
                ");
                $stmt->execute([
                    ':property_id'       => (int)$form['property_id'],
                    ':title'             => $form['title'],
                    ':slug'              => $slug,
                    ':shortcode'         => $form['shortcode'],
                    ':description'       => $form['description'] !== '' ? $form['description'] : null,
                    ':base_occupancy'    => $form['base_occupancy'],
                    ':higher_occupancy'  => $form['higher_occupancy'],
                    ':extra_bed'         => (int)$form['extra_bed'],
                    ':extra_beds'        => $form['extra_beds'] !== '' ? $form['extra_beds'] : null,
                    ':kids_occupancy'    => $form['kids_occupancy'],
                    ':base_price'        => round((float)$form['base_price'], 2),
                    ':additional_person' => round((float)$form['additional_person'], 2),
                    ':extra_bed_price'   => round((float)$form['extra_bed_price'], 2),
                ]);
            }

            header('Location: roomtypes.php?saved=1&property_id=' . (int)$form['property_id']);
            exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['delete']) && (int)$_GET['delete'] > 0) {
    $deleteId = (int)$_GET['delete'];

    try {
        $stmt = $pdo->prepare("DELETE FROM room_types WHERE id = :id");
        $stmt->execute([':id' => $deleteId]);

        header('Location: roomtypes.php?deleted=1&property_id=' . $propertyFilter);
        exit;
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    $editId = (int)$_GET['edit'];

    try {
        $stmt = $pdo->prepare("SELECT * FROM room_types WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $editId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $editing = true;
            $form = [
                'id'                => (int)$row['id'],
                'property_id'       => (string)($row['property_id'] ?? ''),
                'title'             => (string)$row['title'],
                'slug'              => (string)$row['slug'],
                'shortcode'         => (string)$row['shortcode'],
                'description'       => (string)($row['description'] ?? ''),
                'base_occupancy'    => (string)$row['base_occupancy'],
                'higher_occupancy'  => (string)$row['higher_occupancy'],
                'extra_bed'         => (string)(int)($row['extra_bed'] ?? 0),
                'extra_beds'        => (string)($row['extra_beds'] ?? ''),
                'kids_occupancy'    => (string)$row['kids_occupancy'],
                'base_price'        => (string)$row['base_price'],
                'additional_person' => (string)$row['additional_person'],
                'extra_bed_price'   => (string)$row['extra_bed_price'],
            ];
            $propertyFilter = (int)$form['property_id'];
        } else {
            $errors[] = 'Room type not found.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$search = trim((string)($_GET['q'] ?? ''));

$sql = "
    SELECT
        rt.*,
        p.name AS property_name,
        p.code AS property_code,
        p.currency_code
    FROM room_types rt
    LEFT JOIN properties p ON p.id = rt.property_id
    WHERE 1=1
";
$params = [];

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

if ($search !== '') {
    $sql .= "
        AND (
            rt.title LIKE :search
            OR rt.slug LIKE :search
            OR rt.shortcode LIKE :search
            OR rt.description LIKE :search
            OR rt.base_occupancy LIKE :search
            OR rt.higher_occupancy LIKE :search
            OR rt.kids_occupancy LIKE :search
            OR p.name LIKE :search
            OR p.code LIKE :search
        )
    ";
    $params[':search'] = '%' . $search . '%';
}

$sql .= " ORDER BY p.name ASC, rt.title ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$roomTypes = $stmt->fetchAll(PDO::FETCH_ASSOC);

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-house-door"></i> Masters</div>
            <div class="hero-title mt-2">Room Types</div>
            <div class="hero-subtitle mt-2">
                Manage room categories, occupancy rules, and pricing settings by property.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="roomtypes.php<?php echo $propertyFilter > 0 ? '?property_id=' . (int)$propertyFilter : ''; ?>" class="btn btn-outline-light">
                <i class="bi bi-plus-circle me-2"></i>New Room Type
            </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="row g-4">
    <div class="col-xl-5">
        <div class="form-section">
            <div class="form-section-title">
                <i class="bi bi-door-open"></i>
                <?php echo $editing ? 'Edit Room Type' : 'New Room Type'; ?>
            </div>

            <form method="post" class="row g-3">
                <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">

                <div class="col-12">
                    <label class="form-label">Property</label>
                    <select name="property_id" class="form-select" required>
                        <option value="">Select property</option>
                        <?php foreach ($properties as $p): ?>
                            <option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$form['property_id'] === (int)$p['id'] ? 'selected' : ''; ?>>
                                <?php echo h($p['name']); ?> - <?php echo h($p['code']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Title</label>
                    <input type="text" name="title" class="form-control" value="<?php echo h($form['title']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Shortcode</label>
                    <input type="text" name="shortcode" class="form-control" value="<?php echo h($form['shortcode']); ?>" required>
                </div>

                <div class="col-12">
                    <label class="form-label">Slug</label>
                    <input type="text" name="slug" class="form-control" value="<?php echo h($form['slug']); ?>" placeholder="Leave blank to auto-generate from title">
                </div>

                <div class="col-md-4">
                    <label class="form-label">Base Occupancy</label>
                    <input type="text" name="base_occupancy" class="form-control" value="<?php echo h($form['base_occupancy']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Higher Occupancy</label>
                    <input type="text" name="higher_occupancy" class="form-control" value="<?php echo h($form['higher_occupancy']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Kids Occupancy</label>
                    <input type="text" name="kids_occupancy" class="form-control" value="<?php echo h($form['kids_occupancy']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Extra Bed Allowed</label>
                    <select name="extra_bed" class="form-select">
                        <option value="0" <?php echo $form['extra_bed'] === '0' ? 'selected' : ''; ?>>No</option>
                        <option value="1" <?php echo $form['extra_bed'] === '1' ? 'selected' : ''; ?>>Yes</option>
                    </select>
                </div>

                <div class="col-md-8">
                    <label class="form-label">Extra Beds</label>
                    <input type="text" name="extra_beds" class="form-control" value="<?php echo h($form['extra_beds']); ?>" placeholder="e.g. 1, 2, Max 1">
                </div>

                <div class="col-md-4">
                    <label class="form-label">Base Price</label>
                    <input type="number" step="0.01" min="0" name="base_price" class="form-control" value="<?php echo h($form['base_price']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Additional Person</label>
                    <input type="number" step="0.01" min="0" name="additional_person" class="form-control" value="<?php echo h($form['additional_person']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Extra Bed Price</label>
                    <input type="number" step="0.01" min="0" name="extra_bed_price" class="form-control" value="<?php echo h($form['extra_bed_price']); ?>" required>
                </div>

                <div class="col-12">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="4"><?php echo h($form['description']); ?></textarea>
                </div>

                <div class="col-12 d-flex gap-2">
                    <button type="submit" name="save_room_type" value="1" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i><?php echo $editing ? 'Update Room Type' : 'Save Room Type'; ?>
                    </button>
                    <a href="roomtypes.php<?php echo $propertyFilter > 0 ? '?property_id=' . (int)$propertyFilter : ''; ?>" class="btn btn-light">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card">
            <div class="card-header">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <h5 class="mb-0">Room Types</h5>
                    <form method="get" class="d-flex flex-wrap gap-2">
                        <select name="property_id" class="form-select">
                            <option value="0">All properties</option>
                            <?php foreach ($properties as $p): ?>
                                <option value="<?php echo (int)$p['id']; ?>" <?php echo $propertyFilter === (int)$p['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($p['name']); ?> - <?php echo h($p['code']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <input type="text" name="q" class="form-control" placeholder="Search room types..." value="<?php echo h($search); ?>">
                        <button class="btn btn-outline-secondary">Search</button>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Property / Room Type</th>
                                <th>Occupancy</th>
                                <th>Pricing</th>
                                <th>Extra Bed</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$roomTypes): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">No room types found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($roomTypes as $row): ?>
                                    <tr>
                                        <td><?php echo (int)$row['id']; ?></td>
                                        <td>
                                            <div class="fw-semibold"><?php echo h($row['title']); ?></div>
                                            <div class="small text-muted">
                                                <?php echo h($row['property_name'] ?? ''); ?>
                                                <?php if (!empty($row['property_code'])): ?>
                                                     <?php echo h($row['property_code']); ?>
                                                <?php endif; ?>
                                            </div>
                                            <div class="small text-muted">
                                                <?php echo h($row['shortcode']); ?>  <?php echo h($row['slug']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="small">
                                                <strong>Base:</strong> <?php echo h($row['base_occupancy']); ?><br>
                                                <strong>Higher:</strong> <?php echo h($row['higher_occupancy']); ?><br>
                                                <strong>Kids:</strong> <?php echo h($row['kids_occupancy']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="small">
                                                <strong>Base:</strong> <?php echo money_fmt($row['base_price']); ?><br>
                                                <strong>Addl:</strong> <?php echo money_fmt($row['additional_person']); ?><br>
                                                <strong>Bed:</strong> <?php echo money_fmt($row['extra_bed_price']); ?>
                                                <?php if (!empty($row['currency_code'])): ?>
                                                    <br><strong>Cur:</strong> <?php echo h($row['currency_code']); ?>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ((int)$row['extra_bed'] === 1): ?>
                                                <span class="badge text-bg-success">Allowed</span>
                                                <div class="small text-muted mt-1"><?php echo h($row['extra_beds'] ?? ''); ?></div>
                                            <?php else: ?>
                                                <span class="badge text-bg-light text-dark border">No</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="d-inline-flex gap-2">
                                                <a href="roomtypes.php?edit=<?php echo (int)$row['id']; ?>&property_id=<?php echo (int)$row['property_id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                                <a href="roomtypes.php?delete=<?php echo (int)$row['id']; ?>&property_id=<?php echo (int)$propertyFilter; ?>"
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Delete this room type?');">
                                                    Delete
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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