<?php
// ==========================================
// === START OF WEEKLY_LIST.PHP CONTENT ===
// ==========================================

// ERROR REPORTING
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Week calculation (Monday to Sunday)
$monday_timestamp = strtotime("last monday");
$monday_timestamp = date('w', $monday_timestamp) == 1 ? $monday_timestamp : strtotime('this monday');
$this_week_start = date("d-m-Y", $monday_timestamp);
$this_week_end = date("d-m-Y", strtotime("+6 days", $monday_timestamp));
$db_monday = date("Y-m-d", $monday_timestamp);

include "db2.php"; 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$games_list = "Kalyan, Milan, Kalyan Night, Rajdhani, Time, Main Bazar";

// ⚠️ YAHAN APNE SABHI GAMES KI ID DAALIYE (Jinse result match karwana hai)
$all_market_ids = [1, 2, 3, 4, 5, 6, 7, 8]; 

// ==========================================
// 🚀 1. AUTO-GENERATOR (IMPROVED)
// ==========================================
function generatePattiForAnks($target_ank) {
    while (true) {
        $d = [rand(0,9), rand(0,9), rand(0,9)];
        sort($d);
        $str = "";
        $zeroCount = 0;
        foreach($d as $num) {
            if($num == 0) $zeroCount++;
            else $str .= $num;
        }
        for($z=0; $z<$zeroCount; $z++) $str .= "0";

        $sum = 0;
        for($i=0; $i<3; $i++) $sum += (int)$str[$i];
        if ($sum % 10 == $target_ank) return $str;
    }
}

// 1. Sirf Anks check aur generate karne ke liye
$chk_ank = $db1->prepare("SELECT id FROM dpboss_weekly_data WHERE guess_date=? AND guess_type='DP_ANK' LIMIT 1");
$chk_ank->bind_param("s", $db_monday);
$chk_ank->execute();
if ($chk_ank->get_result()->num_rows == 0) {
    $ins = $db1->prepare("INSERT INTO dpboss_weekly_data (guess_type, guess_date, guess1, guess2, guess3, guess4) VALUES (?, ?, ?, ?, ?, ?)");
    for ($i = 0; $i < 7; $i++) {
        $gen_date = date("Y-m-d", strtotime("+$i days", $monday_timestamp));
        $type = 'DP_ANK';
        $a1 = rand(0,9); $a2 = rand(0,9); $a3 = rand(0,9); $a4 = rand(0,9);
        $ins->bind_param("ssssss", $type, $gen_date, $a1, $a2, $a3, $a4); 
        $ins->execute();
    }
}
$chk_ank->close();

// 2. Patti aur Jodi check aur generate karne ke liye
$chk_patti = $db1->prepare("SELECT id FROM dpboss_weekly_data WHERE guess_date=? AND guess_type='DP_PATTI_1' LIMIT 1");
$chk_patti->bind_param("s", $db_monday);
$chk_patti->execute();
if ($chk_patti->get_result()->num_rows == 0) {
    $ins = $db1->prepare("INSERT INTO dpboss_weekly_data (guess_type, guess_date, guess1, guess2, guess3, guess4) VALUES (?, ?, ?, ?, ?, ?)");
    
    // Generate Weekly Pattis
    $nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    foreach ($nums as $n) {
        $type = 'DP_PATTI_' . $n;
        $p1 = generatePattiForAnks($n); $p2 = generatePattiForAnks($n); $p3 = generatePattiForAnks($n); $p4 = generatePattiForAnks($n);
        $ins->bind_param("ssssss", $type, $db_monday, $p1, $p2, $p3, $p4); 
        $ins->execute();
    }

    // Generate Weekly Jodis
    for ($r = 1; $r <= 6; $r++) {
        $type = 'DP_JODI_' . $r;
        $j1 = rand(0,9).rand(0,9); $j2 = rand(0,9).rand(0,9); $j3 = rand(0,9).rand(0,9); $j4 = rand(0,9).rand(0,9);
        $ins->bind_param("ssssss", $type, $db_monday, $j1, $j2, $j3, $j4); 
        $ins->execute();
    }
}
$chk_patti->close();

// ==========================================
// 📊 2. FETCH ACTUAL RESULTS FROM *ALL MARKETS* FOR PASS/FAIL
// ==========================================
$weekly_actual_pattis = [];
$weekly_actual_jodis = [];
$daily_market_anks = []; // Date wise aur All Markets ke Anks

$end_date_db = date("Y-m-d", strtotime("+6 days", $monday_timestamp));

// Sabhi selected games ka result ek sath mangwa rahe hain
$in_clause = implode(',', array_map('intval', $all_market_ids));
$res_query = $db1->query("SELECT draw_date, open_digits, close_digits FROM results WHERE game_id IN ($in_clause) AND draw_date BETWEEN '$db_monday' AND '$end_date_db'");

