<?php
/**
 * REVENDA - Core Functions
 * @version 10.2.0
 */

// ============================================
// SESSION AUTO-HEAL
// ============================================
if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0) {
    $needsHeal = !isset($_SESSION['is_vendor'])
              || !isset($_SESSION['is_admin'])
              || !isset($_SESSION['is_staff'])
              || !isset($_SESSION['role']);

    if ($needsHeal && function_exists('db')) {
        try {
            $__db = db();
            $__u = $__db->fetchOne(
                "SELECT is_admin, is_vendor, is_staff, first_name, last_name, email
                 FROM users WHERE id = ?",
                [$_SESSION['user_id']]
            );

            if ($__u) {
                $_SESSION['is_admin']  = (int)($__u['is_admin'] ?? 0);
                $_SESSION['is_vendor'] = (int)($__u['is_vendor'] ?? 0);
                $_SESSION['is_staff']  = (int)($__u['is_staff'] ?? 0);
                $_SESSION['first_name'] = $__u['first_name'] ?? ($_SESSION['first_name'] ?? '');
                $_SESSION['last_name']  = $__u['last_name'] ?? ($_SESSION['last_name'] ?? '');
                $_SESSION['email']      = $__u['email'] ?? ($_SESSION['email'] ?? '');

                $_SESSION['is_super_admin'] = (
                    $_SESSION['is_admin'] == 1 &&
                    $_SESSION['is_vendor'] == 1 &&
                    $_SESSION['is_staff'] == 1
                ) ? 1 : 0;

                $_SESSION['role'] =
                    $_SESSION['is_super_admin'] ? 'super_admin'
                    : ($_SESSION['is_admin'] ? 'admin'
                    : ($_SESSION['is_vendor'] ? 'vendor'
                    : ($_SESSION['is_staff'] ? 'staff' : 'user')));
            }
        } catch (Throwable $e) {}
    }
}

// ============================================
// AUTHENTICATION & ROLES
// ============================================

function isLoggedIn() {
    return isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0;
}

function isSuperAdmin() {
    if (!isLoggedIn()) return false;
    if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1
        && isset($_SESSION['is_vendor']) && $_SESSION['is_vendor'] == 1
        && isset($_SESSION['is_staff']) && $_SESSION['is_staff'] == 1) {
        return true;
    }
    try {
        $db = db();
        $u = $db->fetchOne(
            "SELECT is_admin, is_vendor, is_staff FROM users WHERE id = ?",
            [$_SESSION['user_id']]
        );
        if ($u && $u['is_admin'] == 1 && $u['is_vendor'] == 1 && $u['is_staff'] == 1) {
            $_SESSION['is_admin'] = 1;
            $_SESSION['is_vendor'] = 1;
            $_SESSION['is_staff'] = 1;
            $_SESSION['is_super_admin'] = 1;
            return true;
        }
    } catch (Throwable $e) {}
    return false;
}

function isAdmin() {
    if (!isLoggedIn()) return false;
    if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1) return true;
    try {
        $u = db()->fetchOne("SELECT is_admin FROM users WHERE id = ?", [$_SESSION['user_id']]);
        if ($u && $u['is_admin'] == 1) {
            $_SESSION['is_admin'] = 1;
            return true;
        }
    } catch (Throwable $e) {}
    return false;
}

function isVendor() {
    if (!isLoggedIn()) return false;
    if (isSuperAdmin()) return true;
    if (isset($_SESSION['is_vendor']) && $_SESSION['is_vendor'] == 1) return true;
    try {
        $u = db()->fetchOne(
            "SELECT is_admin, is_vendor, is_staff FROM users WHERE id = ?",
            [$_SESSION['user_id']]
        );
        if ($u) {
            $_SESSION['is_admin']  = (int)($u['is_admin'] ?? 0);
            $_SESSION['is_vendor'] = (int)($u['is_vendor'] ?? 0);
            $_SESSION['is_staff']  = (int)($u['is_staff'] ?? 0);
            if ($u['is_admin'] == 1 && $u['is_vendor'] == 1 && $u['is_staff'] == 1) {
                $_SESSION['is_super_admin'] = 1;
                return true;
            }
            if ($u['is_vendor'] == 1) return true;
        }
    } catch (Throwable $e) {}
    return false;
}

function isStaff() {
    if (!isLoggedIn()) return false;
    if (isSuperAdmin()) return true;
    if (isset($_SESSION['is_staff']) && $_SESSION['is_staff'] == 1) return true;
    try {
        $u = db()->fetchOne(
            "SELECT is_admin, is_vendor, is_staff FROM users WHERE id = ?",
            [$_SESSION['user_id']]
        );
        if ($u) {
            $_SESSION['is_admin']  = (int)($u['is_admin'] ?? 0);
            $_SESSION['is_vendor'] = (int)($u['is_vendor'] ?? 0);
            $_SESSION['is_staff']  = (int)($u['is_staff'] ?? 0);
            if ($u['is_staff'] == 1) return true;
        }
    } catch (Throwable $e) {}
    return false;
}

function getUserRole() {
    if (!isLoggedIn()) return 'guest';
    if (isSuperAdmin()) return 'super_admin';
    if (isAdmin()) return 'admin';
    if (isVendor()) return 'vendor';
    if (isStaff()) return 'staff';
    return 'user';
}

// ============================================
// USER & VENDOR LOOKUPS
// ============================================

function getUser() {
    if (!isLoggedIn()) return null;
    try {
        return db()->fetchOne("SELECT * FROM users WHERE id = ?", [$_SESSION['user_id']]);
    } catch (Throwable $e) { return null; }
}

function getUserById($id) {
    try {
        return db()->fetchOne("SELECT * FROM users WHERE id = ?", [$id]);
    } catch (Throwable $e) { return null; }
}

function getVendor() {
    if (!isLoggedIn()) return null;
    try {
        $db = db();
        $vendor = $db->fetchOne(
            "SELECT * FROM vendors WHERE user_id = ? LIMIT 1",
            [$_SESSION['user_id']]
        );
        if ($vendor) return $vendor;

        if (isVendor()) {
            $companyName = trim(($_SESSION['first_name'] ?? 'Vendor') . ' Business');
            if (empty($companyName)) $companyName = 'Vendor Business';
            $slug = slugify($companyName) . '-' . $_SESSION['user_id'];
            $existing = $db->fetchOne("SELECT id FROM vendors WHERE slug = ?", [$slug]);
            if ($existing) $slug .= '-' . bin2hex(random_bytes(2));

            $db->query(
                "INSERT INTO vendors (user_id, company_name, slug, business_email, business_phone, status)
                 VALUES (?, ?, ?, ?, ?, 'active')",
                [$_SESSION['user_id'], $companyName, $slug, $_SESSION['email'] ?? '', '']
            );

            return $db->fetchOne(
                "SELECT * FROM vendors WHERE user_id = ? LIMIT 1",
                [$_SESSION['user_id']]
            );
        }
        return null;
    } catch (Throwable $e) {
        error_log("getVendor error: " . $e->getMessage());
        return null;
    }
}

function getVendorById($vendorId) {
    try {
        return db()->fetchOne("SELECT * FROM vendors WHERE id = ?", [$vendorId]);
    } catch (Throwable $e) { return null; }
}

// ============================================
// LOGIN / LOGOUT / REGISTER
// ============================================

function login($email, $password) {
    try {
        $db = db();
        $email = strtolower(trim($email));
        $user = $db->fetchOne(
            "SELECT * FROM users WHERE LOWER(email) = ? LIMIT 1",
            [$email]
        );
        if (!$user) return false;
        if (strtolower($user['status'] ?? 'active') !== 'active') return false;
        if (!password_verify($password, $user['password_hash'] ?? '')) return false;

        $_SESSION['user_id']    = (int)$user['id'];
        $_SESSION['first_name'] = $user['first_name'] ?? '';
        $_SESSION['last_name']  = $user['last_name'] ?? '';
        $_SESSION['email']      = $user['email'] ?? '';
        $_SESSION['is_vendor']  = (int)($user['is_vendor'] ?? 0);
        $_SESSION['is_admin']   = (int)($user['is_admin'] ?? 0);
        $_SESSION['is_staff']   = (int)($user['is_staff'] ?? 0);
        $_SESSION['is_super_admin'] = (
            $_SESSION['is_admin'] == 1 &&
            $_SESSION['is_vendor'] == 1 &&
            $_SESSION['is_staff'] == 1
        ) ? 1 : 0;
        $_SESSION['role'] = getUserRole();

        try { $db->query("UPDATE users SET last_login = NOW() WHERE id = ?", [$user['id']]); }
        catch (Throwable $e) {}
        return true;
    } catch (Throwable $e) {
        error_log("login error: " . $e->getMessage());
        return false;
    }
}

function logout() {
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]);
    }
    session_destroy();
    return true;
}

