<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
set_time_limit(0);
ini_set('memory_limit', '1G');

$cacheFile = 'stars_birthplace_data.json';
$cacheTime = 86400; 
$stars = [];

if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
    $stars = json_decode(file_get_contents($cacheFile), true);
} else {
    $directory = new RecursiveDirectoryIterator('profiles');
    $iterator = new RecursiveIteratorIterator($directory);
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'php' && $file->getFilename() !== 'index.php') {
            $content = file_get_contents($file->getPathname());

            if (preg_match('/<span class="stat-label">Born in<\/span><span class="stat-value">(.*?)<\/span>/is', $content, $birthMatch)) {
                $birthPlace = trim(strip_tags($birthMatch[1]));

                preg_match('/<!-- TITRE -->(.*?)<!-- \/TITRE -->/s', $content, $nameMatch);
                $name = isset($nameMatch[1]) ? trim(strip_tags($nameMatch[1])) : ucwords(str_replace(['-', '.php'], [' ', ''], $file->getBasename('.php')));

                preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $content, $imgMatch);
                $photo = isset($imgMatch[1]) ? $imgMatch[1] : '/default-avatar.png';
                
                $stars[] = [
                    'name' => $name,
                    'birthplace' => $birthPlace,
                    'photo' => $photo,
                    'url' => "/" . str_replace('\\', '/', $file->getPathname())
                ];
            }
        }
    }
    file_put_contents($cacheFile, json_encode($stars));
}

$cityFilter = isset($_GET['city']) ? trim($_GET['city']) : '';
$filteredStars = array_filter($stars, function($s) use ($cityFilter) {
    if ($cityFilter === '') return true;
    return (stripos($s['birthplace'], $cityFilter) !== false);
});

usort($filteredStars, function($a, $b) {
    return strcmp($a['name'], $b['name']);
});

$currentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$itemsPerPage = 60;
$totalItems = count($filteredStars);
$totalPages = ceil($totalItems / $itemsPerPage);
$pagedStars = array_slice($filteredStars, ($currentPage - 1) * $itemsPerPage, $itemsPerPage);

