
 <?php
include "../includes/db.php";
date_default_timezone_set("Asia/Kolkata");

$alias = $_GET['alias'] ?? '';
$page_clean = str_replace('-', ' ', htmlspecialchars($alias, ENT_QUOTES, 'UTF-8'));

// 1. Fetch market details from 'games' table
$stmt = $db->prepare("SELECT game_id, title, jodi_result, game_day FROM games WHERE alias = :alias LIMIT 1");
$stmt->execute(['alias' => $page_clean]);
$game = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$game) {
    echo "404 - Market Not Found";
    exit;
}

$gameId = $game['game_id'];
$title = $game['title'];
$jodi_result = $game['jodi_result'];
$gameDayLimit = (int)$game['game_day'];

// 🔥 NAYA SYSTEM: Fetch SEO data from 'charts_pages' table
$chart_slug = strtolower(str_replace(' ', '-', $page_clean)) . '-jodi'; 
$stmt_seo = $db->prepare("SELECT title, description, content, content2, schema_data FROM charts_pages WHERE slug = :slug LIMIT 1");
$stmt_seo->execute(['slug' => $chart_slug]);
$seo_data = $stmt_seo->fetch(PDO::FETCH_ASSOC);

// Assign values (Agar DB me nahi hai, toh default chalega)
$meta_title = $seo_data['title'] ?? "$title Jodi Chart Record - Full Result";
$meta_description = $seo_data['description'] ?? "Get the latest $title Jodi Chart Record. Fast and accurate results.";
$top_content = $seo_data['content'] ?? ""; 
$bottom_content = $seo_data['content2'] ?? ""; 
$schema_data = $seo_data['schema_data'] ?? ""; 

// 2. Fetch today's result
$stmt = $db->prepare("SELECT open_digits AS result1, close_digits AS result2, note_open AS remark 
                      FROM results 
                      WHERE game_id = :id AND draw_date = CURDATE() LIMIT 1");
$stmt->execute(['id' => $gameId]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);

$result1 = $result['result1'] ?? '';
$result2 = $result['result2'] ?? '';
$text    = $result['remark'] ?? '';

// 3. Fallback to last result
if (empty($result1) && empty($result2)) {
    $stmt = $db->prepare("SELECT open_digits AS result1, close_digits AS result2 
                          FROM results 
                          WHERE game_id = :id 
                          ORDER BY draw_date DESC LIMIT 1");
    $stmt->execute(['id' => $gameId]);
    $prevResult = $stmt->fetch(PDO::FETCH_ASSOC);

    $result1 = $prevResult['result1'] ?? '';
    $result2 = $prevResult['result2'] ?? '';
}

// Fixed '0' issue for Top Display
$c1 = is_numeric($result1) ? substr(array_sum(str_split($result1)), -1) : '*';
$c2 = is_numeric($result2) ? substr(array_sum(str_split($result2)), -1) : '*';

$resultDisplay = (!empty($result1) || !empty($result2)) ? "$result1-$c1$c2-$result2" : "Loading...";

include "jodi_header.php"; 
?>

<?php if (!empty($top_content)): ?>
<div class="card-box txt-md" style="margin-bottom: 15px; text-align: left;">
    <?= $top_content ?>
</div>
<?php endif; ?>

<h2 class="title-head"><?= ucwords(strtolower(htmlspecialchars($title))) ?> Jodi Chart</h2>

<div class="card-box" style="overflow-x: auto; padding: 10px;">
<table border="1">
    <tr>
        <?php
        $dayMap = [
            1 => ["name" => "Mon", "color" => "red"],
            2 => ["name" => "Tue", "color" => "blue"],
            3 => ["name" => "Wed", "color" => "green"],
            4 => ["name" => "Thu", "color" => "brown"],
            5 => ["name" => "Fri", "color" => "purple"],
            6 => ["name" => "Sat", "color" => "black"],
            7 => ["name" => "Sun", "color" => "green"],
        ];

        for ($i = 1; $i <= $gameDayLimit; $i++) {
            $day = $dayMap[$i];
            echo "<td align='center'><font color='{$day['color']}'>{$day['name']}</font></td>";
        }
        ?>
    </tr>

    <?php
    echo $jodi_result;

    // ==========================================
    // HEAVY LOGIC CACHING SYSTEM START
    // ==========================================
    $cache_file = __DIR__ . "/cache/jodi_chart_main_{$gameId}.html";
    $cache_time = 300; 

    if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_time) {
        echo file_get_contents($cache_file);
    } else {
        ob_start(); 

        $stmt2 = $db->prepare("
            SELECT open_digits AS result1, close_digits AS result2, draw_date 
            FROM results 
            WHERE game_id = :id 
            ORDER BY draw_date
        ");
        $stmt2->execute(['id' => $gameId]);

        $groupedWeeks = [];
        while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
            $date = $row['draw_date'];
            $r1 = $row['result1'] ?? '';
            $r2 = $row['result2'] ?? '';
            $dayNum = (int)date('N', strtotime($date));
            if ($dayNum > $gameDayLimit) continue;

            $weekKey = date('o-W', strtotime($date));
            
            $c1 = is_numeric($r1) ? substr(array_sum(str_split($r1)), -1) : '*';
            $c2 = is_numeric($r2) ? substr(array_sum(str_split($r2)), -1) : '*';
            $final = "$c1$c2";
            
            $color = ($c1 !== '*' && $c2 !== '*' && ($c1 == $c2 || abs($c1 - $c2) == 5)) ? "red" : "black";

            $groupedWeeks[$weekKey][$dayNum] = "<td style='color:$color;'>$final</td>";
        }

        if (!empty($groupedWeeks)) {
            foreach ($groupedWeeks as $week) {
                echo "<tr>";
                for ($i = 1; $i <= $gameDayLimit; $i++) {
                    echo $week[$i] ?? "<td>**</td>";
                }
                echo "</tr>";
            }
        } else {
            echo "<tr>";
            for ($i = 1; $i <= $gameDayLimit; $i++) {
                echo "<td>**</td>";
            }
            echo "</tr>";
        }

        $html_output = ob_get_clean();
        
        if (!is_dir(__DIR__ . "/cache")) {
            mkdir(__DIR__ . "/cache", 0777, true);
        }
        file_put_contents($cache_file, $html_output);
        echo $html_output;
    }
    // ==========================================
    // CACHING SYSTEM END
    // ==========================================
    ?>
</table>
</div>
 
<div class="card-box lucky-box">
  <h4 class="color-primary"><?= htmlspecialchars($title) ?></h4> 
  <p class="txt-lg"><span class="loading-emoji">🔄</span> <?= $resultDisplay ?>
    <span style='color:black;'><?= $text ? "- " . htmlspecialchars($text) : "" ?></span>
  </p>
  <button class="btn-gradient" onclick="window.location.reload()"><span class="loading-emoji">🔄</span> Refresh</button>
</div>

<?php if (!empty($bottom_content)): ?>
<div class="card-box txt-md" style="margin-top: 15px; text-align: left;">
    <?= $bottom_content ?>
</div>
<?php endif; ?>

<button id="scrollToTopBtn" class="btn-gradient">Scroll to Top</button>
<script>
  document.getElementById('scrollToTopBtn').addEventListener('click', () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  });
</script>

<div class="card-box txt-sm">
  <b>SattaMatkaLive.Org</b> provide all about satta matka chart & record Related
</div>

<?php include dirname(__DIR__, 3) . "/content/themes/default/mod/_footer.php"; ?>
