
<?php
include dirname(__DIR__, 3) . "/includes/db.php";
$alias = $_GET['alias'] ?? '';
$page_clean = str_replace('-', ' ', htmlspecialchars($alias, ENT_QUOTES, 'UTF-8'));

// 1. Fetch market details
$stmt = $db->prepare("SELECT game_id, title, panel_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;
}

$game_id      = $game['game_id']       ?? '';
$name         = $game['title']         ?? '';
$panel_result = $game['panel_result']  ?? '';
$game_day_str = $game['game_day']      ?? '';  
$game_day_val = (int)$game_day_str;

// 🔥 NAYA SYSTEM: Fetch SEO data from 'charts_pages' table
$chart_slug = strtolower(str_replace(' ', '-', $page_clean)) . '-panel'; 
$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
$meta_title = $seo_data['title'] ?? "$name Panel Chart Record - Full Result";
$meta_description = $seo_data['description'] ?? "Get the latest $name Panel 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
$result1 = $result2 = $text = '';
$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' => $game_id]);
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $result1 = $row['result1'] ?? '';
    $result2 = $row['result2'] ?? '';
    $text    = $row['remark']  ?? '';
}

// If no result today, look back
if ($result1 === '' && $result2 === '') {
    $today_num = date('N');
    $game_days = ($game_day_str === '0' || $game_day_str === '8')
                 ? range(1,7)
                 : (strpos($game_day_str, ',') !== false
                     ? array_map('intval', explode(',', $game_day_str))
                     : range(1, (int)$game_day_str)
                   );
    rsort($game_days);

    $past_day = null;
    foreach ($game_days as $d) {
        if ($d <= $today_num) {
            $past_day = $d;
            break;
        }
    }
    if ($past_day === null) {
        $past_day = max($game_days);
    }
    $day_diff = $today_num - $past_day;

    $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() - INTERVAL :d DAY LIMIT 1"
    );
    $stmt->bindValue('id', $game_id, PDO::PARAM_INT);
    $stmt->bindValue('d',  $day_diff,  PDO::PARAM_INT);
    $stmt->execute();

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $result1 = $row['result1'] ?? '';
        $result2 = $row['result2'] ?? '';
        $text    = $row['remark']  ?? '';
    }
}

// Prepare final result
if ($result1 === '' && $result2 === '') {
    $final_result = "Loading..";
    $color = "gray";
} else {
    $count1 = is_numeric($result1) ? substr(array_sum(str_split($result1)), -1) : '*';
    $count2 = is_numeric($result2) ? substr(array_sum(str_split($result2)), -1) : '*';
    $final_result = sprintf("%s-%s%s-%s", $result1, $count1, $count2, $result2);
    $color = "black";
}

// Header include
include "panel_header.php";
?>


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

<div class="card-box" style="overflow-x: auto; padding: 10px;">
    <table border="1">
        <tr class="tr">
            <th>Date</th>
            <?php
            $dayNames = [1=>"Mon",2=>"Tue",3=>"Wed",4=>"Thu",5=>"Fri",6=>"Sat",7=>"Sun"];
            $allowedDays = ($game_day_str === '0' || $game_day_str === '8')
                         ? range(1,7)
                         : (strpos($game_day_str, ',') !== false
                             ? array_map('intval', explode(',', $game_day_str))
                             : range(1,(int)$game_day_str)
                           );
            foreach ($dayNames as $dn => $dl) {
                if (in_array($dn, $allowedDays)) {
                    echo "<th colspan='3'>{$dl}</th>";
                }
            }
            ?>
        </tr>
        <tbody>
            <?= $panel_result ?>

            <?php
            // ==========================================
            // HEAVY LOGIC CACHING SYSTEM START
            // ==========================================
            $cache_file = __DIR__ . "/cache/panel_chart_{$game_id}.html";
            $cache_time = 300; 

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

                $stmt = $db->prepare(
                    "SELECT open_digits AS result1, close_digits AS result2,
                            DATE_FORMAT(draw_date,'%w')   AS day_num,
                            DATE_FORMAT(draw_date,'%d/%m/%Y') AS date1,
                            draw_date                  AS date_actual
                     FROM results
                     WHERE game_id = :id
                     ORDER BY draw_date"
                );
                $stmt->execute(['id' => $game_id]);
                $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

                $groupedWeeks = [];
                foreach ($results as $row) {
                    $dn = (int)$row['day_num'];
                    $dn = ($dn === 0) ? 7 : $dn;
                    if (!in_array($dn, $allowedDays)) continue;

                    $weekStart = date('Y-m-d', strtotime($row['date_actual'] . ' -'.($dn - min($allowedDays)).' days'));
                    $groupedWeeks[$weekStart][$dn] = $row;
                }

                foreach ($groupedWeeks as $ws => $days) {
                    $wsd = date('d/m/Y', strtotime($ws));
                    $wed = date('d/m/Y', strtotime("{$ws} +".($game_day_val-1)." days"));
                    echo "<tr><td class='chart_date'>{$wsd}<br>To<br>{$wed}</td>";

                    foreach ($dayNames as $dn => $dl) {
                        if (!in_array($dn, $allowedDays)) continue;

                        $r = $days[$dn] ?? null;
                        if ($r && $r['result1'] && $r['result2']) {
                            $r1 = $r['result1'];
                            $r2 = $r['result2'];
                            
                            $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;

                            if (is_numeric($c1) && is_numeric($c2)) {
                                $c3 = $c1+5;
                                $c4 = $c2+5;
                                $col = ($c1==$c2 || $c2==$c3 || $c4==$c1) ? 'red' : 'black';
                            } else {
                                $col = 'black'; 
                            }

                            $p1_0 = $r1[0] ?? '*'; $p1_1 = $r1[1] ?? '*'; $p1_2 = $r1[2] ?? '*';
                            $p2_0 = $r2[0] ?? '*'; $p2_1 = $r2[1] ?? '*'; $p2_2 = $r2[2] ?? '*';

                            echo "<td class='td_{$col}'>{$p1_0}<br>{$p1_1}<br>{$p1_2}</td>";
                            echo "<td class='td_{$col} border_left_right'>{$final}</td>";
                            echo "<td class='td_{$col}'>{$p2_0}<br>{$p2_1}<br>{$p2_2}</td>";
                        } else {
                            echo "<td class='td_blank' title='Result not declared'>*<br>*<br>*</td>";
                            echo "<td class='td_blank border_left_right' title='Final not available'>**</td>";
                            echo "<td class='td_blank' title='Result not declared'>*<br>*<br>*</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
            // ==========================================
            ?>
        </tbody>
    </table>
</div>

<div class="card-box lucky-box">
  <h4 class="color-primary"><?php echo htmlspecialchars($name); ?></h4>
  <p class="txt-lg"><span class="loading-emoji">🔄</span> 
  <span style='color:<?php echo $color; ?>;'><?php echo htmlspecialchars($final_result); ?></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>
<style>
.td_red    { color: red;   font-weight: bold; }
.td_black  { color: black; font-weight: bold; }
.td_blank  { color: gray;  font-weight: bold; text-align: center; }
.border_left_right { border-left:1px solid rgba(3, 169, 244, 0.3); border-right:1px solid rgba(3, 169, 244, 0.3); }
.chart_date { text-align:center; font-weight: bold; color: var(--c-primary); }
.today-result h3 { font-size: 1.2em; }
.today-result p  { font-size: 1em; }
</style>
<?php include dirname(__DIR__, 3) . "/content/themes/default/mod/_footer.php"; ?>