while($r = $res_query->fetch_assoc()) {
    $d = $r['draw_date'];
    $op = $r['open_digits'];
    $cp = $r['close_digits'];
    
    $oa = ($op != '') ? substr(($op[0] + $op[1] + $op[2]), -1) : '';
    $ca = ($cp != '') ? substr(($cp[0] + $cp[1] + $cp[2]), -1) : '';
    $jodi = ($oa != '' && $ca != '') ? $oa . $ca : '';

    // Har din ke liye sabhi games ke Anks store kar rahe hain
    if(!isset($daily_market_anks[$d])) { $daily_market_anks[$d] = []; }
    if($oa != '') $daily_market_anks[$d][] = $oa;
    if($ca != '') $daily_market_anks[$d][] = $ca;
    
    if($op != '') $weekly_actual_pattis[] = $op;
    if($cp != '') $weekly_actual_pattis[] = $cp;
    if($jodi != '') $weekly_actual_jodis[] = $jodi;
}

$is_week_over = (time() > strtotime("+6 days 23:59:59", $monday_timestamp)); 

// ==========================================
// 🎨 3. RENDER THE 3 BOXES
// ==========================================

// --- BOX 1: PATTI CHART ---
echo '<div class="card-box"><div class="title-head">DpBoss Net Weekly Patti Or Penal Chart From '.$this_week_start.' To '.$this_week_end.' For '.$games_list.'</div><div class="dp-list">';
$nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
foreach ($nums as $n) {
    $type = 'DP_PATTI_' . $n;
    $stmt = $db1->prepare("SELECT guess1, guess2, guess3, guess4 FROM dpboss_weekly_data WHERE guess_date=? AND guess_type=?");
    $stmt->bind_param("ss", $db_monday, $type);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row) {
        $pattis = [$row['guess1'], $row['guess2'], $row['guess3'], $row['guess4']];
        $display_pattis = [];
        foreach($pattis as $p) {
            $sym = "🔵"; 
            if (in_array($p, $weekly_actual_pattis)) $sym = "🟢"; // Kisi bhi game me paas hua toh Green
            elseif ($is_week_over) $sym = "🔴"; 
            $display_pattis[] = "$p$sym";
        }
        echo '<p>'.$n.'=>'.implode('-', $display_pattis).'</p>';
    }
}
echo '</div></div>';

// --- BOX 2: LINE OPEN OR CLOSE ---
echo '<div class="card-box"><div class="title-head">DpBoss Net Weekly Line Open Or Close From '.$this_week_start.' To '.$this_week_end.' For '.$games_list.'</div><div class="dp-list">';
$days_names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
for ($i = 0; $i < 7; $i++) {
    $current_date = date("Y-m-d", strtotime("+$i days", $monday_timestamp));
    
    $stmt = $db1->prepare("SELECT guess1, guess2, guess3, guess4 FROM dpboss_weekly_data WHERE guess_date=? AND guess_type='DP_ANK'");
    $stmt->bind_param("s", $current_date);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row) {
        $anks = [$row['guess1'], $row['guess2'], $row['guess3'], $row['guess4']];
        $actual_day_anks = $daily_market_anks[$current_date] ?? [];
        
        $display_anks = [];
        foreach($anks as $a) {
            $sym = "🔵"; 
            if (count($actual_day_anks) > 0) { // Agar aaj kisi bhi game ka result aaya hai
                if (in_array($a, $actual_day_anks)) {
                    $sym = "🟢"; // Agar guess kiya hua ank kisi bhi game me pass hua
                } else {
                    $sym = "🔴"; // Agar result aa gaya par guess pass nahi hua
                }
            }
            $display_anks[] = "$a$sym";
        }
        echo '<p>'.$days_names[$i].'. '.implode('-', $display_anks).'</p>';
    }
}
echo '</div></div>'; 
 
// --- BOX 3: JODI CHART ---
echo '<div class="card-box"><div class="title-head">DpBoss Net Weekly Jodi Chart From '.$this_week_start.' To '.$this_week_end.' For '.$games_list.'</div><div class="dp-list">';
for ($r = 1; $r <= 6; $r++) {
    $type = 'DP_JODI_' . $r;
    $stmt = $db1->prepare("SELECT guess1, guess2, guess3, guess4 FROM dpboss_weekly_data WHERE guess_date=? AND guess_type=?");
    $stmt->bind_param("ss", $db_monday, $type);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row) {
        $jodis = [$row['guess1'], $row['guess2'], $row['guess3'], $row['guess4']];
        $display_jodis = [];
        foreach($jodis as $j) {
            $sym = "🔵"; 
            if (in_array($j, $weekly_actual_jodis)) $sym = "🟢"; 
            elseif ($is_week_over) $sym = "🔴"; 
            $display_jodis[] = "$j$sym";
        }
        echo '<p>'.implode(' &nbsp;&nbsp;&nbsp; ', $display_jodis).'</p>';
    }
}
echo '</div></div>';


