<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
set_time_limit(0);
ini_set('memory_limit', '1G');

$cacheFile = 'stars_birthday_data.json';
$cacheTime = 86400; 
$stars = [];
$months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
$decades = [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010];

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<\/span><span class="stat-value">(.*?)<\/span>/is', $content, $bornMatch)) {
                $bornRaw = trim(strip_tags($bornMatch[1]));
                
                // Normalisation de la date pour le calendrier
                $dateObj = date_create($bornRaw);
                if ($dateObj) {
                    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,
                        'born' => $bornRaw,
                        'date_iso' => $dateObj->format('Y-m-d'), // Format standard pour le filtre
                        'month' => $dateObj->format('M'),
                        'year' => (int)$dateObj->format('Y'),
                        'timestamp' => $dateObj->getTimestamp(),
                        'photo' => $photo,
                        'url' => "/" . str_replace('\\', '/', $file->getPathname())
                    ];
                }
            }
        }
    }
    file_put_contents($cacheFile, json_encode($stars));
}

$currentMonth = isset($_GET['month']) ? $_GET['month'] : 'all';
$currentDecade = isset($_GET['decade']) ? $_GET['decade'] : 'all';
$specificDate = isset($_GET['exact_date']) ? $_GET['exact_date'] : '';
$sortOrder = isset($_GET['sort']) && $_GET['sort'] === 'asc' ? 'asc' : 'desc';

$filteredStars = array_filter($stars, function($s) use ($currentMonth, $currentDecade, $specificDate) {
    if (!empty($specificDate)) {
        return $s['date_iso'] === $specificDate;
    }
    $mMatch = ($currentMonth === 'all' || $s['month'] === $currentMonth);
    $dMatch = ($currentDecade === 'all' || ($s['year'] >= $currentDecade && $s['year'] < $currentDecade + 10));
    return $mMatch && $dMatch;
});

usort($filteredStars, function($a, $b) use ($sortOrder) {
    return ($sortOrder === 'desc') ? ($b['timestamp'] <=> $a['timestamp']) : ($a['timestamp'] <=> $b['timestamp']);
});

$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);

function getAge($birthDate) {
    $dateObj = date_create($birthDate);
    if (!$dateObj) return '??';
    return date_diff($dateObj, date_create('today'))->y;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Celebrity Birthdays & Age Search - Became.info</title>
<?php 
    $metaDescription = "Find out which celebrities were born on a specific date.";
    
    if (!empty($specificDate)) {
        $formattedDate = date_create($specificDate)->format('F j, Y');
        $metaDescription = "Discover all the celebrities born on $formattedDate. See their current age and detailed profiles with photos.";
    } elseif ($currentMonth !== 'all') {
        $metaDescription = "List of famous people and celebrities born in $currentMonth. Check their birthdays, ages, and life stories.";
    } elseif ($currentDecade !== 'all') {
        $metaDescription = "Browse celebrities born in the {$currentDecade}s. Find out the age and birth dates of stars from this era.";
    } else {
        $metaDescription = "Search our database of stars by birth date. Find celebrity birthdays, calculate their current age, and see who was born today.";
    }
?>
<meta name="description" content="<?= $metaDescription ?>">
    <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; }
        .filter-nav { display: flex; flex-wrap: wrap; justify-content: center; gap: 5px; margin: 10px 0; }
        .filter-btn { padding: 8px 12px; background: white; border: 1px solid #e2e8f0; border-radius: 10px; text-decoration: none; color: #64748b; font-weight: 600; font-size: 0.75rem; }
        .filter-btn.active { background: var(--primary); color: white; border-color: var(--primary); }
        .date-picker-container { background: white; padding: 20px; border-radius: 16px; border: 1px solid #e2e8f0; text-align: center; margin-bottom: 20px; }
        .date-input { padding: 10px; border-radius: 8px; border: 1px solid #cbd5e1; font-family: inherit; font-weight: 600; }
        .stars-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 15px; margin-top: 20px; }
        .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: 8px; transition: 0.2s; }
        .star-thumb { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; border: 3px solid #f1f5f9; }
        .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-birthday.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 class="container">
    <header style="text-align: center;"><div class="logo" onclick="location.href='/'">Became.info</div></header>

    <form id="search-form" style="display: flex; gap: 10px; justify-content: center; margin-bottom: 20px; position: relative;">
        <input type="text" id="search-input" placeholder="Search celebrity..." 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;">OK</button>
        <div id="suggestions"></div>
    </form>

    <div class="date-picker-container">
        <form method="GET">
            <label style="font-weight: 700; margin-right: 10px; color: #475569;">Find stars born on :</label>
            <input type="date" name="exact_date" class="date-input" value="<?= $specificDate ?>">
            <button type="submit" style="padding: 10px 20px; border-radius: 8px; border: none; background: var(--text); color: white; font-weight: bold; cursor: pointer; margin-left: 5px;">Search Date</button>
            <?php if (!empty($specificDate)): ?>
                <a href="?" style="margin-left: 10px; font-size: 0.8rem; color: #ef4444;">Clear</a>
            <?php endif; ?>
        </form>
    </div>

    <?php if (empty($specificDate)): ?>
    <div class="filter-nav">
        <a href="?month=all&decade=<?= $currentDecade ?>&sort=<?= $sortOrder ?>" class="filter-btn <?= $currentMonth === 'all' ? 'active' : '' ?>">All Months</a>
        <?php foreach ($months as $m): ?>
            <a href="?month=<?= $m ?>&decade=<?= $currentDecade ?>&sort=<?= $sortOrder ?>" class="filter-btn <?= $currentMonth === $m ? 'active' : '' ?>"><?= $m ?></a>
        <?php endforeach; ?>
    </div>
    <div class="filter-nav">
        <a href="?month=<?= $currentMonth ?>&decade=all&sort=<?= $sortOrder ?>" class="filter-btn <?= $currentDecade === 'all' ? 'active' : '' ?>">All Decades</a>
        <?php foreach ($decades as $d): ?>
            <a href="?month=<?= $currentMonth ?>&decade=<?= $d ?>&sort=<?= $sortOrder ?>" class="filter-btn <?= $currentDecade === $d ? 'active' : '' ?>"><?= $d ?>s</a>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="stars-grid">
        <?php if ($totalItems == 0): ?>
            <p style="text-align: center; grid-column: 1/-1; padding: 40px; color: #94a3b8;">No celebrities found for this selection.</p>
        <?php endif; ?>
        <?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.85rem;"><?= htmlspecialchars($star['name']) ?></span>
                <span style="background: #fef2f2; color: #dc2626; padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 800;"><?= getAge($star['born']) ?> years old</span>
                <span style="font-size:0.7rem; color:#64748b;"><?= htmlspecialchars($star['born']) ?></span>
            </a>
        <?php endforeach; ?>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php $q = "&month=$currentMonth&decade=$currentDecade&exact_date=$specificDate&sort=$sortOrder"; ?>
        <?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 response = await fetch(`https://en.wikipedia.org/w/api.php?action=opensearch&format=json&origin=*&search=${encodeURIComponent(query)}`);
        const data = await response.json();

        if (data[1] && data[1].length > 0) {
            suggestionsBox.innerHTML = data[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) => {
    if (loader) loader.style.display = 'none';
});
</script>
</body>
</html>
