<?php
include 'database/config.php';
include 'database/search_log_config.php';
/* =========================
   BLOCKED IP CHECK
========================= */

$user_ip = $_SERVER['REMOTE_ADDR'] ?? '';

if(!empty($user_ip)){

    $blockCheck = $log_conn->prepare("
        SELECT id 
        FROM blocked_ips 
        WHERE ip_address = ?
        LIMIT 1
    ");

    $blockCheck->bind_param("s", $user_ip);
    $blockCheck->execute();
    $blockCheck->store_result();

    if($blockCheck->num_rows > 0){

    http_response_code(403);

    $blocked_ip = $user_ip;   // pass IP to page
    include "access_denied.php";
    exit;
}

    $blockCheck->close();
}

$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;

/* =========================
   SECURE SEARCH VALIDATION
========================= */

$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$cleanSearch = '';

if (!empty($search)) {

    if (strlen($search) > 60) {
        $search = substr($search, 0, 60);
    }

    if (!preg_match('/^[A-Za-z0-9 ]+$/', $search)) {
        $search = preg_replace('/[^A-Za-z0-9 ]/', '', $search);
    }

    $search = str_replace(['%', '_'], '', $search);
    $search = preg_replace('/\s+/', ' ', $search);

    $cleanSearch = strtolower(trim($search));
}

/* =========================
   RATE LIMIT (10 PER MIN)
========================= */

if (strlen($cleanSearch) >= 2) {

    $ip = $_SERVER['REMOTE_ADDR'] ?? '';

    $rateCheck = $log_conn->prepare("
        SELECT COUNT(*) as total 
        FROM search_logs 
        WHERE ip_address = ? 
        AND searched_at >= NOW() - INTERVAL 15 MINUTE
    ");

    $rateCheck->bind_param("s", $ip);
    $rateCheck->execute();
    $rateData = $rateCheck->get_result()->fetch_assoc();
    $rateCheck->close();

    if ($rateData['total'] > 20) {

    // AUTO BLOCK
    $blockStmt = $log_conn->prepare("
        INSERT IGNORE INTO blocked_ips (ip_address)
        VALUES (?)
    ");
    $blockStmt->bind_param("s", $ip);
    $blockStmt->execute();
    $blockStmt->close();

    http_response_code(429);
    exit("Too many searches. Your IP has been temporarily blocked.");
}
}

/* ===== GET SPONSORED RESULT ===== */

$sponsoredResult = null;

if (strlen($cleanSearch) >= 2) {

    $sponsorStmt = $log_conn->prepare("
        SELECT id, redirect_url 
        FROM sponsored_keywords 
        WHERE keyword = ? 
        AND is_active = 1
        AND (expiry_date IS NULL OR expiry_date >= CURDATE())
        LIMIT 1
    ");

    $sponsorStmt->bind_param("s", $cleanSearch);
    $sponsorStmt->execute();
    $resultSponsor = $sponsorStmt->get_result();

    if ($resultSponsor->num_rows > 0) {
        $sponsoredResult = $resultSponsor->fetch_assoc();
    }

    $sponsorStmt->close();
}

/* ===== SAVE SEARCH LOG ===== */

if (strlen($cleanSearch) >= 2) {

    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

    $logStmt = $log_conn->prepare("
        INSERT INTO search_logs (keyword, ip_address, user_agent)
        VALUES (?, ?, ?)
    ");
    $logStmt->bind_param("sss", $cleanSearch, $ip, $agent);
    $logStmt->execute();
    $logStmt->close();
}

/* ===== TICKER CONTROL ===== */
$enableTicker = false;

$requireVerified = false;
$requireIndexed  = false;

/* ===== LAUNCHER CONTROL ===== */
$enableLauncher = true;

/* ===== TRENDING CONTROL ===== */
$enableTrending = false;
?>
<!DOCTYPE html>
<html>
<head>
<title>
<?php 
if(!empty($search)){
    echo htmlspecialchars($search) . " - GoMAPS Search";
}else{
    echo "GoMAPS - India's No.1 Business Search Engine";
}
?>
</title>
<meta property="og:type" content="website">
<meta property="og:title" content="<?php 
if(!empty($search)){
    echo htmlspecialchars($search) . ' - GoMAPS Search';
}else{
    echo 'GoMAPS - India\'s No.1 Business Search Engine';
}
?>">
<meta property="og:description" content="Search and discover trusted businesses across India instantly.">
<meta property="og:url" content="https://search.gomaps.in/">
<meta property="og:site_name" content="GoMAPS">
<meta property="og:image" content="https://search.gomaps.in/og-image.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="GoMAPS - India's No.1 Business Search Engine">
<meta name="twitter:description" content="Find verified businesses, shops and services near you.">
<meta name="twitter:image" content="https://search.gomaps.in/og-image.jpg">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;}
*{
    box-sizing:border-box;
    font-family:'Open Sans', sans-serif;
}
html,body{
    margin:0;
    font-family:'Open Sans', sans-serif;
    background:#f3f3f3;
}
body{overflow:hidden;}
body.has-search{overflow-y:auto;}

.top-left-logo{
    position:absolute;
    top:20px;
    left:25px;
}

.top-left-logo img{
    width:32px;
    height:32px;
    object-fit:contain;
    cursor:pointer;
}

.launcher-btn{
    position:absolute;
    top:20px;
    right:25px;
    width:30px;
    height:30px;
    cursor:pointer;
    object-fit:contain;
}

.header{
min-height:100vh;
display:flex;
flex-direction:column;
justify-content:center;
align-items:center;
position:relative;
text-align:center;
}
body.has-search .header{
min-height:auto;
padding:40px 0 20px;
}

.logo{
    font-size:38px;
    font-weight:bold;
    margin-bottom:4px;
    color:#007185;
}

.tagline{
    font-size:13px;
    color:#555;
    margin-top:0;
    margin-bottom:15px;
    letter-spacing:0.5px;
}

.search-wrapper{width:100%;max-width:600px;padding:0 20px;}

.search-container{
    display:flex;
    align-items:center;
    background:#fff;
    height:48px;
    padding:0 10px 0 15px;
    border-radius:25px;
    box-shadow:0 2px 8px rgba(0,0,0,0.15);
}

.search-container input{
flex:1;
border:none;
outline:none;
font-size:16px;
background:transparent;
}

.icon{
width:34px;
height:34px;
display:flex;
align-items:center;
justify-content:center;
cursor:pointer;
color:#555;
}

.mic-active{color:red!important;}

.search-btn-wrapper{
    margin-top:18px;
    display:flex;
    justify-content:center;
    align-items:center;
}

.search-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:8px 12px;
    font-size:15px;
    border:none;
    border-radius:22px;
    background:#007185;
    color:#fff;
    cursor:pointer;
    width:auto;
    height:30px;
    white-space:nowrap;
}

.search-btn:hover{background:#005f6b;}

.modal{
display:none;
position:fixed;
inset:0;
background:rgba(0,0,0,0.4);
justify-content:flex-end;
align-items:flex-start;
padding:80px 30px;
z-index:999;
}
.modal.show{display:flex;}

.modal-content{
background:#fff;
width:340px;
border-radius:18px;
padding:20px;
box-shadow:0 10px 25px rgba(0,0,0,0.2);
transform:translateY(-30px);
opacity:0;
transition:all 0.35s ease;
}

.modal.show .modal-content{
    transform:translateY(0);
    opacity:1;
}

.app-grid{
display:grid;
grid-template-columns:repeat(3,1fr);
gap:20px;
text-align:center;
}

.app-item{
text-decoration:none;
color:#333;
font-size:13px;
display:flex;
flex-direction:column;
align-items:center;
padding:10px 5px;
border-radius:12px;
transition:0.2s ease;
}
.app-item:hover{background:#f1f3f4;}
.app-item img{
width:40px;
height:40px;
margin-bottom:8px;
}

.container{
max-width:900px;
margin:20px auto;
padding:0 12px;
}

.card{
display:flex;
align-items:flex-start;
background:#fff;
padding:16px;
margin-bottom:14px;
border-radius:12px;
box-shadow:0 2px 6px rgba(0,0,0,0.08);
}

.card img{
width:100px;
height:100px;
border-radius:14px;
object-fit:cover;
margin-right:18px;
}

.card-content{
flex:1;
text-align:left;
}

.card-content h3{
margin:0 0 6px;
font-size:18px;
color:#007185;
}

.card-content p{
margin:4px 0;
font-size:14px;
color:#555;
}

.views{
font-size:13px;
color:#888;
margin-top:6px;
}

.copyright{
text-align:center;
font-size:13px;
color:#777;
padding:20px 0;
}

.no-result-box{
    background:#fff;
    padding:40px 20px;
    border-radius:14px;
    text-align:center;
    box-shadow:0 2px 8px rgba(0,0,0,0.08);
    margin:20px 0;
}

.no-result-box h2{
    margin:10px 0 8px;
    color:#007185;
    font-size:22px;
}
/* ===== Scroll To Top Button ===== */
#scrollTopBtn {
    position: fixed;
    bottom: 40px;       
    right: 10px;        

    width: 50px;
    height: 50px;

    display: flex;
    align-items: center;
    justify-content: center;

    background: transparent;
    border: none;
    cursor: pointer;
    z-index: 9999;

    opacity: 0;
    visibility: hidden;
    transition: opacity 0.4s ease, transform 0.3s ease;
}

/* PNG Image – Prevent Compression */
#scrollTopBtn img {
    width: 100%;
    height: auto;
    object-fit: contain;
}

/* Show Button */
#scrollTopBtn.show {
    opacity: 1;
    visibility: visible;
}

/* Hover Effect */
#scrollTopBtn:hover {
    transform: scale(1.1);
}
/* ===== Result Count ===== */
.result-count{
    text-align:left;
    font-size:14px;
    color:#555;
    margin:10px 5px 20px;
}

/* ===== Professional Pagination ===== */
.pagination{
    text-align:center;
    margin:30px 0;
}

.page-btn{
    display:inline-block;
    padding:8px 14px;
    margin:4px;
    background:#fff;
    border-radius:6px;
    text-decoration:none;
    color:#007185;
    font-size:14px;
    box-shadow:0 2px 5px rgba(0,0,0,0.08);
    transition:0.2s ease;
}

.page-btn:hover{
    background:#007185;
    color:#fff;
}

.active-page{
    background:#007185;
    color:#fff;
    font-weight:bold;
}

.dots{
    padding:0 8px;
    color:#888;
}
/* ===== Launcher Animation ===== */
.modal{
display:none;
position:fixed;
inset:0;
background:rgba(0,0,0,0.4);
justify-content:flex-end;
align-items:flex-start;
padding:80px 30px;
z-index:999;
}
.modal.show{display:flex;}

.modal-content{
background:#fff;
width:340px;
border-radius:18px;
padding:20px;
box-shadow:0 10px 25px rgba(0,0,0,0.2);
transform:translateY(-30px);
opacity:0;
transition:all 0.35s ease;
}

.modal.show .modal-content{
transform:translateY(0);
opacity:1;
}

/* ===== Launcher Header ===== */
.launcher-header{
margin-bottom:18px;
}

.launcher-title{
display:flex;
justify-content:space-between;
align-items:center;
}

.launcher-title h2{
margin:0;
font-size:18px;
color:#007185;
font-weight:600;
}

/* Close Button */
.close-launcher{
font-size:22px;
cursor:pointer;
color:#888;
transition:0.2s ease;
}

.close-launcher:hover{
color:#007185;
transform:scale(1.1);
}

/* Divider Line */
.launcher-divider{
height:1px;
background:linear-gradient(to right,#007185,transparent);
margin:12px 0 10px;
border-radius:2px;
}

/* App Grid */
.app-grid{
display:grid;
grid-template-columns:repeat(3,1fr);
gap:20px;
text-align:center;
}

.app-item{
text-decoration:none;
color:#333;
font-size:13px;
display:flex;
flex-direction:column;
align-items:center;
padding:10px 5px;
border-radius:12px;
transition:0.2s ease;
}

.app-item:hover{
background:#f1f3f4;
}

.app-item img{
width:40px;
height:40px;
margin-bottom:8px;
}
/* ===== No Result Found Design ===== */
.no-result-box{
    background:#fff;
    padding:40px 20px;
    border-radius:14px;
    text-align:center;
    box-shadow:0 2px 8px rgba(0,0,0,0.08);
    margin:20px 0;
}

.no-result-box img{
    width:120px;
    margin-bottom:15px;
    opacity:0.8;
}

.no-result-box h2{
    margin:10px 0 8px;
    color:#007185;
    font-size:22px;
}

.no-result-box p{
    color:#666;
    font-size:14px;
}
.logo{
    margin-bottom:10px;
}

.logo img{
    width:35px;     /* Change width here */
    height:auto;     /* Keeps ratio */
    object-fit:contain;
}
.booking-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:8px 14px;
    font-size:15px;
    border-radius:22px;
    background:#E05619;
    color:#fff;
    text-decoration:none;
    margin-left:10px;
    height:30px;
    white-space:nowrap;
    transition:0.3s ease;
}

.booking-btn:hover{
    background:#e68900;
}

/* ===== Transparent Fade Ticker ===== */

.ticker-wrapper{
    position:relative;
    width:100%;
    overflow:hidden;
    margin-top:25px;
    height:40px;
}

/* Fade Left */
.ticker-wrapper::before,
.ticker-wrapper::after{
    content:"";
    position:absolute;
    top:0;
    width:80px;
    height:100%;
    z-index:2;
    pointer-events:none;
}

.ticker-wrapper::before{
    left:0;
    background:linear-gradient(to right, #f3f3f3, transparent);
}

.ticker-wrapper::after{
    right:0;
    background:linear-gradient(to left, #f3f3f3, transparent);
}

/* ===== Fade Ticker Version ===== */

.ticker{
    position:relative;
    height:40px;
    display:flex;
    align-items:center;
    justify-content:center;
}

.ticker a{
    position:absolute;
    opacity:0;
    transition:opacity 0.8s ease;
    text-decoration:none;
    color:#007185;
    font-size:14px;
}

.ticker a.active{
    opacity:1;
}

.ticker a{
    text-decoration:none;
    color:#007185;
    font-size:14px;
    transition:0.2s ease;
}

.ticker a:hover{
    color:#000;
    transform:scale(1.05);
}
</style>

<script type="application/ld+json">
{
 "@context": "https://schema.org",
 "@type": "WebSite",
 "name": "GoMAPS",
 "url": "https://search.gomaps.in/",
 "potentialAction": {
   "@type": "SearchAction",
   "target": "https://search.gomaps.in/?q={search_term_string}",
   "query-input": "required name=search_term_string"
 }
}
</script>
</head>

<body class="<?php echo !empty($search) ? 'has-search' : ''; ?>">

<div class="header">

<div class="top-left-logo">
    <a href="index.php">
        <img src="assets/gomaps-logo.png" alt="GoMAPS Logo">
    </a>
</div>

<?php if($enableLauncher): ?>
<img src="https://cdn-icons-png.flaticon.com/128/15219/15219937.png" id="launcherBtn" class="launcher-btn" alt="Launcher">
<?php endif; ?>

<div class="logo">
    <img src="assets/uploads/logo/logo.png" alt="GoMAPS">GoMAPS
</div>
<div class="tagline">Search • Discover • Connect • Globally</div>

<form method="GET" id="searchForm" class="search-wrapper">
<div class="search-container">

<input type="text"
id="searchInput"
name="q"
value="<?php echo htmlspecialchars($search); ?>"
autocomplete="off"
required
maxlength="60"
pattern="[A-Za-z0-9 ]+"
title="Only letters and numbers allowed"
inputmode="search">
<span class="material-icons icon" id="clearIcon" style="display:none;">close</span>
<span class="material-icons icon" onclick="submitSearch()">search</span>
<span class="material-icons icon" id="micIcon">mic</span>
</div>
<div class="search-btn-wrapper">
    <button type="submit" class="search-btn">GoMAPS Search</button>

    <a href="booking.php" class="booking-btn">
        Booking
    </a>
</div>
</form>
<?php if(empty($search)) { ?>

<?php if($enableTrending): ?>
<?php
$trendingStmt = $log_conn->prepare("
    SELECT keyword, COUNT(*) as total
    FROM search_logs
    WHERE searched_at >= NOW() - INTERVAL 7 DAY
    GROUP BY keyword
    ORDER BY total DESC
    LIMIT 5
");
$trendingStmt->execute();
$trendingResult = $trendingStmt->get_result();
?>

<div style="margin-top:25px;text-align:center;">
    <h3 style="color:#007185;">🔥 Trending Searches</h3>

    <?php while($row = $trendingResult->fetch_assoc()): ?>
        <a href="?q=<?= urlencode($row['keyword']) ?>" 
           style="margin:0 8px;text-decoration:none;color:#007185;font-weight:600;">
            <?= htmlspecialchars($row['keyword']) ?>
        </a>
    <?php endwhile; ?>
</div>

<?php $trendingStmt->close(); ?>
<?php endif; ?>

<?php if($enableTicker): ?>
<div class="ticker-wrapper" id="landingTicker">
    <div class="ticker">
        <a href="#">🌍 Restaurants in Dubai</a>
        <a href="#">🏨 Hotels in Singapore</a>
        <a href="#">🏥 Hospitals in Chennai</a>
        <a href="#">🚗 Car Service in Toronto</a>
        <a href="#">💼 Digital Marketing New York</a>
        <a href="#">📦 Courier Services London</a>
        <a href="#">📦 List your Business for Free</a>
    </div>
</div>
<?php endif; ?>

<div class="landing-footer copyright">
    © <?php echo date("Y"); ?> PRITSCO. 
    <a href="terms.php">Terms</a> | 
    <a href="privacy.php">Privacy</a>
</div>

<?php } ?>

</div>

<?php if($enableLauncher): ?>
<div class="modal" id="appModal">
<div class="modal-content">

<div class="launcher-header">
    <div class="launcher-title">
        <h2>Menu</h2>
        <span class="close-launcher material-icons" id="closeLauncher">close</span>
    </div>
    <div class="launcher-divider"></div>
</div>

<div class="app-grid">
    <a href="#" class="app-item"><img src="https://cdn-icons-png.flaticon.com/128/2921/2921226.png">Listing</a>
    <a href="#" class="app-item"><img src="https://cdn-icons-png.flaticon.com/128/3790/3790058.png">Partner</a>
    <a href="#" class="app-item"><img src="https://cdn-icons-png.flaticon.com/128/8898/8898827.png">Support</a>
</div>

</div>
</div>
<?php endif; ?>

<?php if(strlen($cleanSearch) >= 2) { ?>
<div class="container" id="resultsContainer">

<?php if($sponsoredResult): ?>
<div class="card" style="border:2px solid #ff9800;background:#fff8e1;">
    <div class="card-content">
        <h3 style="color:#d35400;">🔥 Sponsored Result</h3>
        <p>
            <a href="sponsored_click.php?id=<?= $sponsoredResult['id'] ?>" 
               style="color:#007185;font-weight:bold;text-decoration:none;">
                Visit Sponsored Business
            </a>
        </p>
    </div>
</div>
<?php endif; ?>

<?php
$words = explode(" ", $cleanSearch);

$conditions = [];
$params = [];
$types = "";

foreach($words as $word){

    $word = trim($word);
    if(strlen($word) < 2) continue;

    $like = "%{$word}%";

    $conditions[] = "(
        title LIKE ?
        OR sub_title LIKE ?
        OR description LIKE ?
        OR slug LIKE ?
        OR social_options LIKE ?
        OR enquery_email LIKE ?
    )";

    for($i=0; $i<6; $i++){
        $params[] = $like;
        $types .= "s";
    }
}

if(empty($conditions)){
    echo "<div class='no-result-box'>";
    echo "<h2>Invalid Search</h2>";
    echo "<p>Please enter valid letters or numbers.</p>";
    echo "</div>";
    exit;
}

$whereClause = implode(" AND ", $conditions);

if($requireVerified){
    $whereClause .= " AND verification_status = 1";
}

if($requireIndexed){
    $whereClause .= " AND search_engine_indexing = 1";
}

$query="SELECT slug,title,sub_title,description,views,profile
FROM cards
WHERE $whereClause
ORDER BY views DESC
LIMIT ?,?";

$types .= "ii";
$params[] = $start;
$params[] = $limit;

$stmt = $conn->prepare($query);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result=$stmt->get_result();

$defaultImage="https://smartvcard.co.in/assets/uploads/logos/default-logo.png";

if($result->num_rows == 0){
echo "<div class='no-result-box'>";
echo "<img src='https://cdn-icons-png.flaticon.com/512/2748/2748558.png' alt='No Result'>";
echo "<h2>No Results Found</h2>";
echo "<p>We couldn’t find any matching results for <strong>\"".htmlspecialchars($search)."\"</strong>.</p>";
echo "<p>Please try different keywords or check your spelling.</p>";
echo "</div>";
}

while($row=$result->fetch_assoc()){

$profileImage=!empty($row['profile'])
?"https://smartvcard.co.in/assets/uploads/card-profile/".$row['profile']
:$defaultImage;

$cardUrl="https://smartvcard.co.in/".$row['slug'];

echo "<a href='".$cardUrl."' style='text-decoration:none;color:inherit;'>";
echo "<div class='card'>";
echo "<img src='".htmlspecialchars($profileImage)."' alt='Profile'>";
echo "<div class='card-content'>";
echo "<h3>".htmlspecialchars($row['title'])."</h3>";
echo "<p>".substr(strip_tags($row['description']),0,100)."...</p>";
echo "<div class='views'>👁 ".$row['views']." views</div>";
echo "</div></div></a>";
}

$stmt->close();
?>
<?php
/* ===== Professional Pagination Logic ===== */

$countQuery = "SELECT COUNT(*) as total FROM cards WHERE $whereClause";
$countStmt = $conn->prepare($countQuery);
$countStmt->bind_param(substr($types,0,-2), ...array_slice($params,0,-2));
$countStmt->execute();
$countResult = $countStmt->get_result();
$totalData = $countResult->fetch_assoc()['total'];

/* ===== UPDATE RESULT COUNT IN LOG DB ===== */
if(!empty($cleanSearch)){
    $updateStmt = $log_conn->prepare("
        UPDATE search_logs 
        SET result_count = ? 
        WHERE keyword = ? 
        ORDER BY id DESC 
        LIMIT 1
    ");
    $updateStmt->bind_param("is", $totalData, $cleanSearch);
    $updateStmt->execute();
    $updateStmt->close();
    /* ===== AUTO BLOCK ZERO RESULT SPAM ===== */

$zeroCheck = $log_conn->prepare("
    SELECT COUNT(*) as total
    FROM search_logs
    WHERE ip_address = ?
    AND result_count = 0
    AND searched_at >= NOW() - INTERVAL 10 MINUTE
");

$zeroCheck->bind_param("s", $user_ip);
$zeroCheck->execute();
$zeroData = $zeroCheck->get_result()->fetch_assoc();
$zeroCheck->close();

if($zeroData['total'] >= 15){

    $blockStmt = $log_conn->prepare("
        INSERT IGNORE INTO blocked_ips (ip_address)
        VALUES (?)
    ");
    $blockStmt->bind_param("s", $user_ip);
    $blockStmt->execute();
    $blockStmt->close();
}
}

$countStmt->close();

$totalPages = ceil($totalData / $limit);

if($totalData > 0){

    $startRecord = $start + 1;
    $endRecord = min($start + $limit, $totalData);

    echo "<div class='result-count'>";
    echo "Showing <strong>{$startRecord}-{$endRecord}</strong> of <strong>$totalData</strong> results";
    echo "</div>";
}

if($totalPages > 1){

    echo "<div class='pagination'>";

    if($page > 1){
        $prevPage = $page - 1;
        echo "<a href='?q=".urlencode($cleanSearch)."&page=".$prevPage."' class='page-btn'>«</a>";
    }

    $range = 2;
    $startPage = max(1, $page - $range);
    $endPage = min($totalPages, $page + $range);

    if($startPage > 1){
        echo "<a href='?q=".urlencode($cleanSearch)."&page=1' class='page-btn'>1</a>";
        if($startPage > 2){
            echo "<span class='dots'>...</span>";
        }
    }

    for($i = $startPage; $i <= $endPage; $i++){
        $active = ($i == $page) ? "active-page" : "";
        echo "<a href='?q=".urlencode($cleanSearch)."&page=".$i."' class='page-btn $active'>$i</a>";
    }

    if($endPage < $totalPages){
        if($endPage < $totalPages - 1){
            echo "<span class='dots'>...</span>";
        }
        echo "<a href='?q=".urlencode($cleanSearch)."&page=".$totalPages."' class='page-btn'>$totalPages</a>";
    }

    if($page < $totalPages){
        $nextPage = $page + 1;
        echo "<a href='?q=".urlencode($cleanSearch)."&page=".$nextPage."' class='page-btn'>»</a>";
    }

    echo "</div>";
}

$conn->close();
$log_conn->close();
?>

<div class="copyright">
© <?php echo date("Y"); ?> GoMAPS. 
<a href="terms.php">Terms</a> | 
<a href="privacy.php">Privacy</a>
</div>

</div>
<?php } ?>
<script>
/* ===== Launcher Modal ===== */
var modal = document.getElementById("appModal");
var launcher = document.getElementById("launcherBtn");

if(modal && launcher){
    launcher.onclick = function(){
        modal.classList.add("show");
    };

    modal.onclick = function(e){
        if(e.target === modal){
            modal.classList.remove("show");
        }
    };
}

var closeBtn = document.getElementById("closeLauncher");
if(closeBtn){
    closeBtn.onclick = function(){
        modal.classList.remove("show");
    };
}

/* ===== Search Input Controls ===== */
var searchInput = document.getElementById("searchInput");
var clearIcon = document.getElementById("clearIcon");
var micIcon = document.getElementById("micIcon");

function toggleClearIcon(){
    if(searchInput.value.trim().length > 0){
        clearIcon.style.display = "flex";
    }else{
        clearIcon.style.display = "none";
    }
}

if(searchInput){
    toggleClearIcon();
    searchInput.addEventListener("input", toggleClearIcon);

    clearIcon.onclick = function(){
        searchInput.value = "";
        toggleClearIcon();
        searchInput.focus();
    };
}

/* ===== Strict Input Protection ===== */
if(searchInput){
    searchInput.addEventListener("input", function () {
        this.value = this.value.replace(/[^a-zA-Z0-9\s]/g, '');
    });

    searchInput.addEventListener("paste", function (e) {
        e.preventDefault();
        let pasteData = (e.clipboardData || window.clipboardData).getData("text");
        pasteData = pasteData.replace(/[^a-zA-Z0-9\s]/g, '');
        document.execCommand("insertText", false, pasteData);
    });
}

/* ===== Voice Search ===== */
if(micIcon){
    micIcon.onclick = function(){
        if(!('webkitSpeechRecognition' in window)){
            alert("Voice search not supported");
            return;
        }

        var recognition = new webkitSpeechRecognition();
        recognition.lang = "en-IN";
        micIcon.classList.add("mic-active");
        recognition.start();

        recognition.onresult = function(event){
            searchInput.value = event.results[0][0].transcript;
            document.getElementById("searchForm").submit();
        };

        recognition.onend = function(){
            micIcon.classList.remove("mic-active");
        };
    };
}

function submitSearch(){
    document.getElementById("searchForm").submit();
}

/* ===== AJAX Search & Pagination ===== */

function loadResults(url){
    const container = document.getElementById("resultsContainer");

    if(!container) return;

    container.innerHTML = `
        <div class="loader">
            <div></div>
        </div>
    `;

    fetch(url)
    .then(response => response.text())
    .then(data => {

        const parser = new DOMParser();
        const doc = parser.parseFromString(data, "text/html");
        const newResults = doc.querySelector("#resultsContainer");

        if(newResults){
            container.innerHTML = newResults.innerHTML;
            window.scrollTo({ top: 0, behavior: "smooth" });
        }
    });
}

document.addEventListener("click", function(e){
    if(e.target.classList.contains("page-btn")){
        e.preventDefault();
        loadResults(e.target.href);
    }
});

/* ===== Live Search ===== */
let typingTimer;

if(searchInput){
    searchInput.addEventListener("keyup", function(){

        clearTimeout(typingTimer);

        typingTimer = setTimeout(function(){

            const query = searchInput.value.trim();
            const tickerWrapper = document.getElementById("landingTicker");

            if(query.length >= 1){
                if(tickerWrapper) tickerWrapper.style.display = "none";
            }else{
                if(tickerWrapper) tickerWrapper.style.display = "block";
            }

            if(query.length >= 2){
                loadResults("?q=" + encodeURIComponent(query));
            }

        }, 600);
    });
}
</script>
<!-- Scroll To Top Button -->
<button id="scrollTopBtn">
    <img src="https://cdn-icons-png.flaticon.com/128/17727/17727194.png" alt="Scroll To Top">
</button>

<script>
const scrollBtn = document.getElementById("scrollTopBtn");
let hideTimer;

window.addEventListener("scroll", function () {

    if (window.scrollY > 200) {
        scrollBtn.classList.add("show");

        clearTimeout(hideTimer);
        hideTimer = setTimeout(function () {
            scrollBtn.classList.remove("show");
        }, 2000);

    } else {
        scrollBtn.classList.remove("show");
    }
});

scrollBtn.addEventListener("click", function () {
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    });
});

/* ===== Animated Placeholder Typing Effect ===== */

const placeholderTexts = [
    "Search businesses worldwide...",
    "Restaurants in Dubai",
    "Hotels in Singapore",
    "CCTV installation London",
    "Digital Marketing New York",
    "Hospitals in Chennai",
    "Car Service in Toronto"
];

const input = document.getElementById("searchInput");

let textIndex = 0;
let charIndex = 0;
let isDeleting = false;
let typingSpeed = 80;

function typeEffect() {

    if (!input || document.activeElement === input) return;

    const currentText = placeholderTexts[textIndex];

    if (!isDeleting) {
        input.setAttribute("placeholder", currentText.substring(0, charIndex + 1));
        charIndex++;

        if (charIndex === currentText.length) {
            setTimeout(() => isDeleting = true, 1200);
        }
    } else {
        input.setAttribute("placeholder", currentText.substring(0, charIndex - 1));
        charIndex--;

        if (charIndex === 0) {
            isDeleting = false;
            textIndex = (textIndex + 1) % placeholderTexts.length;
        }
    }

    setTimeout(typeEffect, isDeleting ? 40 : typingSpeed);
}

if (input && input.value === "") {
    typeEffect();
}

if(input){
    input.addEventListener("focus", () => {
        input.setAttribute("placeholder", "");
    });
}

/* ===== Fade In / Fade Out Rotating Ticker ===== */

const tickerWrapper = document.getElementById("landingTicker");

if(tickerWrapper){

    const tickerLinks = tickerWrapper.querySelectorAll(".ticker a");

    let currentIndex = 0;
    const displayDuration = 3000; // 3 seconds visible
    const fadeDuration = 800;     // must match CSS transition

    function showNextTicker(){

        // Remove active from all
        tickerLinks.forEach(link => link.classList.remove("active"));

        // Activate current
        tickerLinks[currentIndex].classList.add("active");

        // Move to next index
        currentIndex = (currentIndex + 1) % tickerLinks.length;
    }

    // Start first item
    showNextTicker();

    setInterval(showNextTicker, displayDuration + fadeDuration);

}
</script>
</script>

</body>
</html>