$metaDesc = $cityFilter !== '' ? "Celebrities born in $cityFilter." : "Browse celebrities by their place of birth.";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Celebrities by Birthplace - Became.info</title>
    <meta name="description" content="<?= htmlspecialchars($metaDesc) ?>">
    <link rel="stylesheet" href="/style.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700;900&display=swap');
        :root { --primary: #2563eb; --gradient: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%); --bg: #f1f5f9; --text: #0f172a; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); color: var(--text); padding: 15px; margin: 0; }
        .container { max-width: 1100px; margin: auto; width: 100%; }
        .logo { display: inline-block; background: var(--gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; text-align: center; font-size: 2.2rem; font-weight: 900; margin: 10px auto; width: 100%; cursor: pointer; }
        #suggestions { position: absolute; top: 100%; left: 0; right: 0; background: white; border-radius: 12px; box-shadow: 0 10px 15px rgba(0,0,0,0.1); z-index: 1001; max-width: 400px; margin: 5px auto; display: none; border: 1px solid #e2e8f0; overflow:hidden; }
        .suggestion-item { padding: 12px 15px; cursor: pointer; border-bottom: 1px solid #f1f5f9; text-align:left; }
        .loading-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.9); z-index: 2000; justify-content: center; align-items: center; flex-direction: column; font-weight: bold; color: var(--primary); }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        .stars-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 15px; margin-top: 30px; }
        .star-item { background: white; padding: 20px 10px; border-radius: 16px; border: 1px solid #e2e8f0; text-decoration: none; color: #334155; font-weight: 700; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 10px; transition: 0.2s; }
        .star-item:hover { transform: translateY(-5px); border-color: var(--primary); }
        .star-thumb { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; border: 3px solid #f1f5f9; }
        .birth-tag { background: #eff6ff; color: var(--primary); padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 800; border: 1px solid #e2e8f0; }
        .pagination { margin: 40px 0; display: flex; justify-content: center; align-items: center; gap: 8px; flex-wrap: wrap; }
        .page-btn { padding: 8px 14px; background: white; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: var(--text); font-weight: 700; }
        .active-page { background: var(--gradient); color: white; border: none; }
    </style>
	<?php include_once("analyticstracking.php") ?>
	<link rel="canonical" href="https://www.became.info/celebrity-birthplace.php">
<meta name="google-adsense-account" content="ca-pub-9068036362020026"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9068036362020026" crossorigin="anonymous"></script></head>
<body>

<div id="loader" class="loading-overlay">
    <div style="border: 4px solid #f3f3f3; border-top: 4px solid #6366f1; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin-bottom: 15px;"></div>
    <span>Searching City...</span>
</div>

<div class="container">
    <header style="text-align: center;"><div class="logo" onclick="location.href='/'">Became.info</div></header>

    <h2 style="text-align:center; font-size: 1.2rem; color: #64748b; margin-bottom: 20px;">
        <?= $cityFilter !== '' ? "Stars born in: " . htmlspecialchars($cityFilter) : "Find celebrities by birth city" ?>
    </h2>

    <form id="city-search-form" method="GET" style="display: flex; gap: 10px; justify-content: center; margin-bottom: 30px;">
        <input type="text" name="city" id="search-input" value="<?= htmlspecialchars($cityFilter) ?>" placeholder="Enter a city (e.g. Pretoria, London...)" autocomplete="off" required style="padding:15px; border-radius:12px; border:2px solid #e2e8f0; width:100%; max-width:400px;">
        <button type="submit" style="padding:15px 25px; border-radius:12px; border:none; background:var(--gradient); color:white; font-weight:bold; cursor:pointer;">Search</button>
    </form>

    <div class="stars-grid">
        <?php if (empty($pagedStars)): ?>
            <p style="grid-column: 1/-1; text-align: center; padding: 50px; color: #64748b;">No celebrities found for this location.</p>
        <?php else: ?>
            <?php foreach ($pagedStars as $star): ?>
                <a href="<?= $star['url'] ?>" class="star-item">
                    <img src="<?= htmlspecialchars($star['photo']) ?>" alt="<?= htmlspecialchars($star['name']) ?>" class="star-thumb" loading="lazy">
                    <span style="font-size: 0.9rem;"><?= htmlspecialchars($star['name']) ?></span>
                    <span class="birth-tag">📍 <?= htmlspecialchars($star['birthplace']) ?></span>
                </a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php $q = "&city=" . urlencode($cityFilter); ?>
        <?php if ($currentPage > 1): ?>
            <a href="?page=1<?= $q ?>" class="page-btn">First</a>
            <a href="?page=<?= $currentPage - 1 ?><?= $q ?>" class="page-btn">←</a>
        <?php endif; ?>
        <span class="page-btn active-page"><?= $currentPage ?> / <?= $totalPages ?></span>
        <?php if ($currentPage < $totalPages): ?>
            <a href="?page=<?= $currentPage + 1 ?><?= $q ?>" class="page-btn">→</a>
            <a href="?page=<?= $totalPages ?><?= $q ?>" class="page-btn">Last</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<footer style="text-align: center; padding: 40px; border-top: 1px solid #e2e8f0; margin-top: 50px;">
    <?php include("footer.php"); ?>
</footer>

<script>
const searchInput = document.getElementById('search-input');
const suggestionsBox = document.getElementById('suggestions');
const loader = document.getElementById('loader');

function slugify(t) {
    return t.toString().toLowerCase().trim().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-');
}

searchInput.addEventListener('input', async () => {
    const query = searchInput.value.trim();
    if (query.length < 2) { suggestionsBox.style.display = 'none'; return; }
    try {
        const r = await fetch(`https://en.wikipedia.org/w/api.php?action=opensearch&format=json&origin=*&search=${encodeURIComponent(query)}`);
        const d = await r.json();

        if (d[1] && d[1].length > 0) {
            suggestionsBox.innerHTML = d[1].slice(0, 5).map(item => `<div class="suggestion-item">${item}</div>`).join('');
            suggestionsBox.style.display = 'block';
        } else {
            suggestionsBox.style.display = 'none';
        }
    } catch (e) {
        suggestionsBox.style.display = 'none';
    }
});

suggestionsBox.addEventListener('click', (e) => {
    if (e.target.classList.contains('suggestion-item')) {
        searchInput.value = e.target.innerText;
        suggestionsBox.style.display = 'none';
        handleSearch(searchInput.value);
    }
});

async function handleSearch(name) {
    const s = slugify(name);
    const firstLetter = s.charAt(0).toUpperCase();
    const localUrl = `/profiles/${firstLetter}/${s}.php`;
    loader.style.display = 'flex';
    
    try {
        const check = await fetch(localUrl, { method: 'HEAD' });
        if (check.ok) { window.location.href = localUrl; } 
        else { window.location.href = `/index.php?name=${encodeURIComponent(name)}`; }
    } catch (e) {
        window.location.href = `/index.php?name=${encodeURIComponent(name)}`;
    }
}

document.getElementById('search-form').onsubmit = (e) => {
    e.preventDefault();
    handleSearch(searchInput.value);
};

document.addEventListener('click', (e) => {
    if (e.target !== searchInput) suggestionsBox.style.display = 'none';
});

window.addEventListener('pageshow', (event) => {
    const globalLoader = document.getElementById('loader');
    if (globalLoader) {
        globalLoader.style.display = 'none';
    }
});

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload();
    }
};window.addEventListener('pageshow', (event) => {
    const globalLoader = document.getElementById('loader');
    if (globalLoader) {
        globalLoader.style.display = 'none';
    }
});

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload();
    }
};
</script>

</body>
</html>
