<?php
// include "includes/db.php"; // Apni DB file include karein
date_default_timezone_set('Asia/Kolkata');

// 👇 CHANGE 1: YAHAN REDIRECT ADD KAREIN 👇
if (strpos($_SERVER['REQUEST_URI'], '/passing-record/all/all') !== false) {
    header("Location: https://satta4umatka.live/passing-record/", true, 301);
    exit;
}
// 👆 REDIRECT KHATAM 👆


// ==========================================
// 1. DATABASE CONNECTION
// ==========================================
try {
    $db = new PDO("mysql:host=localhost;dbname=4umatka", "root", "");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("❌ DB Connection Failed: " . $e->getMessage());
}

// ==========================================
// 2. FILTER & PAGINATION LOGIC
// ==========================================
$is_ajax     = isset($_GET['ajax']) && $_GET['ajax'] == '1';

// URL me agar koi date nahi hai, to default 'all' maana jayega
$is_all_days = empty($_GET['date']) || (isset($_GET['date']) && $_GET['date'] === 'all');

// Default Dates
$start_date = date('Y-m-d');
$end_date   = date('Y-m-d');

// URL se Date aur Range uthana
if (!empty($_GET['date']) && $_GET['date'] !== 'all' && $_GET['date'] !== 'range') {
    $is_all_days = false; // Agar specific date hai, to 'all_days' ko false karein
    $start_date = trim($_GET['date']);
    $end_date   = trim($_GET['date']);
}

if (!empty($_GET['start_date'])) {
    $start_date = trim($_GET['start_date']);
    $is_all_days = false; // Agar start date aayi hai, to 'all' nahi hai
}
if (!empty($_GET['end_date'])) {
    $end_date = trim($_GET['end_date']);
    $is_all_days = false; // Agar end date aayi hai, to 'all' nahi hai
}

// 🔥 Market pehle se hi 'all' par default hai
$filter_market = (!empty($_GET['market'])) ? trim($_GET['market']) : 'all';
if ($filter_market !== 'all') {
    $filter_market = strtoupper(str_replace('-', ' ', $filter_market));
}

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

// ==========================================
// 3. FETCH PRE-REQUISITE DATA
// ==========================================
// Fetch All Active Markets
$markets_stmt = $db->query("SELECT title FROM games WHERE is_active = 1 ORDER BY title ASC");
$all_markets  = $markets_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Predefined Panels
$panel_groups = [];
$stmt = $db->query("SELECT digit, panel_value FROM predefined_panels");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $digit = (int)$row['digit'];
    $panel_groups[$digit] = array_map('trim', explode(",", $row['panel_value']));
}

function getSingleDigit($panel, $panel_groups) {
    if (empty($panel) || $panel === '***') return null;
    foreach ($panel_groups as $digit => $panels) {
        if (in_array(trim($panel), $panels)) return (string)$digit;
    }
    return null;
}

// ==========================================
// 4. FETCH MAIN FREE GAME DATA
// ==========================================
$query = "
    SELECT f.*, r.open_digits, r.close_digits 
    FROM free_game f
    LEFT JOIN games g ON f.market = g.title
    LEFT JOIN results r ON g.game_id = r.game_id AND f.date = r.draw_date
";

$conditions = [];
if (!$is_all_days) {
    $conditions[] = "f.date BETWEEN :start_date AND :end_date";
}
if ($filter_market !== 'all') {
    $conditions[] = "f.market = :filter_market";
}

if (count($conditions) > 0) {
    $query .= " WHERE " . implode(" AND ", $conditions);
}

$query .= " ORDER BY f.date DESC, COALESCE(g.time_open, '23:59:00') ASC, f.id DESC LIMIT :limit OFFSET :offset";
$stmt = $db->prepare($query);

