<?php
// 📦 Database Connection (PDO)
// include "../includes/db.php"; 

// 🕒 Time Setup
date_default_timezone_set('Asia/Kolkata');

try {
    // Apne DB credentials yaha set karein
    $db = new PDO("mysql:host=localhost;dbname=4umatka", "4umatka", "Manish@#143");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("❌ DB Connection Failed: " . $e->getMessage());
}

$default_start = date('Y-m-d');
$default_end = date('Y-m-d');

// 📥 Fetch Games for Market Selection Dropdown
$games_stmt = $db->query("SELECT game_id, title FROM games ORDER BY title ASC");
$games_list = $games_stmt->fetchAll(PDO::FETCH_ASSOC);

$is_submitted = isset($_POST['generate']);
if ($is_submitted) {
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $market_id = $_POST['market_id'];
    $fail_percentage = isset($_POST['fail_percentage']) ? (int)$_POST['fail_percentage'] : 30;
} else {
    $start_date = $default_start;
    $end_date = $default_end;
    $market_id = 'all';
    $fail_percentage = 30; 
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Fake Pass Generator</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; background-color: #f4f4f9; }
        .form-container { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); max-width: 500px; margin-bottom: 20px; }
        .form-group { margin-bottom: 15px; }
        label { font-weight: bold; display: block; margin-bottom: 5px; }
        input[type="date"], input[type="number"], select { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        button { background-color: #28a745; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; width: 100%; font-weight: bold;}
        button:hover { background-color: #218838; }
        .result-box { margin-bottom: 15px; border: 1px solid #ddd; padding: 10px; border-left: 5px solid #007bff; background: white; }
        .fail-box { border-left: 5px solid #dc3545; }
        .pending-box { border-left: 5px solid #ffc107; background-color: #fffdf5; }
        .error-box { border-left: 5px solid #ff0000; background-color: #ffeeee; }
        .auto-update-text { color: #d63384; font-size: 13px; font-weight: bold; }
    </style>
</head>
<body>

<div class="form-container">
    <h2>📅 Generate Fake Passes</h2>
    <form method="POST" action="">
        <div class="form-group">
            <label for="market_id">Select Market:</label>
            <select id="market_id" name="market_id">
                <option value="all" <?= $market_id === 'all' ? 'selected' : '' ?>>All Markets</option>
                <?php foreach($games_list as $game): ?>
                    <option value="<?= htmlspecialchars($game['game_id']) ?>" <?= $market_id == $game['game_id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($game['title']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label for="start_date">Start Date (From):</label>
            <input type="date" id="start_date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" required>
        </div>
        <div class="form-group">
            <label for="end_date">End Date (To):</label>
            <input type="date" id="end_date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" required>
        </div>
        <div class="form-group">
            <label for="fail_percentage">Fail Percentage (%):</label>
            <input type="number" id="fail_percentage" name="fail_percentage" value="<?= htmlspecialchars($fail_percentage) ?>" min="0" max="100" required>
            <small style="color: #666;">Kitne percent results purposely fail karne hain.</small>
        </div>
        <button type="submit" name="generate">🚀 Generate</button>
    </form>
</div>

<?php
if (!$is_submitted) {
    echo "</body></html>";
    exit;
}

$market_text = $market_id === 'all' ? 'All Markets' : 'Selected Market';
echo "<h2>⚙️ Processing $market_text records from $start_date to $end_date...</h2>";

// 📥 Fetch Panel Groups from DB
$panel_groups = [];
try {
    $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_values = array_map('trim', explode(",", $row['panel_value']));
        $panel_groups[$digit] = $panel_values;
    }
} catch (PDOException $e) {
    die("❌ Error fetching predefined_panels: " . $e->getMessage());
}

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

function calculateDigitFromPanel($panel) {
    $panel = trim($panel);
    if (strlen($panel) != 3 || !is_numeric($panel)) return null;
    $sum = (int)$panel[0] + (int)$panel[1] + (int)$panel[2];
    return $sum % 10;
}

// 🎯 Query with Optional Market Filter
$query = "
    SELECT r.game_id, r.draw_date, r.open_digits, r.close_digits, g.title as market_name 
    FROM results r 
    JOIN games g ON r.game_id = g.game_id 
    WHERE r.draw_date BETWEEN ? AND ?
";
$params = [$start_date, $end_date];

if ($market_id !== 'all') {
    $query .= " AND r.game_id = ?";
    $params[] = $market_id;
}

$query .= " ORDER BY r.draw_date ASC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$real_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (count($real_results) === 0) {
    echo "<h3>❌ Koi results nahi mile in dates/market ke beech me.</h3>";
    echo "</body></html>";
    exit;
}

$pass_types = ['only_open', 'only_close', 'jodi', 'open_panel', 'close_panel', 'mixed'];
$success_count = 0;
$fail_count = 0;
$pending_count = 0;

foreach ($real_results as $row) {
    $market_name = $row['market_name'];
    $draw_date = $row['draw_date'];
    
    $open_result_panel = trim((string)$row['open_digits']);
    $close_result_panel = trim((string)$row['close_digits']);
    
    if ($open_result_panel === '' || $open_result_panel === 'null') $open_result_panel = '***';
    if ($close_result_panel === '' || $close_result_panel === 'null') $close_result_panel = '***';

    $is_fail = false;
    $is_pending = false;
    $auto_update_msg = "";

    $is_open_pending = ($open_result_panel === '***');
    $is_close_pending = ($close_result_panel === '***');

    // 🔴 Agar result Pura Pending hai (Dono ***)
    if ($is_open_pending && $is_close_pending) {
        $final_open_str = "*,*,*,*";
        $final_jodi_str = "**,**,**,**,**,**,**,**";
        $final_panel_str = "***,***,***,***";
        $random_pass_type = 'pending';
        $jodi_result = "**";
        $is_pending = true;
        $pending_count++;
    } else {
        // 🟢 Normal ya Half-Result Processing
        $open_digit = !$is_open_pending ? getSingleDigit($open_result_panel, $panel_groups) : null;
        $close_digit = !$is_close_pending ? getSingleDigit($close_result_panel, $panel_groups) : null;

        // 🔥 AUTO-UPDATE LOGIC FOR OPEN PANEL
        if ($open_digit === null && !$is_open_pending) {
            $open_digit = calculateDigitFromPanel($open_result_panel);
            if ($open_digit !== null) {
                $update_stmt = $db->prepare("UPDATE predefined_panels SET panel_value = CONCAT(panel_value, ',', ?) WHERE digit = ?");
                $update_stmt->execute([$open_result_panel, $open_digit]);
                $panel_groups[$open_digit][] = $open_result_panel;
                $auto_update_msg .= "⚙️ Open Panel [$open_result_panel] auto-added to Digit $open_digit. <br>";
            } else {
                echo "<div class='result-box error-box'><strong>⚠️ Error:</strong> Open Panel [$open_result_panel] invalid number format. Skipping $market_name.</div>";
                continue;
            }
        }

        // 🔥 AUTO-UPDATE LOGIC FOR CLOSE PANEL
        if ($close_digit === null && !$is_close_pending) {
            $close_digit = calculateDigitFromPanel($close_result_panel);
            if ($close_digit !== null) {
                $update_stmt = $db->prepare("UPDATE predefined_panels SET panel_value = CONCAT(panel_value, ',', ?) WHERE digit = ?");
                $update_stmt->execute([$close_result_panel, $close_digit]);
                $panel_groups[$close_digit][] = $close_result_panel;
                $auto_update_msg .= "⚙️ Close Panel [$close_result_panel] auto-added to Digit $close_digit. <br>";
            } else {
                echo "<div class='result-box error-box'><strong>⚠️ Error:</strong> Close Panel [$close_result_panel] invalid number format. Skipping $market_name.</div>";
                continue;
            }
        }

        $jodi_str_open = $open_digit !== null ? $open_digit : '*';
        $jodi_str_close = $close_digit !== null ? $close_digit : '*';
        $jodi_result = $jodi_str_open . $jodi_str_close;
        
        $is_fail = (rand(1, 100) <= $fail_percentage);
        
        if ($is_fail) {
            $random_pass_type = 'fail';
            $fail_count++;
        } else {
            // Logic Change: Agar half pending hai toh wahi pass generate karo jo available hai
            if ($is_close_pending) {
                $valid_types = ['only_open', 'open_panel'];
                $random_pass_type = $valid_types[array_rand($valid_types)];
            } elseif ($is_open_pending) {
                $valid_types = ['only_close', 'close_panel'];
                $random_pass_type = $valid_types[array_rand($valid_types)];
            } else {
                $random_pass_type = $pass_types[array_rand($pass_types)];
            }
        }

        $pool = range(0, 9);
        $exclude = [];
        if ($open_digit !== null) $exclude[] = $open_digit;
        if ($close_digit !== null) $exclude[] = $close_digit;
        
        $pool = array_diff($pool, $exclude); 
        shuffle($pool);
        $pool = array_values($pool); 

        // Fallback for missing digits during generation
        $fallback_open = $open_digit !== null ? $open_digit : $pool[4];
        $fallback_close = $close_digit !== null ? $close_digit : $pool[5];

        $guess_open = [];
        
        // =========================================================
        // 🔥 NAYA LOGIC: Yahan duplicates ko block karne ka logic 
        // sahi tarike se saare pass types ke liye set kiya gaya hai
        // =========================================================
        if ($random_pass_type === 'fail') {
            $guess_open = [$pool[0], $pool[1], $pool[2], $pool[3]];
        } else {
            // Pass type ke hisaab se pehle confirm numbers push kar lo
            if (in_array($random_pass_type, ['only_open', 'open_panel'])) {
                $guess_open[] = $fallback_open;
            } elseif (in_array($random_pass_type, ['only_close', 'close_panel'])) {
                $guess_open[] = $fallback_close;
            } elseif (in_array($random_pass_type, ['jodi', 'mixed'])) {
                if (!in_array($fallback_open, $guess_open)) $guess_open[] = $fallback_open;
                if (!in_array($fallback_close, $guess_open)) $guess_open[] = $fallback_close;
            }

            // Pool se randomly digits nikal ke array me daalo, 
            // array hamesha 4 hone pe loop rok do
            foreach ($pool as $num) {
                // Check karte hain ki number pehle se array me toh nahi hai
                if (!in_array($num, $guess_open)) {
                    $guess_open[] = $num;
                }
                // Jaise hi 4 numbers pure ho jayein, loop rok do
                if (count($guess_open) >= 4) break;
            }
            
            // Jumble kar do taaki original structure random lage
            shuffle($guess_open);
        }
        // =========================================================

        $guess_jodi = [
            "{$guess_open[0]}{$guess_open[1]}", "{$guess_open[1]}{$guess_open[0]}",
            "{$guess_open[1]}{$guess_open[2]}", "{$guess_open[2]}{$guess_open[1]}",
            "{$guess_open[2]}{$guess_open[3]}", "{$guess_open[3]}{$guess_open[2]}",
            "{$guess_open[3]}{$guess_open[0]}", "{$guess_open[0]}{$guess_open[3]}"
        ];

        $guess_panel = [];
        foreach ($guess_open as $index => $digit) {
            if ($random_pass_type === 'open_panel' && $index === 0) {
                $chosen = $open_result_panel;
            } elseif ($random_pass_type === 'close_panel' && $index === 0) {
                $chosen = $close_result_panel;
            } elseif ($random_pass_type === 'mixed') {
                if ($index === 0) $chosen = $open_result_panel;
                elseif ($index === 1) $chosen = $close_result_panel;
                else {
                    do { $chosen = $panel_groups[$digit][array_rand($panel_groups[$digit])]; } while (in_array($chosen, $guess_panel));
                }
            } else {
                do {
                    $chosen = $panel_groups[$digit][array_rand($panel_groups[$digit])];
                } while (in_array($chosen, $guess_panel));
            }
            $guess_panel[] = $chosen;
        }
        
        $final_open_str = implode(",", array_unique($guess_open)); 
        $final_jodi_str = implode(",", $guess_jodi);
        $final_panel_str = implode(",", $guess_panel);
    }

    $generated_at = date("Y-m-d H:i:s");

    // 🔄 Free Game me Insert ya Update
    $check_stmt = $db->prepare("SELECT id FROM free_game WHERE market = ? AND date = ?");
    $check_stmt->execute([$market_name, $draw_date]);
    
    if ($check_stmt->rowCount() > 0) {
        $update_stmt = $db->prepare("UPDATE free_game SET open = ?, jodi = ?, panel = ?, generated_at = ? WHERE market = ? AND date = ?");
        $update_stmt->execute([$final_open_str, $final_jodi_str, $final_panel_str, $generated_at, $market_name, $draw_date]);
        $action_msg = "Updated";
    } else {
        $insert_stmt = $db->prepare("INSERT INTO free_game (market, date, open, jodi, panel, generated_at) VALUES (?, ?, ?, ?, ?, ?)");
        $insert_stmt->execute([$market_name, $draw_date, $final_open_str, $final_jodi_str, $final_panel_str, $generated_at]);
        $action_msg = "Inserted";
    }

    if (!$is_pending) {
        $success_count++;
    }

    // Print Design Logic
    if ($is_pending) {
        $box_class = "result-box pending-box";
        $status_icon = "⏳";
        $status_color = "#b08d00"; 
    } elseif ($is_fail) {
        $box_class = "result-box fail-box";
        $status_icon = "❌";
        $status_color = "red";
    } else {
        $box_class = "result-box";
        $status_icon = "✅";
        $status_color = "green";
    }

    echo "<div class='$box_class'>";
    echo "<strong>$status_icon $market_name ($draw_date)</strong> - <span style='color:$status_color;'>$action_msg</span><br>";
    if ($auto_update_msg != "") {
        echo "<div class='auto-update-text'>$auto_update_msg</div>";
    }
    echo "<strong>Type:</strong> <span style='text-transform:uppercase; color:$status_color;'>$random_pass_type</span> <br>";
    echo "<strong>Real Result:</strong> $open_result_panel-($jodi_result)-$close_result_panel <br>";
    echo "<strong>Generated Open:</strong> $final_open_str <br>";
    echo "<strong>Generated Jodi:</strong> $final_jodi_str <br>";
    echo "<strong>Generated Panel:</strong> $final_panel_str <br>";
    echo "</div>";
}

$passed = $success_count - $fail_count;
echo "<h3>🎉 Total results processed! (Pass: $passed, Fail: $fail_count, Full Pending: $pending_count)</h3>";
?>
</body>
</html>