function registerUser($data) {
    try {
        $db = db();
        $email = strtolower(trim($data['email']));
        $exists = $db->fetchOne("SELECT id FROM users WHERE LOWER(email) = ?", [$email]);
        if ($exists) return ['success' => false, 'message' => 'Email already registered'];

        $hash = password_hash($data['password'], PASSWORD_DEFAULT);
        $userId = $db->insert(
            "INSERT INTO users (first_name, last_name, email, phone, password_hash, is_vendor, is_admin, is_staff, status)
             VALUES (?, ?, ?, ?, ?, ?, 0, ?, 'active')",
            [
                trim($data['first_name'] ?? ''),
                trim($data['last_name'] ?? ''),
                $email,
                trim($data['phone'] ?? ''),
                $hash,
                !empty($data['is_vendor']) ? 1 : 0,
                !empty($data['is_staff']) ? 1 : 0,
            ]
        );
        if (!$userId) return ['success' => false, 'message' => 'Registration failed'];

        if (!empty($data['is_vendor'])) {
            try {
                $companyName = $data['company_name'] ?? ($data['first_name'] . "'s Business");
                $db->query(
                    "INSERT INTO vendors (user_id, company_name, slug, business_email, business_phone, status)
                     VALUES (?, ?, ?, ?, ?, 'active')",
                    [$userId, $companyName, slugify($companyName) . '-' . $userId, $email, $data['phone'] ?? '']
                );
            } catch (Throwable $e) {}
        }
        return ['success' => true, 'user_id' => $userId];
    } catch (Throwable $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

// ============================================
// BOOKINGS
// ============================================

function getUserBookings($userId) {
    if (!$userId) return [];
    try {
        return db()->fetchAll(
            "SELECT b.*, p.name as property_name, p.slug as property_slug,
                (SELECT file_path FROM property_media WHERE property_id = b.property_id AND is_primary = 1 LIMIT 1) as image
             FROM bookings b
             LEFT JOIN properties p ON b.property_id = p.id
             WHERE b.user_id = ?
             ORDER BY b.created_at DESC",
            [$userId]
        );
    } catch (Throwable $e) { return []; }
}

function getVendorBookings($vendorId, $filters = []) {
    if (!$vendorId) return [];
    try {
        $db = db();
        $sql = "SELECT b.*, p.name as property_name, u.first_name, u.last_name, rt.name as room_name
                FROM bookings b
                LEFT JOIN properties p ON b.property_id = p.id
                LEFT JOIN users u ON b.user_id = u.id
                LEFT JOIN room_types rt ON b.room_type_id = rt.id
                WHERE b.vendor_id = ?";
        $params = [$vendorId];

        if (!empty($filters['status'])) {
            $sql .= " AND b.status = ?";
            $params[] = $filters['status'];
        }
        if (!empty($filters['property_id'])) {
            $sql .= " AND b.property_id = ?";
            $params[] = $filters['property_id'];
        }
        $sql .= " ORDER BY b.created_at DESC";
        if (!empty($filters['limit'])) {
            $sql .= " LIMIT " . intval($filters['limit']);
        }
        return $db->fetchAll($sql, $params);
    } catch (Throwable $e) { return []; }
}

function getBooking($id) {
    if (!$id) return null;
    try {
        return db()->fetchOne(
            "SELECT b.*, p.name as property_name, p.slug as property_slug,
                u.first_name, u.last_name, u.email, rt.name as room_name
             FROM bookings b
             LEFT JOIN properties p ON b.property_id = p.id
             LEFT JOIN users u ON b.user_id = u.id
             LEFT JOIN room_types rt ON b.room_type_id = rt.id
             WHERE b.id = ?",
            [$id]
        );
    } catch (Throwable $e) { return null; }
}

function updateBookingStatus($id, $status) {
    try {
        return db()->query("UPDATE bookings SET status = ? WHERE id = ?", [$status, $id]);
    } catch (Throwable $e) { return false; }
}

function cancelBooking($id, $reason = '') {
    try {
        return db()->query(
            "UPDATE bookings SET status = 'cancelled', cancellation_reason = ? WHERE id = ?",
            [$reason, $id]
        );
    } catch (Throwable $e) { return false; }
}

// ============================================
// PROPERTIES
// ============================================

function getPropertyById($id) {
    try { return db()->fetchOne("SELECT * FROM properties WHERE id = ?", [$id]); }
    catch (Throwable $e) { return null; }
}

function getProperty($slug) {
    try { return db()->fetchOne("SELECT * FROM properties WHERE slug = ? AND is_active = 1", [$slug]); }
    catch (Throwable $e) { return null; }
}

function getRoomType($id) {
    try { return db()->fetchOne("SELECT * FROM room_types WHERE id = ?", [$id]); }
    catch (Throwable $e) { return null; }
}

function getRoomTypes($propertyId) {
    try {
        return db()->fetchAll(
            "SELECT * FROM room_types WHERE property_id = ? AND is_active = 1 ORDER BY base_price ASC",
            [$propertyId]
        );
    } catch (Throwable $e) { return []; }
}

function getVendorProperties($vendorId) {
    try {
        return db()->fetchAll(
            "SELECT p.*, c.name as category_name,
                (SELECT file_path FROM property_media WHERE property_id = p.id AND is_primary = 1 LIMIT 1) as image
             FROM properties p
             LEFT JOIN categories c ON p.category_id = c.id
             WHERE p.vendor_id = ?
             ORDER BY p.created_at DESC",
            [$vendorId]
        );
    } catch (Throwable $e) { return []; }
}

function getProperties($filters = []) {
    try {
        $db = db();

        $sql = "SELECT p.*, c.name AS category_name,
                       ct.name AS city_name,
                       co.name AS country_name, co.flag_emoji,
                       (SELECT file_path FROM property_media
                         WHERE property_id = p.id AND is_primary = 1
                         LIMIT 1) AS image
                FROM properties p
                LEFT JOIN categories c   ON p.category_id  = c.id
                LEFT JOIN destinations ct ON p.city_id    = ct.id
                LEFT JOIN destinations co ON p.country_id = co.id
                WHERE p.is_active = 1
                  AND p.status = 'published'";
        $params = [];

        if (!empty($filters['search'])) {
            $s = '%' . $filters['search'] . '%';
            $sql .= " AND (
                        p.name LIKE ?
                     OR p.short_description LIKE ?
                     OR p.description LIKE ?
                     OR ct.name LIKE ?
                     OR co.name LIKE ?
                     OR p.address_line1 LIKE ?
                     OR p.address LIKE ?
                      )";
            for ($i = 0; $i < 7; $i++) $params[] = $s;
        }

        if (!empty($filters['category'])) {
            $sql .= " AND p.category_id = ?";
            $params[] = (int)$filters['category'];
        }

        if (!empty($filters['country'])) {
            $countryId = (int)$filters['country'];
            $country = null;
            if ($countryId > 0) {
                try {
                    $country = $db->fetchOne(
                        "SELECT id, country_code FROM destinations
                         WHERE id = ? AND type = 'country' LIMIT 1",
                        [$countryId]
                    );
                } catch (Throwable $e) {}
            }

            if ($country) {
                $code = $country['country_code'] ?? '';
                if ($code !== '') {
                    $sql .= " AND (
                                p.country_id = ?
                             OR co.country_code = ?
                             OR p.city_id IN (
                                   SELECT id FROM destinations
                                   WHERE type = 'city'
                                     AND (parent_id = ? OR country_code = ?)
                                )
                              )";
                    $params[] = $countryId;
                    $params[] = $code;
                    $params[] = $countryId;
                    $params[] = $code;
                } else {
                    $sql .= " AND (
                                p.country_id = ?
                             OR p.city_id IN (
                                   SELECT id FROM destinations
                                   WHERE type = 'city' AND parent_id = ?
                                )
                              )";
                    $params[] = $countryId;
                    $params[] = $countryId;
                }
            } else {
                $sql .= " AND p.country_id = ?";
                $params[] = $countryId;
            }
        }

        if (!empty($filters['city'])) {
            if (is_numeric($filters['city'])) {
                $sql .= " AND p.city_id = ?";
                $params[] = (int)$filters['city'];
            } else {
                $sql .= " AND ct.name = ?";
                $params[] = (string)$filters['city'];
            }
        }

        if (isset($filters['min_price']) && $filters['min_price'] !== '' && $filters['min_price'] !== null) {
            if ((float)$filters['min_price'] > 0) {
                $sql .= " AND p.min_price_per_night >= ?";
                $params[] = (float)$filters['min_price'];
            }
        }
        if (isset($filters['max_price']) && $filters['max_price'] !== '' && $filters['max_price'] !== null) {
            if ((float)$filters['max_price'] > 0 && (float)$filters['max_price'] < 100000) {
                $sql .= " AND p.min_price_per_night <= ?";
                $params[] = (float)$filters['max_price'];
            }
        }

        if (!empty($filters['star_rating'])) {
            $sql .= " AND p.star_rating >= ?";
            $params[] = (int)$filters['star_rating'];
        }

        if (!empty($filters['instant_book'])) {
            $sql .= " AND p.is_instant_bookable = 1";
        }

        $sort = $filters['sort'] ?? 'relevance';
        switch ($sort) {
            case 'price_asc':  $sql .= " ORDER BY p.min_price_per_night ASC, p.id DESC"; break;
            case 'price_desc': $sql .= " ORDER BY p.min_price_per_night DESC, p.id DESC"; break;
            case 'rating':     $sql .= " ORDER BY p.average_rating DESC, p.total_reviews DESC"; break;
            case 'popularity': $sql .= " ORDER BY p.booking_count DESC, p.views_count DESC"; break;
            case 'newest':     $sql .= " ORDER BY p.created_at DESC"; break;
            case 'relevance':
            default:           $sql .= " ORDER BY p.is_featured DESC, p.average_rating DESC, p.created_at DESC";
        }

        $limit = !empty($filters['limit']) ? (int)$filters['limit'] : 60;
        if ($limit < 1)   $limit = 60;
        if ($limit > 500) $limit = 500;
        $sql .= " LIMIT " . $limit;

        $rows = $db->fetchAll($sql, $params);
        if (!is_array($rows)) $rows = [];

        if (empty($rows) && !empty($filters['search'])) {
            $s = '%' . $filters['search'] . '%';
            $fallback = "
                SELECT p.*, c.name AS category_name,
                       ct.name AS city_name,
                       co.name AS country_name, co.flag_emoji,
                       (SELECT file_path FROM property_media
                         WHERE property_id = p.id AND is_primary = 1
                         LIMIT 1) AS image
                FROM properties p
                LEFT JOIN categories c   ON p.category_id  = c.id
                LEFT JOIN destinations ct ON p.city_id    = ct.id
                LEFT JOIN destinations co ON p.country_id = co.id
                WHERE p.is_active = 1
                  AND (LOWER(p.name) LIKE LOWER(?)
                    OR LOWER(p.description) LIKE LOWER(?)
                    OR LOWER(ct.name) LIKE LOWER(?)
                    OR LOWER(co.name) LIKE LOWER(?))
                ORDER BY p.is_featured DESC, p.average_rating DESC
                LIMIT 100";
            $rows = $db->fetchAll($fallback, [$s, $s, $s, $s]);
            if (!is_array($rows)) $rows = [];
        }

        return $rows;

    } catch (Throwable $e) {
        error_log('getProperties() failed: ' . $e->getMessage());
        return [];
    }
}

function getPropertyImages($propertyId) {
    try {
        return db()->fetchAll(
            "SELECT * FROM property_media WHERE property_id = ? ORDER BY is_primary DESC, display_order ASC",
            [$propertyId]
        );
    } catch (Throwable $e) { return []; }
}