// ==========================================
// === START OF WEEKLY_TABLE.PHP CONTENT ===
// ==========================================

// ==========================================
// 🕒 PERFECT DATE & WEEK CALCULATION (IST)
// ==========================================
date_default_timezone_set('Asia/Kolkata');

$today_timestamp = strtotime('today');
$day_of_week = date('N', $today_timestamp); // 1 = Monday, 7 = Sunday

if ($day_of_week == 1) {
    // Agar aaj Monday hai, toh aaj hi start date banega
    $monday_timestamp = $today_timestamp;
} else {
    // Agar koi aur din hai, toh pichla Monday dhundo
    $monday_timestamp = strtotime('last monday', $today_timestamp);
}

$this_week_start = date("d/m/Y", $monday_timestamp);
$this_week_end = date("d/m/Y", strtotime("+6 days", $monday_timestamp));
$db_monday = date("Y-m-d", $monday_timestamp);

include "db2.php"; 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// ==========================================
// 🚀 1. NEW AUTO-GENERATOR SCRIPT
// ==========================================

function generatePattiForAnk($target_ank) {
    while (true) {
        $d = [rand(0,9), rand(0,9), rand(0,9)];
        sort($d);
        
        $str = "";
        $zeroCount = 0;
        foreach($d as $num) {
            if($num == 0) $zeroCount++;
            else $str .= $num;
        }
        for($z=0; $z<$zeroCount; $z++) $str .= "0";

        $sum = 0;
        for($i=0; $i<3; $i++) $sum += (int)$str[$i];
        
        if ($sum % 10 == $target_ank) return $str;
    }
}

$games_to_generate = [1 => 6, 2 => 5];

