<?php
/**
 * REVENDA - Core Functions
 * @version 9.1.0 - Added destination helpers (countries/cities from `destinations` table)
 *
 * NOTE: This file contains ONLY core functions.
 * Module functions (mailer, ai, themes, tenant, smart_pricing, loyalty,
 * security, webrtc, blockchain, iot, robot, carbon, insurance,
 * gamification, support, push, channels, trip_planner, concierge, etc.)
 * are provided by their respective files in /includes/.
 *
 * DO NOT add stubs here. If you need a module function, create the module.
 */

// ============================================
// 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 cities ct ON p.city_id = ct.id
                LEFT JOIN countries co ON p.country_id = co.id
                WHERE p.is_active = 1";
        $params = [];

        if (!empty($filters['search'])) {
            $sql .= " AND (p.name LIKE ? OR p.description LIKE ? OR p.short_description LIKE ?)";
            $s = '%' . $filters['search'] . '%';
            $params[] = $s; $params[] = $s; $params[] = $s;
        }
        if (!empty($filters['category'])) {
            $sql .= " AND p.category_id = ?";
            $params[] = $filters['category'];
        }
        if (!empty($filters['country'])) {
            $sql .= " AND p.country_id = ?";
            $params[] = $filters['country'];
        }
        if (!empty($filters['city'])) {
            $sql .= " AND p.city_id = ?";
            $params[] = $filters['city'];
        }
        if (!empty($filters['star_rating'])) {
            $sql .= " AND p.star_rating >= ?";
            $params[] = $filters['star_rating'];
        }
        if (!empty($filters['instant_book'])) {
            $sql .= " AND p.is_instant_bookable = 1";
        }

        if (!empty($filters['sort'])) {
            switch ($filters['sort']) {
                case 'price_asc': $sql .= " ORDER BY p.min_price_per_night ASC"; break;
                case 'price_desc': $sql .= " ORDER BY p.max_price_per_night DESC"; break;
                case 'rating': $sql .= " ORDER BY p.average_rating DESC"; break;
                case 'popularity': $sql .= " ORDER BY p.booking_count DESC"; break;
                case 'newest': $sql .= " ORDER BY p.created_at DESC"; break;
                default: $sql .= " ORDER BY p.is_featured DESC, p.created_at DESC";
            }
        } else {
            $sql .= " ORDER BY p.is_featured DESC, p.created_at DESC";
        }

        if (!empty($filters['limit'])) {
            $sql .= " LIMIT " . intval($filters['limit']);
        } else {
            $sql .= " LIMIT 50";
        }

        return $db->fetchAll($sql, $params);
    } catch (Throwable $e) { 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
             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 — powered by the `destinations` table
// ============================================================
// These are the single source of truth for countries and cities
// across the whole platform. The `destinations` table holds ~250
// countries and ~34,000 cities imported from GeoNames.

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')) {
    /**
     * All active countries from the destinations table.
     * Falls back to legacy `countries` table if destinations is missing.
     */
    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, population
                 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')) {
    /**
     * All active cities from the destinations table.
     * Optionally filtered by country ID and/or substring search.
     */
    function getAllCities($countryId = null, $search = null, $limit = 2000) {
        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.latitude, ci.longitude, ci.population,
                           co.id AS country_id
                    FROM destinations ci
                    LEFT JOIN destinations co
                      ON co.type = 'country' AND co.country_code = ci.country_code
                    WHERE ci.type = 'city' AND ci.is_active = 1";
            $params = [];

            if ($countryId) {
                $country = db()->fetchOne(
                    "SELECT country_code FROM destinations
                     WHERE id = ? AND type = 'country' LIMIT 1",
                    [$countryId]
                );
                if ($country) {
                    $sql .= " AND ci.country_code = ?";
                    $params[] = $country['country_code'];
                }
            }
            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, 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('searchDestinations')) {
    /**
     * Search any destination (country or city) — good for autocomplete/typeahead.
     */
    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 [];
        }
    }
}

// ============================================================
// LEGACY WRAPPERS (kept for backwards compatibility)
// These now delegate to the destinations helpers above,
// so existing pages automatically get the 34k-city dataset.
// ============================================================

if (!function_exists('getCountries')) {
    function getCountries() {
        return getAllCountries();
    }
}

if (!function_exists('getCities')) {
    function getCities($countryId = null) {
        return getAllCities($countryId, null, 3000);
    }
}

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>';
}

function getPropertyImageUrl($property) {
    if (!empty($property['image'])) {
        if (strpos($property['image'], 'http') === 0) return $property['image'];
        return '/uploads/' . ltrim($property['image'], '/');
    }
    if (!empty($property['id'])) {
        $images = getPropertyImages($property['id']);
        if (!empty($images) && !empty($images[0]['file_path'])) {
            return '/uploads/' . ltrim($images[0]['file_path'], '/');
        }
    }
    return 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=800&h=600&fit=crop';
}

function getAmenityIconSafe($amenity) {
    return getAmenityIcon($amenity);
}

function safeStarRating($rating) {
    return generateStarRating($rating);
}

// ============================================
// DASHBOARD STATS & ANALYTICS
// ============================================

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) {
            error_log("getDashboardStats error: " . $e->getMessage());
            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,
        ];
    }
}

// ============================================
// AVAILABILITY FUNCTIONS
// ============================================

if (!function_exists('getQuickAvailability')) {
    function getQuickAvailability($propertyId) {
        try {
            $roomTypes = getRoomTypes($propertyId);
            if (empty($roomTypes)) {
                return [
                    'available' => false,
                    'next_available' => null,
                    'lowest_price' => null,
                ];
            }

            $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']);
                if ($quick['available']) {
                    $p['available'] = true;
                    $p['next_available'] = $quick['next_available'];
                    $p['lowest_price'] = $quick['lowest_price'];
                    $result[] = $p;
                }
            }
            return !empty($result) ? $result : $properties;
        } 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];
        }
    }
}

// ============================================
// END OF FILE
// ============================================
// NO MODULE STUBS
// NO CSRF STUBS
// NO DUPLICATES
// ============================================