function getFeaturedProperties($limit = 6) {
    try {
        return db()->fetchAll(
            "SELECT p.*,
                (SELECT file_path FROM property_media WHERE property_id = p.id AND is_primary = 1 LIMIT 1) as image
             FROM properties p
             WHERE p.is_active = 1 AND p.is_featured = 1 AND p.status = 'published'
             ORDER BY p.created_at DESC
             LIMIT " . intval($limit)
        );
    } catch (Throwable $e) { return []; }
}

// ============================================
// WISHLIST
// ============================================

function toggleWishlist($userId, $propertyId) {
    if (!$userId || !$propertyId) return 'error';
    try {
        $db = db();
        $exists = $db->fetchOne(
            "SELECT id FROM wishlists WHERE user_id = ? AND property_id = ?",
            [$userId, $propertyId]
        );
        if ($exists) {
            $db->query("DELETE FROM wishlists WHERE id = ?", [$exists['id']]);
            return 'removed';
        }
        $db->query(
            "INSERT INTO wishlists (user_id, property_id) VALUES (?, ?)",
            [$userId, $propertyId]
        );
        return 'added';
    } catch (Throwable $e) { return 'error'; }
}

function getWishlist($userId) {
    if (!$userId) return [];
    try {
        return db()->fetchAll(
            "SELECT w.*, p.name, p.slug, p.min_price_per_night,
                (SELECT file_path FROM property_media WHERE property_id = p.id AND is_primary = 1 LIMIT 1) as image
             FROM wishlists w
             LEFT JOIN properties p ON w.property_id = p.id
             WHERE w.user_id = ?
             ORDER BY w.created_at DESC",
            [$userId]
        );
    } catch (Throwable $e) { return []; }
}

// ============================================
// NOTIFICATIONS
// ============================================

function createNotification($userId, $type, $title, $message, $link = null, $icon = null) {
    try {
        return db()->insert(
            "INSERT INTO notifications (user_id, type, title, message, link, icon, is_read)
             VALUES (?, ?, ?, ?, ?, ?, 0)",
            [$userId, $type, $title, $message, $link, $icon]
        );
    } catch (Throwable $e) { return false; }
}

function getNotifications($userId, $limit = 20) {
    try {
        return db()->fetchAll(
            "SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT " . intval($limit),
            [$userId]
        );
    } catch (Throwable $e) { return []; }
}

function getUnreadNotifications($userId) {
    try {
        return db()->fetchAll(
            "SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC",
            [$userId]
        );
    } catch (Throwable $e) { return []; }
}

function markNotificationRead($id, $userId) {
    try {
        return db()->query(
            "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ? AND user_id = ?",
            [$id, $userId]
        );
    } catch (Throwable $e) { return false; }
}

function markAllNotificationsRead($userId) {
    try {
        return db()->query(
            "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0",
            [$userId]
        );
    } catch (Throwable $e) { return false; }
}

// ============================================
// STAFF & SUBSCRIPTION
// ============================================

function getVendorSubscription($vendorId) {
    try {
        $sub = db()->fetchOne(
            "SELECT * FROM vendor_subscriptions
             WHERE vendor_id = ? AND status = 'active'
             ORDER BY created_at DESC LIMIT 1",
            [$vendorId]
        );
        if ($sub) return $sub;
    } catch (Throwable $e) {}

    return [
        'id' => null, 'vendor_id' => $vendorId, 'plan' => 'trial',
        'max_staff' => 5, 'max_properties' => 3, 'max_rooms' => 20,
        'status' => 'active',
    ];
}

function getStaffMembers($vendorId) {
    try {
        return db()->fetchAll(
            "SELECT s.*, u.first_name, u.last_name, u.email, u.phone, r.name as role_name
             FROM staff_members s
             LEFT JOIN users u ON s.user_id = u.id
             LEFT JOIN staff_roles r ON s.role_id = r.id
             WHERE s.vendor_id = ?
             ORDER BY s.created_at DESC",
            [$vendorId]
        );
    } catch (Throwable $e) { return []; }
}

function getStaffRoles() {
    try {
        return db()->fetchAll("SELECT * FROM staff_roles ORDER BY name");
    } catch (Throwable $e) {
        return [
            ['id' => 1, 'name' => 'Manager'],
            ['id' => 2, 'name' => 'Front Desk'],
            ['id' => 3, 'name' => 'Housekeeping'],
            ['id' => 4, 'name' => 'Maintenance'],
            ['id' => 5, 'name' => 'Restaurant'],
        ];
    }
}

function addStaffMember($vendorId, $userId, $roleId = null, $department = '', $position = '') {
    try {
        return db()->insert(
            "INSERT INTO staff_members (vendor_id, user_id, role_id, department, position, is_active)
             VALUES (?, ?, ?, ?, ?, 1)",
            [$vendorId, $userId, $roleId, $department, $position]
        );
    } catch (Throwable $e) { return false; }
}

function updateStaffMember($id, $data) {
    try {
        return db()->query(
            "UPDATE staff_members SET role_id = ?, department = ?, position = ?, is_active = ? WHERE id = ?",
            [
                $data['role_id'] ?? null,
                $data['department'] ?? '',
                $data['position'] ?? '',
                $data['is_active'] ?? 1,
                $id,
            ]
        );
    } catch (Throwable $e) { return false; }
}

function deleteStaffMember($id) {
    try {
        return db()->query("DELETE FROM staff_members WHERE id = ?", [$id]);
    } catch (Throwable $e) { return false; }
}

// ============================================
// UTILITIES
// ============================================

function redirect($url) {
    if (preg_match('#^https?://#i', $url)) {
        $finalUrl = $url;
    } elseif (strpos($url, '/') === 0) {
        $base = defined('SITE_URL') ? rtrim(SITE_URL, '/') : '';
        $finalUrl = $base . $url;
    } else {
        $base = defined('SITE_URL') ? rtrim(SITE_URL, '/') : '';
        $finalUrl = $base . '/' . ltrim($url, '/');
    }
    $finalUrl = preg_replace('#(?<!:)//+#', '/', $finalUrl);

    if (!headers_sent()) {
        header('Location: ' . $finalUrl, true, 302);
        exit;
    }
    echo '<script>window.location.href=' . json_encode($finalUrl) . ';</script>';
    exit;
}

function setMessage($text, $type = 'success') {
    $_SESSION['message'] = ['text' => $text, 'type' => $type];
}

function displayMessage() {
    if (isset($_SESSION['message'])) {
        $msg = $_SESSION['message'];
        unset($_SESSION['message']);
        return $msg;
    }
    return null;
}

function slugify($text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = @iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    return strtolower($text ?: 'item');
}

function formatCurrency($amount, $currency = null) {
    if ($currency === null) {
        $currency = defined('DEFAULT_CURRENCY') ? DEFAULT_CURRENCY : 'USD';
    }
    $symbols = ['USD' => '$', 'EUR' => '€', 'GBP' => '£', 'JPY' => '¥', 'TZS' => 'TSh ', 'KES' => 'KSh ', 'ZAR' => 'R '];
    $symbol = $symbols[$currency] ?? ($currency . ' ');
    return $symbol . number_format((float)$amount, 2);
}

function getUserCurrency() {
    if (isset($_SESSION['currency'])) return $_SESSION['currency'];
    return defined('DEFAULT_CURRENCY') ? DEFAULT_CURRENCY : 'USD';
}

function getCurrencySymbol($currency = null) {
    if ($currency === null) $currency = getUserCurrency();
    $symbols = ['USD' => '$', 'EUR' => '€', 'GBP' => '£', 'JPY' => '¥', 'TZS' => 'TSh'];
    return $symbols[$currency] ?? '$';
}

function getAvailableCurrencies() {
    return [
        ['code' => 'USD', 'name' => 'US Dollar', 'symbol' => '$', 'flag' => '🇺🇸'],
        ['code' => 'EUR', 'name' => 'Euro', 'symbol' => '€', 'flag' => '🇪🇺'],
        ['code' => 'GBP', 'name' => 'British Pound', 'symbol' => '£', 'flag' => '🇬🇧'],
        ['code' => 'TZS', 'name' => 'Tanzanian Shilling', 'symbol' => 'TSh', 'flag' => '🇹🇿'],
    ];
}

function generateStarRating($rating) {
    $rating = round((float)$rating, 1);
    $html = '';
    for ($i = 1; $i <= 5; $i++) {
        if ($i <= $rating) $html .= '<i class="fas fa-star" style="color:#f6ad55;"></i>';
        elseif ($i - 0.5 <= $rating) $html .= '<i class="fas fa-star-half-alt" style="color:#f6ad55;"></i>';
        else $html .= '<i class="far fa-star" style="color:#718096;"></i>';
    }
    return $html;
}

function getClientIP() {
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $key) {
        if (!empty($_SERVER[$key])) {
            return trim(explode(',', $_SERVER[$key])[0]);
        }
    }
    return '0.0.0.0';
}

function getAmenityIcon($amenity) {
    $icons = [
        'wifi' => 'fa-wifi', 'pool' => 'fa-swimming-pool', 'parking' => 'fa-parking',
        'air_conditioning' => 'fa-snowflake', 'breakfast' => 'fa-utensils',
        'gym' => 'fa-dumbbell', 'spa' => 'fa-spa', 'restaurant' => 'fa-utensils',
        'bar' => 'fa-glass-martini-alt', 'room_service' => 'fa-concierge-bell',
        'laundry' => 'fa-tshirt', 'pet_friendly' => 'fa-dog', 'family_rooms' => 'fa-users',
        'non_smoking' => 'fa-smoking-ban', '24h_front_desk' => 'fa-clock',
        'beach_access' => 'fa-umbrella-beach', 'water_sports' => 'fa-water',
        'tv' => 'fa-tv', 'minibar' => 'fa-wine-bottle', 'balcony' => 'fa-door-open',
    ];
    return $icons[$amenity] ?? 'fa-check-circle';
}

function getCategories() {
    try { return db()->fetchAll("SELECT * FROM categories WHERE is_active = 1 ORDER BY name"); }
    catch (Throwable $e) { return []; }
}

// ============================================================
// LOCATION HELPERS
// ============================================================

if (!function_exists('destinations_table_exists')) {
    function destinations_table_exists() {
        static $exists = null;
        if ($exists !== null) return $exists;
        try {
            $row = db()->fetchOne("SHOW TABLES LIKE 'destinations'");
            $exists = !empty($row);
        } catch (Throwable $e) {
            $exists = false;
        }
        return $exists;
    }
}