foreach ($games_to_generate as $g_id => $days_count) {
    for ($i = 0; $i < $days_count; $i++) {
        $gen_date = date("Y-m-d", strtotime("+$i days", $monday_timestamp));
        
        $chk = $db1->prepare("SELECT id FROM weekly_chart_guesses WHERE game_id=? AND guess_date=? LIMIT 1");
        $chk->bind_param("is", $g_id, $gen_date);
        $chk->execute();
        
        if ($chk->get_result()->num_rows == 0) {
            $ins = $db1->prepare("INSERT INTO weekly_chart_guesses (game_id, guess_type, guess_date, guess1, guess2, guess3, guess4) VALUES (?, ?, ?, ?, ?, ?, ?)");
            
            $o1 = rand(0,9); $o2 = rand(0,9); $o3 = rand(0,9); $o4 = rand(0,9);
            $j1 = $o1 . rand(0,9); $j2 = $o2 . rand(0,9); $j3 = $o3 . rand(0,9); $j4 = $o4 . rand(0,9);
            $p1 = generatePattiForAnk($o1); $p2 = generatePattiForAnk($o2); $p3 = generatePattiForAnk($o3); $p4 = generatePattiForAnk($o4);

            $type = 'OPEN';
            $ins->bind_param("issssss", $g_id, $type, $gen_date, $o1, $o2, $o3, $o4); $ins->execute();

            $type = 'JODI';
            $ins->bind_param("issssss", $g_id, $type, $gen_date, $j1, $j2, $j3, $j4); $ins->execute();

            $type = 'PATTI';
            $ins->bind_param("issssss", $g_id, $type, $gen_date, $p1, $p2, $p3, $p4); $ins->execute();
        }
        $chk->close();
    }
}
// ========================================== 
// 📊 2. RENDER CHARTS FUNCTION (NOW USING FULLY RESPONSIVE DIVS)
// ==========================================
function renderWeeklyChart($db1, $game_id, $game_name, $days_array, $monday_timestamp, $this_week_start, $this_week_end) {
    echo '<div class="card-box" style="padding: 0;">';
    echo '<div class="title-head" style="margin: 0; border-radius: 0;">'.$game_name.'</div>';

    foreach ($days_array as $index => $day_name) {
        $current_date = date("Y-m-d", strtotime("+$index days", $monday_timestamp));
        
        try {
            $stmt_res = $db1->prepare("SELECT open_digits, close_digits FROM results WHERE game_id = ? AND draw_date = ? LIMIT 1");
            $stmt_res->bind_param("is", $game_id, $current_date);
            $stmt_res->execute();
            $actual_result = $stmt_res->get_result()->fetch_assoc();
            $stmt_res->close();
            
            $open_patti = $actual_result['open_digits'] ?? '';
            $close_patti = $actual_result['close_digits'] ?? '';
            
            $is_open_out = ($open_patti != '');
            $is_close_out = ($close_patti != '');
            
            $actual_open_ank = $is_open_out ? substr(($open_patti[0] + $open_patti[1] + $open_patti[2]), -1) : '';
            $actual_close_ank = $is_close_out ? substr(($close_patti[0] + $close_patti[1] + $close_patti[2]), -1) : '';
            $actual_jodi = ($is_open_out && $is_close_out) ? $actual_open_ank . $actual_close_ank : '';

            $guess_data = ['OPEN' => [], 'JODI' => [], 'PATTI' => []];
            $stmt_guess = $db1->prepare("SELECT guess_type, guess1, guess2, guess3, guess4 FROM weekly_chart_guesses WHERE game_id = ? AND guess_date = ?");
            $stmt_guess->bind_param("is", $game_id, $current_date);
            $stmt_guess->execute();
            $result_guess = $stmt_guess->get_result();
            
            while($row = $result_guess->fetch_assoc()) {
                $type = $row['guess_type'];
                $guesses = [$row['guess1'], $row['guess2'], $row['guess3'], $row['guess4']];
                
                foreach($guesses as $k => $g) {
                    if((string)$g === '') continue; 
                    
                    $symbol = "🔵"; 
                    if ($type == 'OPEN') {
                        if (($is_open_out && $g == $actual_open_ank) || ($is_close_out && $g == $actual_close_ank)) $symbol = "🟢"; 
                        elseif ($is_open_out && $is_close_out) $symbol = "🔴"; 
                    } 
                    elseif ($type == 'JODI') {
                        if ($is_open_out && $is_close_out) $symbol = ($g == $actual_jodi) ? "🟢" : "🔴";
                    } 
                    elseif ($type == 'PATTI') {
                        if (($is_open_out && $g == $open_patti) || ($is_close_out && $g == $close_patti)) $symbol = "🟢"; 
                        elseif ($is_open_out && $is_close_out) $symbol = "🔴"; 
                    }
                    $guess_data[$type][$k] = "$g $symbol"; 
                }
            }
            $stmt_guess->close();

            $o = $guess_data['OPEN'] ?? ['','','',''];
            $j = $guess_data['JODI'] ?? ['','','',''];
            $p = $guess_data['PATTI'] ?? ['','','',''];

        } catch (Exception $e) {
            echo "<div class='w-chart-error'>Error: " . $e->getMessage() . "</div>";
            continue;
        }

        // Last row ke liye border-bottom hatane ka logic (Set 2 design ke mutabik)
        $row_style = ($index == count($days_array) - 1) ? ' style="border-bottom: none;"' : '';
        echo '<div class="table-row"'.$row_style.'>';
        
        // Column 1: Day Name
        echo '<div class="table-day">'.$day_name.'</div>';
        
        // Group 1
        echo '<div class="table-cell">';
        echo '<div class="cell-ank">'.($o[0]??'').'</div>';
        echo '<div class="cell-patti">'.($p[0]??'').'</div>';
        echo '<div class="cell-jodi">'.($j[0]??'').'</div>';
        echo '</div>';
        
        // Group 2
        echo '<div class="table-cell">';
        echo '<div class="cell-ank">'.($o[1]??'').'</div>';
        echo '<div class="cell-patti">'.($p[1]??'').'</div>';
        echo '<div class="cell-jodi">'.($j[1]??'').'</div>';
        echo '</div>';
        
        // Group 3
        echo '<div class="table-cell">';
        echo '<div class="cell-ank">'.($o[2]??'').'</div>';
        echo '<div class="cell-patti">'.($p[2]??'').'</div>';
        echo '<div class="cell-jodi">'.($j[2]??'').'</div>';
        echo '</div>';
         
        // Group 4
        echo '<div class="table-cell">';
        echo '<div class="cell-ank">'.($o[3]??'').'</div>';
        echo '<div class="cell-patti">'.($p[3]??'').'</div>';
        echo '<div class="cell-jodi">'.($j[3]??'').'</div>';
        echo '</div>';
        
        echo '</div>'; // End Row
    }
    echo '</div>'; // End Card-box
}

// ==========================================
// 🚀 3. CALL FUNCTIONS FOR KALYAN & MAIN BAZAR
// ==========================================

renderWeeklyChart($db1, 1, 'कल्याण', ['सोम', 'मंगल', 'बुध', 'गुरु', 'शुक्र', 'शनि'], $monday_timestamp, $this_week_start, $this_week_end);
renderWeeklyChart($db1, 2, 'KALYAN NIGHT / MAIN BAZAR', ['सोम', 'मंगल', 'बुध', 'गुरु', 'शुक्र'], $monday_timestamp, $this_week_start, $this_week_end);

?>