if (!$is_all_days) {
    $stmt->bindParam(':start_date', $start_date);
    $stmt->bindParam(':end_date', $end_date);
}
if ($filter_market !== 'all') {
    $stmt->bindParam(':filter_market', $filter_market);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ==========================================
// 5. CARD HTML GENERATION
// ==========================================
ob_start();
if (count($records) > 0) {
    foreach ($records as $record): 
        $market         = $record['market'];
        $formatted_date = date('d M Y', strtotime($record['date']));
        
        $open_guesses  = explode(",", $record['open']);
        $jodi_guesses  = explode(",", $record['jodi']);
        $panel_guesses = explode(",", $record['panel']);
        
        $res_open_panel  = trim($record['open_digits'] ?? '***');
        $res_close_panel = trim($record['close_digits'] ?? '***');
        
        $res_open_digit  = getSingleDigit($res_open_panel, $panel_groups);
        $res_close_digit = getSingleDigit($res_close_panel, $panel_groups);

        if ($res_open_digit !== null && $res_close_digit !== null) {
            $res_jodi = $res_open_digit . $res_close_digit;
        } elseif ($res_open_digit !== null) {
            $res_jodi = $res_open_digit . '*';
        } elseif ($res_close_digit !== null) {
            $res_jodi = '*' . $res_close_digit;
        } else {
            $res_jodi = '**';
        }
        
        $display_result = "$res_open_panel - $res_jodi - $res_close_panel";

        $overall_pass = false;
        foreach ($open_guesses as $num) { if ($num !== '' && ($num === $res_open_digit || $num === $res_close_digit)) $overall_pass = true; }
        foreach ($jodi_guesses as $num) { if ($num !== '' && $num === $res_jodi) $overall_pass = true; }
        foreach ($panel_guesses as $num) { if ($num !== '' && ($num === $res_open_panel || $num === $res_close_panel)) $overall_pass = true; }
        ?>
        
        <div class="col mb-4 d-flex justify-content-center">
            <div class="box bg-w" style="overflow: hidden; width: 100%; max-width: 380px;">
                <div class="bg-head" style="padding: 12px 10px; text-align: center;">
                    <h3 style="margin:0; font-size: 1.2rem; text-transform: uppercase; color: #fff; text-shadow: 1px 1px 2px #000;">
                        <?= htmlspecialchars($market) ?>
                    </h3>
                    <div style="font-size: 0.85rem; color: #fff; font-weight: bold; margin-top: 5px; text-shadow: 1px 1px 2px #000;">
                        📅 <?= $formatted_date ?>
                    </div>
                </div>

                <div class="bg-main mp" style="padding: 15px 10px; border-bottom: 2px solid var(--border); text-align: center;">
                    <?php if ($res_open_panel === '***' && $res_jodi === '**' && $res_close_panel === '***'): ?>
                        <?php if ($record['date'] === date('Y-m-d')): ?>
                            <div style="background: #e0f7fa; color: #00838f; padding: 5px 20px; border-radius: 8px; display: inline-block; font-size: 1.3rem; border: 2px dashed #00bcd4; font-weight: 900;">⏳ WAITING...</div>
                        <?php else: ?>
                            <div style="background: #ffecb3; color: #d84315; padding: 5px 20px; border-radius: 8px; display: inline-block; font-size: 1.3rem; border: 2px dashed #ff9800; font-weight: 900;">🏖️ HOLIDAY 🏖️</div>
                        <?php endif; ?>
                    <?php else: ?>
                        <p class="t24 text-white b900 mb-0"><?= $display_result ?></p>
                    <?php endif; ?>
                    
                    <div class="mt-2 text-center">
                        <?php if ($res_open_panel === '***' && $res_jodi === '**' && $res_close_panel === '***'): ?>
                            <span style="background: #6c757d; color: white; padding: 3px 15px; border-radius: 5px; border: 1px solid #fff; display: inline-block;" class="count b900">PENDING</span>
                        <?php else: ?>
                            <?php if($overall_pass): ?>
                                <span class="yellow count b900" style="padding: 3px 15px; border-radius: 5px; color: #000; border: 1px solid #000; display: inline-block;">PASS</span>
                            <?php else: ?>
                                <span style="background: red; color: white; padding: 3px 15px; border-radius: 5px; border: 1px solid #fff; display: inline-block;" class="count b900">FAIL</span>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="bg-w mp" style="padding: 15px 10px; text-align: center;">
                    <div class="time-color b900" style="font-size: 0.95rem; margin-bottom: 5px;">🔢 Open / Close</div>
                    <div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-bottom: 15px;">
                        <?php foreach ($open_guesses as $num): 
                            $is_pass = ($num !== '' && ($num === $res_open_digit || $num === $res_close_digit)); ?>
                            <span style="background: <?= $is_pass ? 'var(--res-color)' : '#f1f1f1' ?>; color: <?= $is_pass ? '#fff' : '#333' ?>; padding: 3px 12px; border-radius: 20px; font-weight: bold; border: 1px solid <?= $is_pass ? 'var(--border)' : '#ccc' ?>; <?= $is_pass ? 'box-shadow: 0 0 8px var(--border);' : '' ?>">
                                <?= htmlspecialchars($num) ?>
                            </span>
                        <?php endforeach; ?>
                    </div>

                    <div class="time-color b900" style="font-size: 0.95rem; margin-bottom: 5px;">🎰 Jodi</div>
                    <div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-bottom: 15px;">
                        <?php foreach ($jodi_guesses as $num): 
                            $is_pass = ($num !== '' && $num === $res_jodi); ?>
                            <span style="background: <?= $is_pass ? 'var(--res-color)' : '#f1f1f1' ?>; color: <?= $is_pass ? '#fff' : '#333' ?>; padding: 3px 12px; border-radius: 20px; font-weight: bold; border: 1px solid <?= $is_pass ? 'var(--border)' : '#ccc' ?>; <?= $is_pass ? 'box-shadow: 0 0 8px var(--border);' : '' ?>">
                                <?= htmlspecialchars($num) ?>
                            </span>
                        <?php endforeach; ?>
                    </div>

                    <div class="time-color b900" style="font-size: 0.95rem; margin-bottom: 5px;">🎲 Panel</div>
                    <div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-bottom: 5px;">
                        <?php foreach ($panel_guesses as $num): 
                            $is_pass = ($num !== '' && ($num === $res_open_panel || $num === $res_close_panel)); ?>
                            <span style="background: <?= $is_pass ? 'var(--res-color)' : '#f1f1f1' ?>; color: <?= $is_pass ? '#fff' : '#333' ?>; padding: 3px 12px; border-radius: 20px; font-weight: bold; border: 1px solid <?= $is_pass ? 'var(--border)' : '#ccc' ?>; <?= $is_pass ? 'box-shadow: 0 0 8px var(--border);' : '' ?>">
                                <?= htmlspecialchars($num) ?>
                            </span>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        
        
<?php endforeach; 
}
$cards_html = ob_get_clean();

// AJAX Return
if ($is_ajax) {
    echo $cards_html;
    exit;
}

// ==========================================
// 6. SEO, SCHEMA & DYNAMIC CONTENT SETUP
// ==========================================
$page_title_seo   = ($filter_market !== 'all') ? ucwords(strtolower($filter_market)) : 'All Markets';
$canonical_market = strtolower(str_replace(' ', '-', $filter_market));

// URL LOGIC UPDATE
if ($filter_market === 'all') {
    $canonical_url = "https://satta4umatka.live/passing-record/";
} else {
    $canonical_url = "https://satta4umatka.live/passing-record/all/" . $canonical_market;
}

// 🔥 NAYA SYSTEM: Fetch SEO data from 'all_pass_pages' table using canonical market slug 🔥
$seo_slug = $canonical_market; // Example: 'kalyan', 'madhur-day', or 'all'
$stmt_seo = $db->prepare("SELECT title, description, content, content2, schema_data FROM all_pass_pages WHERE slug = :slug LIMIT 1");
$stmt_seo->execute(['slug' => $seo_slug]);
$seo_data = $stmt_seo->fetch(PDO::FETCH_ASSOC);

$seo_meta_title   = $seo_data['title'] ?? "";
$seo_meta_desc    = $seo_data['description'] ?? "";
$seo_schema_data  = $seo_data['schema_data'] ?? "";
$seo_top_content  = $seo_data['content'] ?? ""; 
$seo_bottom_content = $seo_data['content2'] ?? ""; 

// 🔥 Pagination Suffix for Unique Content 🔥
$page_suffix = ($page > 1) ? " - Page " . $page : "";

$page_name  = $page_title_seo . $page_suffix;
$page_url   = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$today_date = date("Y-m-d");

$market_seed = crc32($filter_market); 

// 🔥 Internal Linking Array 🔥
$internal_links = [];
if (!empty($all_markets)) {
    foreach ($all_markets as $m) {
        $market_name = $m['title'];
        
        // 👇 MAIN FIX: Jo market currently open hai usko ignore karo taaki wo khud ko link na kare 👇
        if (strtolower($market_name) === strtolower($filter_market)) {
            continue; 
        }
        // 👆 ----------------------------------------------------------------------------- 👆

        $market_slug = strtolower(str_replace(' ', '-', $market_name));
        $internal_links[$market_name] = "/passing-record/all/" . $market_slug;
    }
}

// 🔥 Advanced Auto Internal Linking Function 🔥
function autoInternalLink($content, $links) {
    static $already_linked = [];
    uksort($links, function($a, $b) { return strlen($b) - strlen($a); });

    foreach ($links as $keyword => $url) {
        if (isset($already_linked[$keyword])) continue;
        $escaped_keyword = preg_quote($keyword, '/');
        $parts = preg_split('/(<a\b[^>]*>.*?<\/a>)/is', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
        
        $replaced = false;
        $new_content = '';
        foreach ($parts as $part) {
            if (!$replaced && stripos($part, '<a') !== 0) {
                $new_part = preg_replace(
                    '/\b('.$escaped_keyword.')\b/i', 
                    '<a href="'.$url.'" title="'.$keyword.' Matka Result" class="seo-link">$1</a>', 
                    $part, 1, $count
                );
                if ($count > 0) {
                    $replaced = true;
                    $already_linked[$keyword] = true;
                    $part = $new_part;
                }
            }
            $new_content .= $part;
        }
        $content = $new_content;
    }
    return $content;
}
?>

<?php include dirname(__DIR__, 3) . "/includes/minify.php"; ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <?php
    // SEO Meta Title Logic (Fallback to generated title if DB is empty)
    $final_meta_title = !empty($seo_meta_title) ? $seo_meta_title . $page_suffix : htmlspecialchars($page_title_seo) . " Satta Matka Result Chart 2026 (Live Results + History)" . $page_suffix;
    
    // SEO Meta Description Logic (Fallback to generated desc if DB is empty)
    $final_meta_desc = !empty($seo_meta_desc) ? $seo_meta_desc . $page_suffix : "Check the latest Satta Matka " . htmlspecialchars($page_title_seo) . " all passing records. Get daily updated open, close, jodi, and panel results to verify our VIP predictions accurately." . $page_suffix;
    ?>
    <title><?= $final_meta_title ?></title>
    <meta name="description" content="<?= $final_meta_desc ?>">
    
    <?php if (($is_all_days && $page == 1) || (!isset($_GET['date']) && !isset($_GET['start_date']) && $page == 1)): ?>
        <meta name="robots" content="index, follow">
        <link rel="canonical" href="<?= $canonical_url ?>">
    <?php else: ?>
        <meta name="robots" content="noindex, follow"> 
    <?php endif; ?>
    
    <?php include dirname(__DIR__, 3) . "/content/themes/default/mod/_meta.php" ; ?>
    
    <link rel="preconnect" href="https://cdn.jsdelivr.net">
    <link rel="dns-prefetch" href="https://cdn.jsdelivr.net">

    <link rel="preload" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    </noscript>

    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "WebPage",
      "name": "<?= htmlspecialchars($page_name) ?>",
      "url": "<?= htmlspecialchars($page_url) ?>",
      "description": "Get fastest <?= htmlspecialchars($page_name) ?> with live updates, jodi, panel, open close and passing record.<?= $page_suffix ?>",
      "inLanguage": "en",
      "datePublished": "<?= $today_date ?>",
      "dateModified": "<?= $today_date ?>"
    }
    </script>
    <script type="application/ld+json">
    {
     "@context": "https://schema.org",
     "@type": "BreadcrumbList",
     "itemListElement": [
      {
       "@type": "ListItem",
       "position": 1,
       "name": "Home",
       "item": "https://<?= $_SERVER['HTTP_HOST'] ?>/"
      },
      {
       "@type": "ListItem",
       "position": 2,
       "name": "Passing Record",
       "item": "https://<?= $_SERVER['HTTP_HOST'] ?>/passing-record/"
      },
      {
       "@type": "ListItem",
       "position": 3,
       "name": "<?= htmlspecialchars($page_title_seo) ?>",
       "item": "<?= htmlspecialchars($canonical_url) ?>"
      }
     ]
    }
    </script>

    <?php if(!empty($seo_schema_data)) { echo $seo_schema_data; } ?>

    <style>
        :root{--text:#000;--border:#e800a9;--bg-w:#fff;--bg-hed:#4a0036;--text-shadow:#aba8a8;--box-shadow:rgba(145, 138, 142);--h1:#ff0077;--sub-head:#f2ac71;--white:#fff;--time-color:#45153e;--res-color:#94005b;}
        html{overflow-x:hidden;scroll-behavior:smooth;}
        body{font-family:'Roboto', 'Open Sans', Arial, sans-serif;font-size:16px;line-height:1.5;color:#333;text-align:center;padding:3px 10px;margin:0;font-weight:700; background-color: #f8f9fa;}
        h1, h2, h3, h4, h5, h6{font-family:'Montserrat', 'Lato', 'Helvetica', sans-serif;font-weight:700;margin-top:1.2em;margin-bottom:0.5em;color:#111;}
        a{font-family:'Poppins', 'Arial', sans-serif;text-decoration:none;color:#007BFF;}
        a:hover{text-decoration:underline;}
        p{margin-bottom:1em; font-weight:normal; font-size:15px;}
        @media (max-width:768px){body{font-size:15px;}}
        .yellow{background:yellow;}
        ul, ol, li{font-size:12px;}
        ol{text-align:left;}
        ul{list-style:none;padding:0;}
        .count{font-size:14px;}
        .b900{font-weight:700;}
        .mp{margin:0;padding:0;}
        .blue{color:blue;}
        .contener{margin:5px auto; padding:5px; max-width: 1200px; text-align: center;}
        .contener h2, .contener h4, .contener h5, .contener h6{margin:0;padding:0;font-size:17px;}
        .contener h1{margin:0;padding:0;font-size:24px; color:var(--border);}
        .box{border-radius:10px 10px 0px 0px;border:2px solid var(--border); margin: 0 auto;}
        .box h2, .box h3{text-align:center;font-size:16px;margin:10px 0 5px;}
        .bg-w{background:var(--bg-w);}
        .orignal{color:#ffddd9;}
        .t, .t24{font-size:24px;}
        .t15{font-size:12px;}
        .t20{font-size:20px;}
        .text{color:var(--text);}
        .text-white{color:var(--white);}
        .time-color{color:var(--time-color);}
        .res-color{color:var(--res-color);}
        .bg-main{background-color:var(--bg-hed);color:var(--bg-w);}
        .bg-head{background:linear-gradient(90deg, #5c0054 0%, #ffd5b5 50%, #5c0054 100%);position:relative;color:#000;}
        .zone{text-decoration:none;display:block;margin:10px auto;border:2px solid var(--border);padding:10px 0;border-radius:10px 10px 0px 0px; max-width: 600px;}
        .ad-link-box{display:block;text-decoration:none;margin:20px auto; max-width: 400px;}
        .ad-content{border:2px solid #e800a9;border-radius:12px;padding:12px;text-align:center;background:linear-gradient(90deg, #fff, #ffe6f7);position:relative;transition:0.3s;}
        .ad-content:hover{transform:scale(1.02);box-shadow:0 0 12px rgba(232, 0, 169, 0.4);}
        .ad-tag{position:absolute;top:-8px;left:10px;background:#fff;color:#999;font-size:10px;padding:2px 6px;}
        .faq-section{max-width:800px;margin:30px auto;padding:10px;font-family:Arial, sans-serif; text-align: left;}
        .faq-item{border:1px solid #ddd;border-radius:5px;margin-bottom:10px;overflow:hidden;}
        .faq-toggle{display:none;}
        .faq-question{display:block;padding:15px;font-size:14px;background:#f5f5f5;cursor:pointer;font-weight:bold;position:relative;}
        .faq-question::after{content:'+';position:absolute;right:20px;font-size:20px;}
        .faq-toggle:checked + .faq-question::after{content:'−';}
        .faq-answer{max-height:0;overflow:hidden;background:#fafafa;padding:0 15px;transition:max-height 0.4s ease, padding 0.4s ease;}
        .faq-toggle:checked + .faq-question + .faq-answer{max-height:500px;padding:15px;}
        .breadcrumb-nav { background: #fff; padding: 10px 15px; border-radius: 8px; border: 1px solid var(--border); margin: 0 auto 15px auto; max-width: 800px; font-size: 14px; font-weight: 700; text-align: left; }
        .breadcrumb-nav a { color: var(--time-color); text-decoration: none; transition: 0.3s;}
        .breadcrumb-nav a:hover { color: var(--h1); text-decoration: underline;}
        .breadcrumb-nav span { color: var(--res-color); }
        .seo-link { color: #007BFF; text-decoration: none; font-weight: bold; border-bottom: 1px dashed #007BFF;}
        .seo-link:hover { color: var(--h1); border-bottom: 1px solid var(--h1);}
        .related-markets { background: #fff; border: 2px solid var(--border); border-radius: 10px; padding: 15px; margin: 30px auto; max-width: 800px; text-align: center; }
        .related-markets h3 { color: var(--time-color); font-size: 20px; border-bottom: 2px dashed #ccc; padding-bottom: 10px; margin-top: 0; }
        .related-markets ul { list-style: none; padding: 0; margin: 15px 0 0 0; display: flex; flex-wrap: wrap; gap: 10px; justify-content: center;}
        .related-markets li { display: inline-block; }
        .related-markets li a { background: var(--bg-hed); color: #fff; padding: 8px 18px; border-radius: 20px; text-decoration: none; font-size: 14px; border: 1px solid var(--border); transition: 0.3s; display: block;}
        .related-markets li a:hover { background: #fff; color: var(--bg-hed); transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.2);}
        
        .floting_r { position: fixed; padding: 5px 8px; bottom: 7px; right: 5px; font-size: 14px; margin-bottom: 30px; text-decoration: none;}
    </style>  
</head>
<body>

<div class="contener">
    <nav class="breadcrumb-nav">
        <a href="/">Home</a> »
        <a href="/passing-record/">Passing Record</a> »
        <span><?= htmlspecialchars($page_title_seo) ?></span>
    </nav>
    
    <div class="contener box time-color" style="padding: 10px;">
        <?php
        $page_title_tc = ucwords(strtolower($page_title_seo));
        $safe_title_tc = htmlspecialchars($page_title_tc);

        // SEO Link Generator Logic
        $current_market_lower = strtolower($page_title_seo);
        $words = explode(' ', $page_title_seo);
        $base_name = strtolower($words[0]); 

        $related_markets = [];
        if (!empty($internal_links)) {
            foreach($internal_links as $name => $url) {
                $name_lower = strtolower($name);
                if($name_lower !== $current_market_lower && $name_lower !== 'all markets') {
                    if (strpos($name_lower, $base_name) !== false) {
                        $related_markets[ucwords($name_lower)] = $url;
                    }
                }
            }
        }

        $final_mentions = array_slice($related_markets, 0, 2, true);
        $mention_names  = array_keys($final_mentions);
        $mention_urls   = array_values($final_mentions);

        $smart_mention_en = "";
        $smart_mention_hi = "";
        
        if(count($final_mentions) == 2) {
            $smart_mention_en = " While checking your " . $safe_title_tc . " live matka result, you can also see our <a href='{$mention_urls[0]}' style='color:#007BFF;font-weight:bold;'>satta {$mention_names[0]} result today</a> and the <a href='{$mention_urls[1]}' style='color:#007BFF;font-weight:bold;'>{$mention_names[1]} live chart</a>.";
            $smart_mention_hi = " इसके साथ ही, आप <a href='{$mention_urls[0]}' style='color:#007BFF;font-weight:bold;'>{$mention_names[0]} रिजल्ट टुडे</a> और <a href='{$mention_urls[1]}' style='color:#007BFF;font-weight:bold;'>{$mention_names[1]} लाइव चार्ट</a> के अपडेट्स भी देख सकते हैं।";
        } elseif(count($final_mentions) == 1) {
            $smart_mention_en = " While checking your " . $safe_title_tc . " live matka result, you can also see our <a href='{$mention_urls[0]}' style='color:#007BFF;font-weight:bold;'>satta {$mention_names[0]} result today</a>.";
            $smart_mention_hi = " इसके साथ ही, आप <a href='{$mention_urls[0]}' style='color:#007BFF;font-weight:bold;'>{$mention_names[0]} रिजल्ट टुडे</a> के अपडेट्स भी देख सकते हैं।";
        }

        // --- ORIGINAL ENGLISH PARAGRAPHS ---
        $intro_1 = "Searching for today's real ".$safe_title_tc." result? You are at the best spot. We update the fastest ".$safe_title_tc." live result and correct satta matka ".$safe_title_tc." final ank right here on satta4umatka.live. We get these numbers straight from main sources because we know you need real-time updates for your ".$safe_title_tc." guessing number." . $smart_mention_en;
        $p1 = "It is super easy to track numbers using our live ".$safe_title_tc." chart. Whenever a new number comes out, we post the ".$safe_title_tc." result today on this very page. You will also find the ".$safe_title_tc." open close guessing result and today's lucky number chart. People trust our site because our ".$safe_title_tc." live records never make mistakes. Just check the daily passing record and ".$safe_title_tc." jodi chart to find your matka fix jodi easily.";
        $p2 = "Want a clever trick? Check old satta records before you play. When you look at the ".$safe_title_tc." panel chart on our site, you will notice certain patterns repeating. This past satta matka ".$safe_title_tc." result history helps you guess the next ".$safe_title_tc." final ank much better. We keep the data clean so you can spot trends fast. It really helps when you are trying to guess your ".$safe_title_tc." fix jodi.";
        $p3 = "Our team works daily to bring you fresh satta data. If you watch the live ".$safe_title_tc." chart closely, you might catch which matka fix jodi shows up again. This little trick is helpful for both beginners and old players in the satta matka market. From the ".$safe_title_tc." panel chart to the ".$safe_title_tc." jodi chart, everything is right here. Using our site makes checking your daily matka performance a breeze.";

        // Link Injection Pool
        $random_link_pool = [];
        if (!empty($internal_links)) {
            foreach($internal_links as $name => $url) {
                $name_lower = strtolower($name);
                if($name_lower !== $current_market_lower && $name_lower !== 'all markets') {
                    $random_link_pool[ucwords($name_lower)] = $url; 
                }
            }
        }

        srand($market_seed); 
        $random_injections = [];
        $max_links = min(count($random_link_pool), 4); 
        
        if($max_links > 0) {
            $rand_names = (array) array_rand($random_link_pool, $max_links);
            $anchor_templates = [
                " We also suggest checking the <a href='{url}' class='seo-link'>{name} result today</a> for fast updates.",
                " It is a good idea to look at the <a href='{url}' class='seo-link'>{name} live chart</a> for your next game.",
                " See the best numbers on our <a href='{url}' class='seo-link'>satta matka {name} final ank</a> page.",
                " Make sure to check the <a href='{url}' class='seo-link'>{name} open close guessing result</a> too."
            ];

            foreach($rand_names as $index => $n) {
                $u = $random_link_pool[$n];
                $template = str_replace(['{url}', '{name}'], [$u, $n], $anchor_templates[$index % 4]);
                $random_injections[] = $template;
            }
        }

        $para_vars = ['intro_1', 'p1', 'p2', 'p3'];
        shuffle($para_vars); 

        for ($i = 0; $i < count($random_injections); $i++) {
            if (isset($para_vars[$i])) {
                ${$para_vars[$i]} .= $random_injections[$i];
            }
        }

        // 👇 FIX 2: DB TEXT KE ANDAR SMART LINKS KA INJECTION 👇
        if (!empty($seo_top_content)) {
            // Pehle keywords link karega
            $seo_top_content = autoInternalLink($seo_top_content, $internal_links);
            
            // Fir DB content ke end me automatically 2 links add kar dega (Agar DB content me koi market mention nahi tha)
            $top_injections = array_slice($random_injections, 0, 2);
            if (count($top_injections) > 0) {
                $seo_top_content .= "<p style='margin-top: 10px; font-size: 15px; font-weight: normal;'>" . implode(" ", $top_injections) . "</p>";
            }
        }
        // 👆 ------------------------------------------------ 👆
        ?>

        <?php if (!empty($seo_top_content)): ?>
            <div class="text-left" style="margin-bottom: 15px;">
                <?= $seo_top_content ?>
            </div>
        <?php else: ?>
            <p><?= autoInternalLink($intro_1, $internal_links) ?></p>
            <h1 class=""><?= $safe_title_tc ?> Result Today, Live Chart & Final Ank Update <?= $page_suffix ?></h1>
            <p><?= autoInternalLink($p1, $internal_links) ?></p>
        <?php endif; ?>
        </div>

    <h2 class="text-center mb-4 time-color b900">🏆 Last updated: <?= date("d F Y h:i A") ?> Passing Records</h2>

    <div class="box bg-w p-3 mb-5 shadow-sm" style="max-width: 800px;">
        <form method="GET" action="" class="row g-3 align-items-center justify-content-center" id="filterForm">
            <div class="col-md-5 col-sm-12 text-center">
                <label class="form-label time-color b900 d-block">Select Date Range</label>
                <div class="input-group justify-content-center">
                    <div class="input-group-text bg-main text-white" style="border-color: var(--border);">
                        <input class="form-check-input mt-0" type="checkbox" name="all_days" id="allDaysCheck" value="1" <?= $is_all_days ? 'checked' : '' ?>>
                        <label class="ms-2 mb-0 b900" style="font-size: 0.9rem;" for="allDaysCheck">All</label>
                    </div>
                    <input type="date" name="start_date" id="startDateInput" class="form-control" style="border-color: var(--border); max-width: 140px;" value="<?= htmlspecialchars($start_date) ?>" <?= $is_all_days ? 'disabled' : '' ?>>
                    <span class="input-group-text" style="background: #ffd5b5; border-color: var(--border); color: #000;">To</span>
                    <input type="date" name="end_date" id="endDateInput" class="form-control" style="border-color: var(--border); max-width: 140px;" value="<?= htmlspecialchars($end_date) ?>" <?= $is_all_days ? 'disabled' : '' ?>>
                </div>
            </div>

            <div class="col-md-4 col-sm-12 text-center">
                <label class="form-label time-color b900 d-block">Select Market</label>
                <select name="market" class="form-select mx-auto" style="border-color: var(--border); max-width: 250px;">
                    <option value="all" <?= ($filter_market === 'all') ? 'selected' : '' ?>>All Markets</option>
                    <?php foreach ($all_markets as $m): ?>
                        <option value="<?= $m['title'] ?>" <?= ($filter_market == $m['title']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($m['title']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-3 col-sm-12 text-center mt-4">
                <button type="submit" class="btn b900 text-white bg-main px-4 py-2" style="border: 2px solid var(--border); border-radius: 30px;">🔍 Filter Records</button>
            </div>
        </form>
    </div>

    <div id="records-container" class="row row-cols-1 row-cols-md-2 row-cols-lg-3 justify-content-center">
        <?= $cards_html ?>
        <?php if (count($records) == 0 && !$is_ajax): ?>
            <div class="col-12 w-100 d-flex justify-content-center">
                <div class="box bg-w p-4 text-center b900 res-color" style="max-width: 500px;">
                    ⚠️ No passing records found in this date range.
                </div>
            </div>
        <?php endif; ?>
    </div>

    <?php if (count($records) == $limit): ?>
        <div class="text-center mt-4 mb-5">
            <button id="loadMoreBtn" class="btn b900 px-5 py-3" style="background: linear-gradient(90deg, #5c0054 0%, #ffd5b5 50%, #5c0054 100%); color:#fff; border: 2px solid var(--border); border-radius: 50px; text-shadow: 1px 1px #000; font-size: 1.1rem; box-shadow: 0 4px 10px rgba(0,0,0,0.2);">
                ⬇️ 👉 View More Records 🔥⬇️
            </button>
        </div>
    <?php endif; ?>

    <a href="#" class="zone bg-w text-center">
        <p class="t20 blue b900">Click Here To Visit VIP Zone</p>
        <p class="yellow count mx-auto d-inline-block px-3 py-1" style="border-radius: 5px;">100% Fix Game</p>
    </a>

    <div class="related-markets">
        <h3>🔗 Related Matka Markets (Live Results)</h3>
        <ul>
            <?php foreach($internal_links as $name => $url): ?>
                <li><a href="<?= htmlspecialchars($url) ?>"><?= htmlspecialchars($name) ?> Result Today</a></li>
            <?php endforeach; ?>
        </ul>
    </div>

    <a href="#" class="ad-link-box">
        <div class="ad-content">
            <span class="ad-tag">Ad</span>
            <h3 class="b900" style="color:#d10077;">Play Matka Online</h3>
            <p class="b900">Get the best rates and fastest withdrawals.</p>
            <button class="b900 bg-main border-0 py-2 px-4 text-white" style="border-radius: 20px;">Download App</button>
        </div>
    </a>
</div>

<div class="contener box time-color" style="padding: 10px;">

    <?php 
    // 👇 FIX 3: BOTTOM DB TEXT KE ANDAR SMART LINKS KA INJECTION 👇
    if (!empty($seo_bottom_content)) {
        $seo_bottom_content = autoInternalLink($seo_bottom_content, $internal_links);
        
        $bot_injections = array_slice($random_injections, 2, 2);
        if (count($bot_injections) > 0) {
            $seo_bottom_content .= "<p style='margin-top: 10px; font-size: 15px; font-weight: normal;'>" . implode(" ", $bot_injections) . "</p>";
        }
    }
    // 👆 ------------------------------------------------ 👆
    ?>

    <?php if (!empty($seo_bottom_content)): ?>
        <div class="text-left" style="margin-top: 15px; margin-bottom: 20px;">
            <?= $seo_bottom_content ?>
        </div>
    <?php else: ?>
        <h2>Why Follow The <?= $safe_title_tc ?> Final Ank & Satta Passing Record Here?</h2>
        <p><?= autoInternalLink($p2, $internal_links) ?></p>

        <h3>Daily <?= $safe_title_tc ?> Matka Guessing Number & Live History</h3>
        <p><?= autoInternalLink($p3, $internal_links) ?></p>

        <?php
        // --- ORIGINAL HINDI TEXT ---
        @include_once 'market_translations.php';
        $hindi_market_name = $market_translations[$page_title_seo] ?? $page_title_tc;

        $hindi_para = "यहाँ " . htmlspecialchars($hindi_market_name) . " सट्टा मटका का डेली पासिंग रिकॉर्ड देखना बहुत आसान है। हम इस पेज पर मटका ओपन, क्लोज, जोड़ी और पैनल के रिजल्ट एकदम साफ-साफ दिखाते हैं। रोज़ का पास और फेल स्टेटस बहुत ही सरल भाषा में होता है। इससे आपको अपना अगला मटका गेसिंग नंबर और टुडे लकी नंबर चार्ट निकालने में मदद मिलेगी। हमारी वेबसाइट पर आपको हमेशा एकदम तेज़ और सही जानकारी ही मिलेगी।" . $smart_mention_hi;
        ?>

        <h4><?= htmlspecialchars($hindi_market_name) ?> सट्टा मटका का १००% सही दैनिक रिकॉर्ड</h4>
        <p><?= autoInternalLink($hindi_para, $internal_links) ?></p>

        <hr style="margin: 20px 0;">

        <p><strong>Conclusion:</strong> In short, getting fast matka info changes the game for your <?= $safe_title_tc ?> open close guessing result. Save satta4umatka.live in your browser for daily updates. Just keep checking the satta matka <?= $safe_title_tc ?> result today along with our live charts to stay one step ahead. Best of luck with your fix jodi and calculations!</p>
        <br>
    <?php endif; ?>

    <?php
    // Dynamic Hidden SEO Layer
    $hidden_seo_keywords = [
        $page_title_tc . " result today",
        $page_title_tc . " live result",
        "satta matka " . $page_title_tc,
        $page_title_tc . " final ank",
        $page_title_tc . " jodi chart",
        $page_title_tc . " panel chart",
        $page_title_tc . " guessing number",
        $page_title_tc . " fix jodi",
        "fast " . $page_title_tc . " result",
        "satta " . $page_title_tc . " result",
        "live " . $page_title_tc . " chart",
        $page_title_tc . " open close guessing result",
        $page_title_tc . " matka result",
        "fastest " . $page_title_tc . " update",
        $page_title_tc . " passing record",
        "satta matka official result",
        $page_title_tc . " today lucky number chart"
    ];
    
    shuffle($hidden_seo_keywords);
    srand(); // Reset Seed
    ?>

    
<details>
    <summary>More Results &amp; Keywords</summary>
<p>
 <?= htmlspecialchars(implode(", ", $hidden_seo_keywords)) ?>
</p>
</details>
    
    
    <div style="display:none;">
       
    </div>
</div>

</div>

<script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const allDaysCheck = document.getElementById('allDaysCheck');
    const startDateInput = document.getElementById('startDateInput');
    const endDateInput = document.getElementById('endDateInput');

    allDaysCheck.addEventListener('change', function() {
        if (this.checked) {
            startDateInput.disabled = true;
            endDateInput.disabled = true;
        } else {
            startDateInput.disabled = false;
            endDateInput.disabled = false;
        }
    });

    document.getElementById('filterForm').addEventListener('submit', function(e) {
        e.preventDefault(); 
        
        const isAllDays = document.getElementById('allDaysCheck').checked;
        let marketVal = document.querySelector('select[name="market"]').value;
        
        if (marketVal !== 'all') {
            marketVal = marketVal.toLowerCase().replace(/\s+/g, '-');
        }
        
        if (isAllDays) {
            window.location.href = '/passing-record/all/' + marketVal;
        } else {
            const startVal = startDateInput.value;
            const endVal = endDateInput.value;
            
            if(startVal === endVal) {
                window.location.href = '/passing-record/' + startVal + '/' + marketVal;
            } else {
                window.location.href = '/passing-record/range/' + marketVal + '?start_date=' + startVal + '&end_date=' + endVal;
            }
        }
    });

    let currentPage = <?= $page ?>;
    const loadMoreBtn = document.getElementById('loadMoreBtn');

    if (loadMoreBtn) {
        loadMoreBtn.addEventListener('click', function() {
            currentPage++;
            const urlParams = new URLSearchParams(window.location.search);
            urlParams.set('page', currentPage);
            urlParams.set('ajax', '1');
            
            if (!document.getElementById('allDaysCheck').checked) {
                urlParams.set('start_date', document.getElementById('startDateInput').value);
                urlParams.set('end_date', document.getElementById('endDateInput').value);
            }
            
            const originalText = loadMoreBtn.innerText;
            loadMoreBtn.innerText = "Loading...";
            loadMoreBtn.disabled = true;

            fetch(window.location.pathname + '?' + urlParams.toString())
                .then(response => response.text())
                .then(html => {
                    if (html.trim() === '') {
                        loadMoreBtn.style.display = 'none';
                    } else {
                        document.getElementById('records-container').insertAdjacentHTML('beforeend', html);
                        loadMoreBtn.innerText = originalText;
                        loadMoreBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error loading more records:', error);
                    loadMoreBtn.innerText = "Error. Try Again";
                    loadMoreBtn.disabled = false;
                });
        });
    }
</script> 
<?php include dirname(__DIR__, 3) . "/content/themes/default/mod/_footer.php"; ?>
<h1> Matka </h1>
</body>
</html>