if (!function_exists('getAllCountries')) {
    function getAllCountries() {
        static $cache = null;
        if ($cache !== null) return $cache;
        try {
            if (!destinations_table_exists()) {
                $cache = db()->fetchAll(
                    "SELECT id, name, code AS country_code, flag_emoji FROM countries ORDER BY name"
                ) ?: [];
                return $cache;
            }
            $cache = db()->fetchAll(
                "SELECT id, name, country_code, flag_emoji, continent
                 FROM destinations
                 WHERE type = 'country' AND is_active = 1
                 ORDER BY name ASC"
            ) ?: [];
        } catch (Throwable $e) {
            error_log('getAllCountries failed: ' . $e->getMessage());
            $cache = [];
        }
        return $cache;
    }
}

if (!function_exists('getAllCities')) {
    function getAllCities($countryId = null, $search = null, $limit = 3000) {
        try {
            if (!destinations_table_exists()) {
                $sql = "SELECT id, name, country_id FROM cities";
                $params = [];
                if ($countryId) { $sql .= " WHERE country_id = ?"; $params[] = $countryId; }
                $sql .= " ORDER BY name LIMIT " . (int)$limit;
                return db()->fetchAll($sql, $params) ?: [];
            }

            $sql = "SELECT ci.id, ci.name, ci.country_code, ci.country_name,
                           ci.parent_id, ci.latitude, ci.longitude, ci.population,
                           co.id AS country_id,
                           co.name AS parent_country_name
                    FROM destinations ci
                    LEFT JOIN destinations co
                      ON co.type = 'country'
                     AND (co.id = ci.parent_id OR co.country_code = ci.country_code)
                    WHERE ci.type = 'city' AND ci.is_active = 1";
            $params = [];

            if ($countryId) {
                $country = db()->fetchOne(
                    "SELECT id, country_code FROM destinations
                     WHERE id = ? AND type = 'country' LIMIT 1",
                    [$countryId]
                );

                if ($country && !empty($country['country_code'])) {
                    $sql .= " AND (ci.parent_id = ? OR ci.country_code = ? OR co.id = ?)";
                    $params[] = (int)$countryId;
                    $params[] = $country['country_code'];
                    $params[] = (int)$countryId;
                } else {
                    $sql .= " AND (ci.parent_id = ? OR co.id = ?)";
                    $params[] = (int)$countryId;
                    $params[] = (int)$countryId;
                }
            }

            if ($search !== null && $search !== '') {
                $sql .= " AND ci.name LIKE ?";
                $params[] = '%' . $search . '%';
            }

            $sql .= " ORDER BY ci.population DESC, ci.name ASC LIMIT " . (int)$limit;
            return db()->fetchAll($sql, $params) ?: [];

        } catch (Throwable $e) {
            error_log('getAllCities failed: ' . $e->getMessage());
            return [];
        }
    }
}

if (!function_exists('getCountryById')) {
    function getCountryById($id) {
        try {
            if (destinations_table_exists()) {
                return db()->fetchOne(
                    "SELECT id, name, country_code, flag_emoji, continent
                     FROM destinations WHERE id = ? AND type = 'country' LIMIT 1",
                    [$id]
                ) ?: null;
            }
            return db()->fetchOne(
                "SELECT id, name, code AS country_code FROM countries WHERE id = ? LIMIT 1",
                [$id]
            ) ?: null;
        } catch (Throwable $e) { return null; }
    }
}

if (!function_exists('getCityById')) {
    function getCityById($id) {
        try {
            if (destinations_table_exists()) {
                return db()->fetchOne(
                    "SELECT id, name, country_code, country_name, parent_id,
                            latitude, longitude
                     FROM destinations WHERE id = ? AND type = 'city' LIMIT 1",
                    [$id]
                ) ?: null;
            }
            return db()->fetchOne(
                "SELECT id, name, country_id FROM cities WHERE id = ? LIMIT 1",
                [$id]
            ) ?: null;
        } catch (Throwable $e) { return null; }
    }
}

if (!function_exists('getCityParentCountry')) {
    function getCityParentCountry($cityId) {
        try {
            if (!destinations_table_exists()) return null;
            $city = db()->fetchOne(
                "SELECT id, parent_id, country_code FROM destinations
                 WHERE id = ? AND type = 'city' LIMIT 1",
                [$cityId]
            );
            if (!$city) return null;

            if (!empty($city['parent_id'])) {
                $c = db()->fetchOne(
                    "SELECT id, name, country_code FROM destinations
                     WHERE id = ? AND type = 'country' LIMIT 1",
                    [$city['parent_id']]
                );
                if ($c) return $c;
            }
            if (!empty($city['country_code'])) {
                return db()->fetchOne(
                    "SELECT id, name, country_code FROM destinations
                     WHERE country_code = ? AND type = 'country' LIMIT 1",
                    [$city['country_code']]
                ) ?: null;
            }
            return null;
        } catch (Throwable $e) { return null; }
    }
}

if (!function_exists('resolveLocationFromSearch')) {
    function resolveLocationFromSearch($term) {
        $term = trim((string)$term);
        if ($term === '') return null;
        try {
            if (!destinations_table_exists()) return null;

            $city = db()->fetchOne(
                "SELECT id, name, parent_id, country_code, country_name
                 FROM destinations
                 WHERE type = 'city' AND is_active = 1 AND name = ?
                 LIMIT 1",
                [$term]
            );

            if (!$city) {
                $city = db()->fetchOne(
                    "SELECT id, name, parent_id, country_code, country_name
                     FROM destinations
                     WHERE type = 'city' AND is_active = 1 AND name LIKE ?
                     ORDER BY population DESC LIMIT 1",
                    ['%' . $term . '%']
                );
            }

            $country = db()->fetchOne(
                "SELECT id, name, country_code
                 FROM destinations
                 WHERE type = 'country' AND is_active = 1
                   AND (name = ? OR name LIKE ?)
                 ORDER BY (name = ?) DESC LIMIT 1",
                [$term, '%' . $term . '%', $term]
            );

            if ($city && !$country) {
                $country = getCityParentCountry((int)$city['id']);
            }

            return ['city' => $city, 'country' => $country];
        } catch (Throwable $e) {
            return null;
        }
    }
}

if (!function_exists('searchDestinations')) {
    function searchDestinations($q, $limit = 20) {
        $q = trim((string)$q);
        if ($q === '') return [];
        try {
            if (!destinations_table_exists()) {
                return db()->fetchAll(
                    "SELECT id, name, 'country' AS type FROM countries WHERE name LIKE ? LIMIT " . (int)$limit,
                    ['%' . $q . '%']
                ) ?: [];
            }
            return db()->fetchAll(
                "SELECT id, name, type, country_code, country_name, flag_emoji, population
                 FROM destinations
                 WHERE is_active = 1 AND name LIKE ?
                 ORDER BY
                    CASE type WHEN 'country' THEN 1 WHEN 'city' THEN 2 ELSE 3 END,
                    popularity_score DESC,
                    population DESC
                 LIMIT " . (int)$limit,
                ['%' . $q . '%']
            ) ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('getCountries')) {
    function getCountries() {
        return getAllCountries();
    }
}

if (!function_exists('getCities')) {
    function getCities($countryId = null) {
        return getAllCities($countryId, null, 3000);
    }
}

if (!function_exists('diagnoseLocationData')) {
    function diagnoseLocationData() {
        $out = [
            'total_countries'      => 0,
            'total_cities'         => 0,
            'cities_with_parent'   => 0,
            'cities_with_code'     => 0,
            'cities_linked_any'    => 0,
            'sample_countries'     => [],
            'sample_cities'        => [],
            'sample_orphan_cities' => [],
        ];

        try {
            if (!destinations_table_exists()) {
                $out['error'] = 'destinations table does not exist';
                return $out;
            }

            $db = db();

            $out['total_countries'] = (int)($db->fetchOne(
                "SELECT COUNT(*) AS c FROM destinations WHERE type='country' AND is_active=1"
            )['c'] ?? 0);

            $out['total_cities'] = (int)($db->fetchOne(
                "SELECT COUNT(*) AS c FROM destinations WHERE type='city' AND is_active=1"
            )['c'] ?? 0);

            $out['cities_with_parent'] = (int)($db->fetchOne(
                "SELECT COUNT(*) AS c FROM destinations
                 WHERE type='city' AND is_active=1 AND parent_id IS NOT NULL"
            )['c'] ?? 0);

            $out['cities_with_code'] = (int)($db->fetchOne(
                "SELECT COUNT(*) AS c FROM destinations
                 WHERE type='city' AND is_active=1 AND country_code IS NOT NULL AND country_code != ''"
            )['c'] ?? 0);

            $out['cities_linked_any'] = (int)($db->fetchOne(
                "SELECT COUNT(*) AS c FROM destinations ci
                 WHERE ci.type='city' AND ci.is_active=1
                   AND (ci.parent_id IS NOT NULL OR (ci.country_code IS NOT NULL AND ci.country_code != ''))
                "
            )['c'] ?? 0);

            $out['sample_countries'] = $db->fetchAll(
                "SELECT id, name, country_code FROM destinations
                 WHERE type='country' AND is_active=1
                 ORDER BY name LIMIT 10"
            ) ?: [];

            $out['sample_cities'] = $db->fetchAll(
                "SELECT id, name, parent_id, country_code, country_name
                 FROM destinations
                 WHERE type='city' AND is_active=1
                 ORDER BY RAND() LIMIT 10"
            ) ?: [];

            $out['sample_orphan_cities'] = $db->fetchAll(
                "SELECT id, name, parent_id, country_code, country_name
                 FROM destinations
                 WHERE type='city' AND is_active=1
                   AND parent_id IS NULL
                   AND (country_code IS NULL OR country_code = '')
                 LIMIT 10"
            ) ?: [];

        } catch (Throwable $e) {
            $out['error'] = $e->getMessage();
        }

        return $out;
    }
}

// ============================================
// REVIEWS
// ============================================

function getAverageRating($propertyId) {
    try {
        $r = db()->fetchOne(
            "SELECT AVG(rating) as avg_rating, COUNT(*) as total FROM reviews WHERE property_id = ?",
            [$propertyId]
        );
        return ['average' => round((float)($r['avg_rating'] ?? 0), 2), 'total' => (int)($r['total'] ?? 0)];
    } catch (Throwable $e) { return ['average' => 0, 'total' => 0]; }
}

function getPropertyReviews($propertyId, $limit = 10) {
    try {
        return db()->fetchAll(
            "SELECT r.*, u.first_name, u.last_name
             FROM reviews r LEFT JOIN users u ON r.user_id = u.id
             WHERE r.property_id = ?
             ORDER BY r.created_at DESC LIMIT " . intval($limit),
            [$propertyId]
        );
    } catch (Throwable $e) { return []; }
}

function getRatingDistribution($propertyId) {
    try {
        $rows = db()->fetchAll(
            "SELECT rating, COUNT(*) as count FROM reviews WHERE property_id = ? GROUP BY rating",
            [$propertyId]
        );
        $dist = [5 => 0, 4 => 0, 3 => 0, 2 => 0, 1 => 0];
        foreach ($rows as $r) {
            $rating = (int)$r['rating'];
            if ($rating >= 1 && $rating <= 5) $dist[$rating] = (int)$r['count'];
        }
        return $dist;
    } catch (Throwable $e) { return [5 => 0, 4 => 0, 3 => 0, 2 => 0, 1 => 0]; }
}

function getStatusBadge($status) {
    $colors = ['pending' => 'warning', 'confirmed' => 'info', 'checked_in' => 'primary', 'checked_out' => 'success', 'completed' => 'success', 'cancelled' => 'danger'];
    $color = $colors[$status] ?? 'secondary';
    return '<span class="badge badge-' . $color . '">' . ucfirst(str_replace('_', ' ', $status)) . '</span>';
}

// ============================================================
// PROPERTY IMAGE
// ============================================================
// Storage convention:
//   Disk:  /uploads/properties/filename.jpg     (flat)
//   DB:    properties/filename.jpg
//   URL:   /uploads/properties/filename.jpg
// ============================================================

function getPropertyImageUrl($property) {
    // 1. Try pre-fetched image columns
    $candidate = $property['image']          ?? null;
    if (!$candidate || $candidate === '0') $candidate = $property['featured_image'] ?? null;
    if (!$candidate || $candidate === '0') $candidate = $property['primary_image']  ?? null;

    // 2. Fall back to property_media
    if ((!$candidate || $candidate === '0') && !empty($property['id'])) {
        try {
            $row = db()->fetchOne(
                "SELECT file_path FROM property_media
                 WHERE property_id = ?
                 ORDER BY is_primary DESC, display_order ASC, id ASC
                 LIMIT 1",
                [$property['id']]
            );
            if ($row && !empty($row['file_path'])) $candidate = $row['file_path'];
        } catch (Throwable $e) {}
    }

    // 3. Normalize
    if ($candidate && $candidate !== '0') {
        if (strpos($candidate, 'http') === 0) return $candidate;

        $clean = ltrim($candidate, '/');

        // Already full
        if (strpos($clean, 'uploads/') === 0) return '/' . $clean;

        // "properties/xxx.jpg" — flat format (what we store)
        if (strpos($clean, 'properties/') === 0) {
            // Tolerate legacy "properties/12345/xxx.jpg" by stripping the middle folder
            if (preg_match('#^properties/\d+/(.+)$#', $clean, $m)) {
                return '/uploads/properties/' . $m[1];
            }
            return '/uploads/' . $clean;
        }

        // Bare filename
        return '/uploads/properties/' . basename($clean);
    }

    return generatePropertyPlaceholder($property);
}

function generatePropertyPlaceholder($property) {
    $category = trim((string)(
        $property['property_type'] ?? $property['category_slug'] ?? $property['category_name'] ?? 'hotel'
    ));
    $category = strtolower($category);

    $categoryLabels = [
        'hotels' => 'HOTEL', 'resorts' => 'RESORT', 'villas' => 'VILLA',
        'luxury-villas' => 'LUXURY VILLA', 'beach-villas' => 'BEACH VILLA',
        'serviced-apartments' => 'APARTMENTS', 'apartments' => 'APARTMENTS',
        'hostels' => 'HOSTEL', 'lodges' => 'LODGE', 'eco-lodges' => 'ECO LODGE',
        'camps' => 'CAMP', 'bed-breakfast' => 'B&B', 'bnb' => 'B&B',
        'boutique-hotels' => 'BOUTIQUE', 'city-hotels' => 'CITY HOTEL',
        'business-hotels' => 'BUSINESS HOTEL', 'airport-hotels' => 'AIRPORT HOTEL',
        'beach-resorts' => 'BEACH RESORT', 'ski-resorts' => 'SKI RESORT',
        'wellness-resorts' => 'WELLNESS', 'guesthouse' => 'GUESTHOUSE',
        'guest_house' => 'GUESTHOUSE', 'motel' => 'MOTEL', 'chalet' => 'CHALET',
        'apartment' => 'APARTMENT', 'resort' => 'RESORT', 'hotel' => 'HOTEL',
        'hostel' => 'HOSTEL', 'lodge' => 'LODGE', 'camp' => 'CAMP', 'villa' => 'VILLA',
    ];
    $label = $categoryLabels[$category] ?? 'STAY';
    $city = mb_strtoupper(mb_substr(trim((string)($property['city_name'] ?? '')), 0, 22));
    $country = mb_strtoupper(mb_substr(trim((string)($property['country_name'] ?? '')), 0, 18));

    $gradients = [
        'hotels' => ['#667eea', '#764ba2'], 'resorts' => ['#00d4ff', '#00b894'],
        'villas' => ['#f093fb', '#f5576c'], 'luxury-villas' => ['#ffd700', '#f6ad55'],
        'beach-villas' => ['#00d4ff', '#00b894'], 'serviced-apartments' => ['#b794f4', '#667eea'],
        'apartments' => ['#b794f4', '#667eea'], 'hostels' => ['#f6ad55', '#ed8936'],
        'lodges' => ['#00b894', '#667eea'], 'eco-lodges' => ['#00b894', '#a3bffa'],
        'camps' => ['#f6ad55', '#f5576c'], 'bed-breakfast' => ['#f5576c', '#b794f4'],
        'bnb' => ['#f5576c', '#b794f4'], 'boutique-hotels' => ['#f093fb', '#764ba2'],
        'city-hotels' => ['#667eea', '#00d4ff'], 'business-hotels' => ['#a3bffa', '#667eea'],
        'airport-hotels' => ['#00d4ff', '#a3bffa'], 'beach-resorts' => ['#00d4ff', '#00b894'],
        'ski-resorts' => ['#a3bffa', '#b794f4'], 'wellness-resorts' => ['#00b894', '#00d4ff'],
        'guesthouse' => ['#f6ad55', '#f5576c'], 'guest_house' => ['#f6ad55', '#f5576c'],
        'motel' => ['#667eea', '#764ba2'], 'chalet' => ['#b794f4', '#00d4ff'],
        'apartment' => ['#b794f4', '#667eea'], 'resort' => ['#00d4ff', '#00b894'],
        'hotel' => ['#667eea', '#764ba2'], 'hostel' => ['#f6ad55', '#ed8936'],
        'lodge' => ['#00b894', '#667eea'], 'camp' => ['#f6ad55', '#f5576c'],
        'villa' => ['#f093fb', '#f5576c'],
    ];
    [$c1, $c2] = $gradients[$category] ?? ['#667eea', '#764ba2'];

    $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice">'
         . '<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1">'
         . '<stop offset="0%" stop-color="' . $c1 . '"/>'
         . '<stop offset="100%" stop-color="' . $c2 . '"/>'
         . '</linearGradient></defs>'
         . '<rect width="800" height="600" fill="url(#g)"/>'
         . '<g opacity="0.06" stroke="#fff" stroke-width="1">'
         . '<line x1="0" y1="0" x2="800" y2="600"/>'
         . '<line x1="200" y1="0" x2="800" y2="450"/>'
         . '<line x1="400" y1="0" x2="800" y2="300"/>'
         . '<line x1="0" y1="150" x2="650" y2="600"/>'
         . '<line x1="0" y1="300" x2="500" y2="600"/>'
         . '<line x1="0" y1="450" x2="350" y2="600"/>'
         . '</g>'
         . '<text x="400" y="290" text-anchor="middle" fill="#ffffff" '
         . 'font-family="Arial,Helvetica,sans-serif" font-size="72" font-weight="900" '
         . 'letter-spacing="6" opacity="0.95">'
         . htmlspecialchars($label, ENT_XML1) . '</text>'
         . ($city !== ''
             ? '<text x="400" y="355" text-anchor="middle" fill="#ffffff" '
             . 'font-family="Arial,Helvetica,sans-serif" font-size="32" font-weight="700" '
             . 'letter-spacing="2" opacity="0.85">'
             . htmlspecialchars($city, ENT_XML1) . '</text>' : '')
         . ($country !== ''
             ? '<text x="400" y="395" text-anchor="middle" fill="#ffffff" '
             . 'font-family="Arial,Helvetica,sans-serif" font-size="18" font-weight="600" '
             . 'letter-spacing="3" opacity="0.6">'
             . htmlspecialchars($country, ENT_XML1) . '</text>' : '')
         . '<rect x="330" y="430" width="140" height="3" fill="#ffffff" opacity="0.4" rx="2"/>'
         . '</svg>';

    return 'data:image/svg+xml;base64,' . base64_encode($svg);
}

function getAmenityIconSafe($amenity) {
    return getAmenityIcon($amenity);
}

function safeStarRating($rating) {
    return generateStarRating($rating);
}

// ============================================
// DASHBOARD STATS
// ============================================

if (!function_exists('getDashboardStats')) {
    function getDashboardStats($vendorId) {
        try {
            $db = db();
            $today = date('Y-m-d');
            $monthStart = date('Y-m-01');
            return [
                'total_properties' => (int)($db->fetchOne("SELECT COUNT(*) as c FROM properties WHERE vendor_id = ? AND is_active = 1", [$vendorId])['c'] ?? 0),
                'total_bookings' => (int)($db->fetchOne("SELECT COUNT(*) as c FROM bookings WHERE vendor_id = ?", [$vendorId])['c'] ?? 0),
                'total_revenue' => (float)($db->fetchOne("SELECT COALESCE(SUM(total_amount),0) as t FROM bookings WHERE vendor_id = ? AND status IN ('completed','checked_out','confirmed','checked_in')", [$vendorId])['t'] ?? 0),
                'monthly_revenue' => (float)($db->fetchOne("SELECT COALESCE(SUM(total_amount),0) as t FROM bookings WHERE vendor_id = ? AND created_at >= ? AND status IN ('completed','checked_out','confirmed','checked_in')", [$vendorId, $monthStart])['t'] ?? 0),
                'pending' => (int)($db->fetchOne("SELECT COUNT(*) as c FROM bookings WHERE vendor_id = ? AND status = 'pending'", [$vendorId])['c'] ?? 0),
                'confirmed' => (int)($db->fetchOne("SELECT COUNT(*) as c FROM bookings WHERE vendor_id = ? AND status = 'confirmed'", [$vendorId])['c'] ?? 0),
                'checked_in' => (int)($db->fetchOne("SELECT COUNT(*) as c FROM bookings WHERE vendor_id = ? AND status = 'checked_in'", [$vendorId])['c'] ?? 0),
                'today_bookings' => (int)($db->fetchOne("SELECT COUNT(*) as c FROM bookings WHERE vendor_id = ? AND DATE(created_at) = ?", [$vendorId, $today])['c'] ?? 0),
                'balance' => 0, 'pending_balance' => 0,
            ];
        } catch (Throwable $e) {
            return ['total_properties' => 0, 'total_bookings' => 0, 'total_revenue' => 0, 'monthly_revenue' => 0, 'pending' => 0, 'confirmed' => 0, 'checked_in' => 0, 'today_bookings' => 0, 'balance' => 0, 'pending_balance' => 0];
        }
    }
}

if (!function_exists('getPropertyCount')) {
    function getPropertyCount($vendorId) {
        try {
            $r = db()->fetchOne("SELECT COUNT(*) as c FROM properties WHERE vendor_id = ? AND is_active = 1", [$vendorId]);
            return (int)($r['c'] ?? 0);
        } catch (Throwable $e) { return 0; }
    }
}

if (!function_exists('getBookingCount')) {
    function getBookingCount($vendorId) {
        try {
            $r = db()->fetchOne("SELECT COUNT(*) as c FROM bookings WHERE vendor_id = ?", [$vendorId]);
            return (int)($r['c'] ?? 0);
        } catch (Throwable $e) { return 0; }
    }
}

if (!function_exists('getVendorBalance')) {
    function getVendorBalance($vendorId) {
        try {
            $b = db()->fetchOne("SELECT * FROM vendor_balances WHERE vendor_id = ?", [$vendorId]);
            if ($b) return $b;
        } catch (Throwable $e) {}
        return ['balance' => 0, 'pending_balance' => 0, 'total_earned' => 0];
    }
}

if (!function_exists('getQuickAvailability')) {
    function getQuickAvailability($propertyId) {
        try {
            $roomTypes = getRoomTypes($propertyId);
            if (empty($roomTypes)) {
                $prop = getPropertyById($propertyId);
                return ['available' => true, 'next_available' => date('Y-m-d'), 'lowest_price' => (float)($prop['min_price_per_night'] ?? 0)];
            }
            $room = $roomTypes[0];
            return ['available' => true, 'next_available' => date('Y-m-d'), 'lowest_price' => (float)($room['base_price'] ?? 0)];
        } catch (Throwable $e) {
            return ['available' => true, 'next_available' => date('Y-m-d'), 'lowest_price' => 0];
        }
    }
}

if (!function_exists('searchAvailableProperties')) {
    function searchAvailableProperties($filters = []) {
        try {
            $properties = getProperties($filters);
            if (empty($properties)) return [];
            $result = [];
            foreach ($properties as $p) {
                $quick = getQuickAvailability($p['id']);
                $p['available']      = $quick['available'] ?? true;
                $p['next_available'] = $quick['next_available'] ?? null;
                $p['lowest_price']   = $quick['lowest_price'] ?? ($p['min_price_per_night'] ?? 0);
                $result[] = $p;
            }
            return $result;
        } catch (Throwable $e) {
            return getProperties($filters);
        }
    }
}

if (!function_exists('checkRoomAvailability')) {
    function checkRoomAvailability($roomTypeId, $checkIn, $checkOut, $rooms = 1) {
        try {
            $room = getRoomType($roomTypeId);
            if (!$room) return ['available' => false, 'message' => 'Room not found'];
            $nights = max(1, (strtotime($checkOut) - strtotime($checkIn)) / 86400);
            $price = (float)($room['base_price'] ?? 0);
            return ['available' => true, 'available_units' => (int)($room['total_units'] ?? 1), 'price_per_night' => $price, 'total_price' => $price * $nights * $rooms, 'nights' => $nights];
        } catch (Throwable $e) {
            return ['available' => true, 'nights' => 1, 'total_price' => 0];
        }
    }
}

if (!function_exists('checkAvailability')) {
    function checkAvailability($propertyId, $checkIn, $checkOut, $rooms = 1) {
        try {
            $roomTypes = getRoomTypes($propertyId);
            if (empty($roomTypes)) return ['available' => false, 'message' => 'No rooms', 'rooms' => []];
            $availableRooms = [];
            foreach ($roomTypes as $room) {
                $avail = checkRoomAvailability($room['id'], $checkIn, $checkOut, $rooms);
                if ($avail['available']) {
                    $availableRooms[] = array_merge($avail, ['room_id' => $room['id'], 'room_name' => $room['name']]);
                }
            }
            return ['available' => !empty($availableRooms), 'message' => empty($availableRooms) ? 'No rooms available' : count($availableRooms) . ' room types available', 'rooms' => $availableRooms, 'total_available' => count($availableRooms)];
        } catch (Throwable $e) {
            return ['available' => true, 'message' => 'Available', 'rooms' => [], 'total_available' => 0];
        }
    }
}

// ============================================================
// createProperty()
// ============================================================
if (!function_exists('createProperty')) {
    function createProperty(array $data): array {
        try {
            $allowed = [
                'vendor_id','slug','category_id','country_id','city_id','neighbourhood',
                'name','description','short_description','address_line1','postal_code',
                'latitude','longitude','star_rating','property_type','year_established',
                'min_price_per_night','max_price_per_night','high_season_rate','low_season_rate',
                'min_stay','currency','base_currency','check_in_time','check_out_time',
                'cancellation_policy','house_rules','amenities',
                'meta_title','meta_description','claim_status','status','is_active',
            ];

            if (empty($data['slug'])) {
                $data['slug'] = function_exists('slugify') ? slugify($data['name'] ?? 'property') : 'property';
            }
            $baseSlug = $data['slug'];
            $try = 1;
            while ($try < 200) {
                $hit = db()->fetchOne("SELECT id FROM properties WHERE slug = ? LIMIT 1", [$data['slug']]);
                if (!$hit) break;
                $try++;
                $data['slug'] = $baseSlug . '-' . $try;
            }

            $cols   = [];
            $holders = [];
            $values = [];
            foreach ($allowed as $c) {
                if (!array_key_exists($c, $data)) continue;
                $cols[]    = $c;
                $holders[] = '?';
                $values[]  = $data[$c];
            }

            $sql = "INSERT INTO properties (`" . implode('`,`', $cols) . "`) VALUES (" . implode(',', $holders) . ")";

            $id = db()->insert($sql, $values);
            if (!$id) {
                return ['success' => false, 'error' => 'Insert returned no ID — check logs/php-errors.log'];
            }

            return ['success' => true, 'id' => (int)$id];
        } catch (Throwable $e) {
            error_log('createProperty error: ' . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}

// ============================================================
// PHOTO PIPELINE — FLAT storage
// Disk:   /uploads/properties/filename.jpg
// DB:     properties/filename.jpg
// URL:    /uploads/properties/filename.jpg
// ============================================================

if (!function_exists('handlePropertyPhotos')) {
    function handlePropertyPhotos(array $files, int $propertyId): array {
        $saved = [];
        if (empty($files['name'][0])) return $saved;

        $root      = __DIR__;
        $targetDir = $root . '/uploads/properties';

        if (!is_dir($targetDir)) {
            if (!@mkdir($targetDir, 0775, true) && !is_dir($targetDir)) {
                error_log("handlePropertyPhotos: cannot create $targetDir");
                return $saved;
            }
        }

        $allowed = [
            'image/jpeg' => 'jpg',
            'image/png'  => 'png',
            'image/webp' => 'webp',
            'image/gif'  => 'gif',
        ];
        $maxSize = 8 * 1024 * 1024;
        $finfo   = finfo_open(FILEINFO_MIME_TYPE);
        $idx     = 0;

        foreach ($files['name'] as $i => $origName) {
            if (($files['error'][$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) continue;
            if (($files['size'][$i]  ?? 0) > $maxSize) continue;

            $tmp  = $files['tmp_name'][$i];
            $mime = finfo_file($finfo, $tmp);
            if (!isset($allowed[$mime])) continue;

            $ext     = $allowed[$mime];
            $newName = 'property_' . $propertyId . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
            $target  = $targetDir . '/' . $newName;

            if (!move_uploaded_file($tmp, $target)) {
                error_log("handlePropertyPhotos: move failed $tmp -> $target");
                continue;
            }
            @chmod($target, 0644);

            $saved[] = [
                'file_path'     => 'properties/' . $newName,
                'is_primary'    => $idx === 0 ? 1 : 0,
                'display_order' => $idx,
                'caption'       => null,
            ];
            $idx++;
        }
        finfo_close($finfo);
        return $saved;
    }
}

if (!function_exists('savePropertyPhotos')) {
    function savePropertyPhotos(int $propertyId, array $photos): int {
        if (!$photos) return 0;
        $db = db();

        $count = 0;
        foreach ($photos as $p) {
            $raw = ltrim(str_replace('/uploads/', '', $p['file_path']), '/');
            $raw = 'properties/' . basename($raw);

            $row = $db->insert(
                "INSERT INTO property_media (property_id, file_path, is_primary, display_order, caption)
                 VALUES (?, ?, ?, ?, ?)",
                [
                    $propertyId,
                    $raw,
                    (int)($p['is_primary']    ?? 0),
                    (int)($p['display_order'] ?? 0),
                    $p['caption'] ?? null,
                ]
            );
            if ($row) $count++;
        }
        if ($count === 0) return 0;

        $rows = $db->fetchAll(
            "SELECT file_path FROM property_media
             WHERE property_id = ?
             ORDER BY is_primary DESC, display_order ASC, id ASC",
            [$propertyId]
        );
        $paths   = array_column($rows, 'file_path');
        $primary = $paths[0] ?? null;
        $gallery = json_encode($paths, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $db->update(
            "UPDATE properties
             SET featured_image = ?, primary_image = ?, gallery = ?, photo_count = ?
             WHERE id = ?",
            [$primary, $primary, $gallery, count($paths), $propertyId]
        );

        return $count;
    }
}

// ============================================================
// createRoomType()
// ============================================================
if (!function_exists('createRoomType')) {
    function createRoomType(array $data): array {
        try {
            // ---- Required fields ----
            $propertyId = (int)($data['property_id'] ?? 0);
            $name       = trim((string)($data['name'] ?? ''));
            $basePrice  = (float)($data['base_price'] ?? 0);

            if ($propertyId <= 0)   return ['success' => false, 'error' => 'property_id is required'];
            if ($name === '')       return ['success' => false, 'error' => 'name is required'];
            if ($basePrice <= 0)    return ['success' => false, 'error' => 'base_price must be greater than 0'];

            // ---- Slug: generate, ensure unique ----
            $baseSlug = !empty($data['slug'])
                ? slugify((string)$data['slug'])
                : slugify($name);
            if ($baseSlug === '' || $baseSlug === 'item') $baseSlug = 'room';

            $slug = $baseSlug;
            $try  = 1;
            while ($try < 200) {
                $hit = db()->fetchOne(
                    "SELECT id FROM room_types WHERE slug = ? LIMIT 1",
                    [$slug]
                );
                if (!$hit) break;
                $try++;
                $slug = $baseSlug . '-' . $try;
            }

            // ---- Whitelist of columns present in room_types ----
            $allowed = [
                'property_id', 'name', 'slug', 'description',
                'capacity', 'max_capacity', 'bed_configuration',
                'room_size', 'room_view', 'floor',
                'base_price', 'weekend_price', 'holiday_price',
                'extra_person_charge', 'child_charge',
                'total_units', 'available_units',
                'min_stay', 'max_stay',
                'amenities', 'photos',
                'is_active', 'is_smoking', 'is_pet_friendly',
            ];

            // ---- Normalize values ----
            $row = [];

            // Required
            $row['property_id'] = $propertyId;
            $row['name']        = $name;
            $row['slug']        = $slug;
            $row['base_price']  = $basePrice;

            // Optional — text
            foreach (['description', 'bed_configuration', 'room_view', 'floor'] as $k) {
                if (array_key_exists($k, $data)) {
                    $row[$k] = ($data[$k] === '' || $data[$k] === null) ? null : (string)$data[$k];
                }
            }

            // Optional — numbers
            $numeric = [
                'capacity', 'max_capacity', 'room_size',
                'weekend_price', 'holiday_price',
                'extra_person_charge', 'child_charge',
                'total_units', 'available_units',
                'min_stay', 'max_stay',
            ];
            foreach ($numeric as $k) {
                if (array_key_exists($k, $data)) {
                    $v = $data[$k];
                    $row[$k] = ($v === '' || $v === null) ? null : (float)$v;
                }
            }

            // Booleans
            foreach (['is_active', 'is_smoking', 'is_pet_friendly'] as $k) {
                if (array_key_exists($k, $data)) {
                    $row[$k] = !empty($data[$k]) ? 1 : 0;
                }
            }

            // JSON arrays
            foreach (['amenities', 'photos'] as $k) {
                if (array_key_exists($k, $data)) {
                    $val = $data[$k];
                    if (is_array($val)) {
                        $row[$k] = json_encode(array_values($val), JSON_UNESCAPED_UNICODE);
                    } elseif (is_string($val) && $val !== '' && (str_starts_with($val, '[') || str_starts_with($val, '{'))) {
                        $row[$k] = $val; // already JSON
                    } elseif ($val === '' || $val === null) {
                        $row[$k] = null;
                    } else {
                        $row[$k] = json_encode([$val], JSON_UNESCAPED_UNICODE);
                    }
                }
            }

            // ---- Build INSERT dynamically from the whitelist ----
            $cols = []; $holders = []; $values = [];
            foreach ($allowed as $c) {
                if (!array_key_exists($c, $row)) continue;
                $cols[]    = $c;
                $holders[] = '?';
                $values[]  = $row[$c];
            }

            if (empty($cols)) {
                return ['success' => false, 'error' => 'No valid fields to insert'];
            }

            $sql = "INSERT INTO room_types (`" . implode('`,`', $cols) . "`) VALUES (" . implode(',', $holders) . ")";

            $id = db()->insert($sql, $values);
            if (!$id) {
                return ['success' => false, 'error' => 'Insert returned no ID — check logs/php-errors.log'];
            }

            return ['success' => true, 'id' => (int)$id];
        } catch (Throwable $e) {
            error_log('createRoomType error: ' . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}
// ============================================================
// calculateBookingPrice()
// Authoritative price calculator. Returns a detailed breakdown.
// Sums ALL applicable tax_rates for the property's country + Global.
// ============================================================

// ============================================================
// createBooking()
// Authoritative booking insert. Takes price data as-is from
// calculateBookingPrice() — does NOT recompute.
// Returns ['success' => true, 'id' => N, 'reference' => 'BK-XXXX']
// ============================================================
if (!function_exists('createBooking')) {
    function createBooking(array $data): array {
        try {
            $userId     = (int)($data['user_id'] ?? 0);
            $propertyId = (int)($data['property_id'] ?? 0);
            $roomTypeId = (int)($data['room_type_id'] ?? 0);
            $checkIn    = (string)($data['check_in'] ?? '');
            $checkOut   = (string)($data['check_out'] ?? '');
            $guests     = max(1, (int)($data['guests'] ?? 1));
            $children   = max(0, (int)($data['children'] ?? 0));
            $rooms      = max(1, (int)($data['rooms'] ?? 1));

            if ($userId <= 0)     return ['success' => false, 'message' => 'user_id required'];
            if ($propertyId <= 0) return ['success' => false, 'message' => 'property_id required'];
            if ($roomTypeId <= 0) return ['success' => false, 'message' => 'room_type_id required'];

            $ci = DateTime::createFromFormat('Y-m-d', $checkIn);
            $co = DateTime::createFromFormat('Y-m-d', $checkOut);
            if (!$ci || !$co || $co <= $ci) {
                return ['success' => false, 'message' => 'Invalid dates'];
            }
            $nights = (int)$ci->diff($co)->days;

            // ---- Property → vendor_id + currency + commission ----
            $property = db()->fetchOne("SELECT * FROM properties WHERE id = ? LIMIT 1", [$propertyId]);
            if (!$property) return ['success' => false, 'message' => 'Property not found'];

            $vendorId = (int)($property['vendor_id'] ?? 0);
            if ($vendorId <= 0) return ['success' => false, 'message' => 'Property has no vendor'];

            // Commission rate: vendors.commission_rate (percent)
            $commissionRate = 20.0;
            try {
                $vrow = db()->fetchOne("SELECT commission_rate FROM vendors WHERE id = ? LIMIT 1", [$vendorId]);
                if ($vrow && isset($vrow['commission_rate'])) {
                    $commissionRate = (float)$vrow['commission_rate'];
                }
            } catch (Throwable $e) {}

            // ---- Currency ----
            $baseCurrency = (string)($data['currency']
                            ?? $property['base_currency']
                            ?? $property['currency']
                            ?? 'USD');
            $baseCurrency = strtoupper(substr($baseCurrency, 0, 3));

            // ---- Pricing (from calculateBookingPrice) ----
            $subtotal     = round((float)($data['subtotal']            ?? 0), 2);
            $extraPerson  = round((float)($data['extra_person_fee']    ?? 0), 2);
            $childFee     = round((float)($data['child_fee']           ?? 0), 2);
            $cleaningFee  = round((float)($data['cleaning_fee']        ?? 0), 2);
            $serviceFee   = round((float)($data['service_fee']         ?? 0), 2);
            $taxAmount    = round((float)($data['tax_amount']          ?? 0), 2);
            $totalAmount  = round((float)($data['total_amount']        ?? 0), 2);

            // If total wasn't passed (defensive), compute it
            if ($totalAmount <= 0) {
                $totalAmount = $subtotal + $extraPerson + $childFee + $cleaningFee + $serviceFee + $taxAmount;
            }

            // Combine extra person + child into "extra_charges"
            $extraCharges = round($extraPerson + $childFee, 2);

            // ---- Commission + payout ----
            $commissionAmount = round($totalAmount * ($commissionRate / 100.0), 2);
            $vendorPayout     = round($totalAmount - $commissionAmount, 2);
            $platformFee      = $commissionAmount;

            // ---- Booking reference ----
            // Format: BK-YYMMDD-XXXX where XXXX = 4 random hex chars
            $reference = 'BK-' . date('ymd') . '-' . strtoupper(bin2hex(random_bytes(2)));
            // Ensure uniqueness (rare collision, but be safe)
            $try = 1;
            while ($try < 20) {
                $hit = db()->fetchOne("SELECT id FROM bookings WHERE booking_reference = ? LIMIT 1", [$reference]);
                if (!$hit) break;
                $reference = 'BK-' . date('ymd') . '-' . strtoupper(bin2hex(random_bytes(2)));
                $try++;
            }

            // ---- Tax breakdown JSON (audit) ----
            $taxBreakdown = null;
            if (!empty($data['price_breakdown'])) {
                // Full breakdown is stored on its own column if present
                $taxBreakdown = $data['price_breakdown'];
            } else {
                $taxBreakdown = json_encode([], JSON_UNESCAPED_UNICODE);
            }

            // ---- Guest details ----
            $guestName  = trim((string)($data['guest_name']  ?? ''));
            $guestEmail = trim((string)($data['guest_email'] ?? ''));
            $guestPhone = trim((string)($data['guest_phone'] ?? ''));

            if ($guestName === '')  $guestName  = 'Guest';
            if ($guestEmail === '') $guestEmail = 'guest@example.invalid';

            // ---- Insert ----
            $row = [
                'booking_reference' => $reference,
                'user_id'           => $userId,
                'property_id'       => $propertyId,
                'room_type_id'      => $roomTypeId,
                'vendor_id'         => $vendorId,
                'guest_name'        => $guestName,
                'guest_email'       => $guestEmail,
                'guest_phone'       => $guestPhone !== '' ? $guestPhone : null,
                'check_in'          => $checkIn,
                'check_out'         => $checkOut,
                'total_nights'      => $nights,
                'guests'            => $guests,
                'children'          => $children,
                'rooms'             => $rooms,
                'room_units'        => $rooms,

                'subtotal'          => $subtotal,
                'tax_amount'        => $taxAmount,
                'service_fee'       => $serviceFee,
                'cleaning_fee'      => $cleaningFee,
                'extra_charges'     => $extraCharges,
                'discount_amount'   => 0.00,
                'markup_amount'     => 0.00,
                'total_amount'      => $totalAmount,

                'base_currency'     => $baseCurrency,
                'currency'          => $baseCurrency,
                'exchange_rate'     => 1.0000,

                'commission_rate'   => $commissionRate,
                'commission_amount' => $commissionAmount,
                'vendor_payout'     => $vendorPayout,
                'platform_fee'      => $platformFee,

                'tax_breakdown'     => $taxBreakdown,

                'status'            => 'pending',
                'payment_status'    => 'pending',
                'channel'           => 'direct',
            ];

            $cols = array_keys($row);
            $holders = implode(',', array_fill(0, count($cols), '?'));
            $sql = "INSERT INTO bookings (`" . implode('`,`', $cols) . "`) VALUES ($holders)";

            $id = db()->insert($sql, array_values($row));
            if (!$id) {
                return ['success' => false, 'message' => 'Insert failed — check logs/php-errors.log'];
            }

            // ---- Side effects ----
            // Bump booking_count on the property
            try {
                db()->query(
                    "UPDATE properties SET booking_count = COALESCE(booking_count, 0) + 1 WHERE id = ?",
                    [$propertyId]
                );
            } catch (Throwable $e) {}

            // ---- Return ----
            return [
                'success'   => true,
                'id'        => (int)$id,
                'reference' => $reference,
                'total'     => $totalAmount,
                'currency'  => $baseCurrency,
            ];
        } catch (Throwable $e) {
            error_log('createBooking error: ' . $e->getMessage());
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
}
// ============================================
// END OF FILE

// ============================================================
// END getApplicableTaxes()

// ============================================================
// END getApplicableTaxes()



// ============================================================
// getApplicableTaxes() — property tax resolver
// ============================================================



// ============================================================
// getApplicableTaxes()
// ============================================================


// ============================================================
// getApplicableTaxes() — uses ACTUAL tax_rates columns
//   tax_rates: id, country, name, rate, type, is_active
// ============================================================






// ============================================================
// calculateBookingPrice() — calls getApplicableTaxes()
// ============================================================


// ============================================================
// calculateBookingPrice() — calls getApplicableTaxes()
// ============================================================


// ============================================================
// calculateBookingPrice() — calls getApplicableTaxes()
// ============================================================


// ============================================================
// calculateBookingPrice() — calls getApplicableTaxes()
// ============================================================
if (!function_exists('calculateBookingPrice')) {
    function calculateBookingPrice(array $input): array {
        $fail = function (string $msg) {
            return ['success' => false, 'error' => $msg, 'nights' => 0, 'subtotal' => 0.0,
                    'cleaning_fee' => 0.0, 'extra_person_fee' => 0.0, 'child_fee' => 0.0,
                    'service_fee' => 0.0, 'tax' => 0.0, 'total' => 0.0, 'currency' => 'USD',
                    'nightly_breakdown' => [], 'tax_lines' => [], 'fee_lines' => []];
        };
        try {
            $propertyId = (int)($input['property_id'] ?? 0);
            $roomTypeId = (int)($input['room_type_id'] ?? 0);
            $checkIn    = (string)($input['check_in'] ?? '');
            $checkOut   = (string)($input['check_out'] ?? '');
            $guests     = max(1, (int)($input['guests'] ?? 1));
            $children   = max(0, (int)($input['children'] ?? 0));
            $rooms      = max(1, (int)($input['rooms'] ?? 1));

            if ($propertyId <= 0)  return $fail('property_id required');
            if ($roomTypeId <= 0)  return $fail('room_type_id required');

            $in  = DateTime::createFromFormat('Y-m-d', $checkIn);
            $out = DateTime::createFromFormat('Y-m-d', $checkOut);
            if (!$in || !$out) return $fail('Invalid dates');
            if ($out <= $in)   return $fail('Check-out must be after check-in');

            $nights = (int)$in->diff($out)->days;
            if ($nights < 1) return $fail('Stay must be at least 1 night');

            $property = db()->fetchOne("SELECT * FROM properties WHERE id = ? LIMIT 1", [$propertyId]);
            if (!$property) return $fail('Property not found');

            $room = db()->fetchOne("SELECT * FROM room_types WHERE id = ? AND property_id = ? LIMIT 1", [$roomTypeId, $propertyId]);
            if (!$room) return $fail('Room type not found');

            $currency = (string)($property['base_currency'] ?? $property['currency'] ?? 'USD');

            $baseRate     = (float)($room['base_price'] ?? 0);
            $weekendRate  = (float)($room['weekend_price'] ?? 0);
            $holidayRate  = (float)($room['holiday_price'] ?? 0);
            $extraRate    = (float)($room['extra_person_charge'] ?? 0);
            $childRate    = (float)($room['child_charge'] ?? 0);
            $baseCap      = max(1, (int)($room['capacity'] ?? 2));

            if ($baseRate <= 0) return $fail('Room base price not set');

            // holiday dates
            $holidays = [];
            try {
                $hr = db()->fetchAll("SELECT date_from, date_to FROM property_holiday_dates WHERE property_id = ? AND date_to >= ? AND date_from <= ?",
                    [$propertyId, $checkIn, $checkOut]);
                foreach ((array)$hr as $r) {
                    $s = new DateTime($r['date_from']); $e = new DateTime($r['date_to']);
                    while ($s <= $e) { $holidays[] = $s->format('Y-m-d'); $s->modify('+1 day'); }
                }
            } catch (Throwable $e) {}

            // nightly
            $nightly = [];
            $subtotal = 0.0;
            $cur = clone $in;
            for ($i = 0; $i < $nights; $i++) {
                $d = $cur->format('Y-m-d');
                $dow = (int)$cur->format('N');
                $isWeekend = ($dow === 5 || $dow === 6);
                $isHoliday = in_array($d, $holidays, true);
                $rate = $baseRate;
                if ($isHoliday && $holidayRate > 0) $rate = $holidayRate;
                elseif ($isWeekend && $weekendRate > 0) $rate = $weekendRate;
                $subtotal += $rate * $rooms;
                $nightly[] = ['date' => $d, 'rate' => round($rate, 2), 'rooms' => $rooms];
                $cur->modify('+1 day');
            }

            $extraPersons = max(0, $guests - $baseCap);
            $extraFee     = $extraPersons * $extraRate * $nights * $rooms;
            $childFee     = $children * $childRate * $nights * $rooms;
            $cleaningFee  = (float)($property['cleaning_fee'] ?? 0);

            $serviceRate = 0.05;
            $serviceBase = $subtotal + $extraFee + $childFee + $cleaningFee;
            $serviceFee  = $serviceBase * $serviceRate;

            // TAXES — use the helper
            $taxes = function_exists('getApplicableTaxes') ? getApplicableTaxes($propertyId) : [];
            $taxAmount = 0.0;
            $taxLines = [];
            $taxBase = $serviceBase + $serviceFee;
            foreach ((array)$taxes as $t) {
                $r = (float)($t['rate'] ?? 0);
                if ($r <= 0) continue;
                $amt = ($t['type'] ?? 'percentage') === 'fixed' ? $r : $taxBase * ($r / 100.0);
                $amt = round($amt, 2);
                if ($amt <= 0) continue;
                $label = (string)$t['name'];
                if (($t['type'] ?? 'percentage') === 'percentage') $label .= ' (' . number_format($r, 2) . '%)';
                $taxLines[] = ['label' => $label, 'amount' => $amt];
                $taxAmount += $amt;
            }

            $total = $subtotal + $extraFee + $childFee + $cleaningFee + $serviceFee + $taxAmount;

            return [
                'success' => true, 'error' => null,
                'nights' => $nights, 'guests' => $guests, 'children' => $children, 'rooms' => $rooms,
                'currency' => $currency,
                'subtotal' => round($subtotal, 2),
                'extra_person_fee' => round($extraFee, 2),
                'child_fee' => round($childFee, 2),
                'cleaning_fee' => round($cleaningFee, 2),
                'service_fee' => round($serviceFee, 2),
                'service_fee_rate' => $serviceRate,
                'tax' => round($taxAmount, 2),
                'total' => round($total, 2),
                'nightly_breakdown' => $nightly,
                'tax_lines' => $taxLines,
                'fee_lines' => [],
            ];
        } catch (Throwable $e) {
            error_log('calculateBookingPrice: ' . $e->getMessage());
            return $fail($e->getMessage());
        }
    }
}


if (!function_exists('getApplicableTaxes')) {
    function getApplicableTaxes(int $propertyId): array {
        $name = '';
        $p = db()->fetchOne("SELECT country_id FROM properties WHERE id = ? LIMIT 1", [$propertyId]);
        if ($p && (int)$p['country_id'] > 0) {
            $d = db()->fetchOne("SELECT name FROM destinations WHERE id = ? LIMIT 1", [(int)$p['country_id']]);
            if ($d && !empty($d['name'])) $name = strtolower(trim((string)$d['name']));
        }
        $all = db()->fetchAll("SELECT id, country, name, rate, type FROM tax_rates WHERE is_active = 1");
        $country = [];
        $global  = [];
        foreach ((array)$all as $r) {
            $rc = strtolower(trim((string)($r['country'] ?? '')));
            $rate = (float)($r['rate'] ?? 0);
            if ($rate <= 0) continue;
            $type = strtolower(trim((string)($r['type'] ?? 'percentage')));
            if ($type !== 'fixed') $type = 'percentage';
            $row = ['id' => (int)($r['id'] ?? 0), 'name' => (string)($r['name'] ?? 'Tax'),
                    'rate' => $rate, 'type' => $type, 'applies_to' => 'base', 'is_compound' => 0];
            if ($rc === '' || $rc === 'global') { $global[] = $row; continue; }
            if ($name !== '' && ($rc === $name || strpos($name, $rc) !== false || strpos($rc, $name) !== false)) {
                $country[] = $row;
            }
        }
        // Prefer country-specific; only fall back to Global if the country has none
        return !empty($country) ? $country : $global;
    }
}
