<?php
session_start();

// ডাটাবেজ ফাইল লোড করা
$db_file = 'database.json';
// ডাটাবেজ স্ট্রাকচার আপডেট: এখন আমরা ফ্রিকোয়েন্সি সেভ করব
$db = file_exists($db_file) ? json_decode(file_get_contents($db_file), true) : ['learned_patterns' => []];

// আপনার দেওয়া নিখুঁত ডাটা ম্যাপ
$data_map = [
    0 => ['t' => 'Small', 'c' => 'Red/Violet'],
    1 => ['t' => 'Small', 'c' => 'Green'],
    2 => ['t' => 'Small', 'c' => 'Red'],
    3 => ['t' => 'Small', 'c' => 'Green'],
    4 => ['t' => 'Small', 'c' => 'Red'],
    5 => ['t' => 'Big',   'c' => 'Green/Violet'],
    6 => ['t' => 'Big',   'c' => 'Red'],
    7 => ['t' => 'Big',   'c' => 'Green'],
    8 => ['t' => 'Big',   'c' => 'Red'],
    9 => ['t' => 'Big',   'c' => 'Green'],
];

// আপনার দেওয়া ফিক্সড রুলস ডাটাবেজ
$fixed_rules = [
    "num_rules" => [
        "8,8" => ["num" => 2, "type" => "Small", "color" => "Red"],
        "2,2" => ["num" => 7, "type" => "Big", "color" => "Green"],
        "0,5" => ["num" => 8, "type" => "Big", "color" => "Red"],
        "5,0" => ["num" => 1, "type" => "Small", "color" => "Green"],
        "1,3,1" => ["num" => 3, "type" => "Small", "color" => "Green"],
        "6,8,6" => ["num" => 8, "type" => "Big", "color" => "Red"],
        "9,7,9" => ["num" => 7, "type" => "Big", "color" => "Green"],
        "4,2,4" => ["num" => 2, "type" => "Small", "color" => "Red"],
        "1,2,3" => ["num" => 4, "type" => "Small", "color" => "Red"],
        "9,8,7" => ["num" => 6, "type" => "Big", "color" => "Red"],
        "0,1,0" => ["num" => 5, "type" => "Big", "color" => "Green"],
        "5,6,5" => ["num" => 0, "type" => "Small", "color" => "Red"],
        "1,1,2,2" => ["num" => 3, "type" => "Small", "color" => "Green"],
        "8,8,7,7" => ["num" => 6, "type" => "Big", "color" => "Red"],
        "1,3,5,7" => ["num" => 9, "type" => "Big", "color" => "Green"],
        "2,4,6,8" => ["num" => 0, "type" => "Small", "color" => "Red"],
        "0,2,4,6" => ["num" => 8, "type" => "Big", "color" => "Red"],
        "9,7,5,3" => ["num" => 1, "type" => "Small", "color" => "Green"],
        "1,1,1" => ["num" => 1, "type" => "Small", "color" => "Green"],
        "8,8,8" => ["num" => 8, "type" => "Big", "color" => "Red"],
        "4,3,2,1" => ["num" => 0, "type" => "Small", "color" => "Red"],
        "6,7,8,9" => ["num" => 5, "type" => "Big", "color" => "Green"],
        "0,0,5,5" => ["num" => 2, "type" => "Small", "color" => "Red"],
        "3,3,6,6" => ["num" => 9, "type" => "Big", "color" => "Green"],
        "1,0,1,0" => ["num" => 2, "type" => "Small", "color" => "Red"],
        "9,5,9,5" => ["num" => 8, "type" => "Big", "color" => "Red"],
        "7,3,7,3" => ["num" => 1, "type" => "Small", "color" => "Green"],
        "1,2,1,2,1" => ["num" => 2, "type" => "Small", "color" => "Red"],
        "8,9,8,9,8" => ["num" => 9, "type" => "Big", "color" => "Green"],
        "5,5,0,0,5" => ["num" => 5, "type" => "Big", "color" => "Green"],
        "4,4,1,1,4" => ["num" => 4, "type" => "Small", "color" => "Red"]
    ],
    "streak_rules" => [
        "3_Big" => ["res_type" => "Big", "res_color" => "Red"],
        "3_Small" => ["res_type" => "Small", "res_color" => "Green"],
        "4_Big" => ["res_type" => "Big", "res_color" => "Red"],
        "4_Small" => ["res_type" => "Small", "res_color" => "Green"],
        "5_Big" => ["res_type" => "Big", "res_color" => "Red"],
        "5_Small" => ["res_type" => "Small", "res_color" => "Green"],
        "2_Big" => ["res_type" => "Small", "res_color" => "Green"],
        "2_Small" => ["res_type" => "Big", "res_color" => "Red"]
    ]
];

// সেশন ভেরিয়েবল
if (!isset($_SESSION['history'])) $_SESSION['history'] = [];
if (!isset($_SESSION['analytics_log'])) $_SESSION['analytics_log'] = [];
if (!isset($_SESSION['current_prediction'])) $_SESSION['current_prediction'] = null;

// নতুন নাম্বার যোগ এবং অটো-লার্নিং লজিক
if (isset($_POST['add_number']) && $_POST['new_num'] !== "") {
    $actual_num = (int)$_POST['new_num'];
    $hist = $_SESSION['history'];

    // ১. অটো-লার্নিং লজিক (নিজে নিজে শেখা)
    // আমরা গত ১০টি প্যাটার্ন পর্যন্ত শিখব (১-ডিজিট থেকে ১০-ডিজিট পর্যন্ত)
    for ($len = 1; $len <= 10; $len++) {
        if (count($hist) >= $len) {
            $pattern_segment = array_slice($hist, 0, $len);
            $pattern_key = implode(',', array_reverse($pattern_segment));
            
            // যদি এই প্যাটার্ন আগে না থাকে তবে তৈরি করো
            if (!isset($db['learned_patterns'][$pattern_key])) {
                $db['learned_patterns'][$pattern_key] = array_fill(0, 10, 0); // ০-৯ পর্যন্ত কাউন্টার
            }
            // এই প্যাটার্নের পর যে সংখ্যাটি আসলো তার কাউন্ট ১ বাড়িয়ে দাও
            $db['learned_patterns'][$pattern_key][$actual_num]++;
        }
    }
    // ডাটাবেজ সেভ করা
    file_put_contents($db_file, json_encode($db));

    // এনালাইটিক্স লগ আপডেট
    if ($_SESSION['current_prediction']) {
        $pred = $_SESSION['current_prediction'];
        $actual_data = $data_map[$actual_num];
        $log_entry = [
            'actual' => $actual_num,
            'predicted' => $pred['num'],
            'num_match' => ($actual_num == $pred['num']),
            'type_match' => ($actual_data['t'] == $pred['type']),
            'color_match' => (strpos($actual_data['c'], $pred['color']) !== false),
            'mode' => $pred['mode'],
            'rule_key' => $pred['rule_key']
        ];
        array_unshift($_SESSION['analytics_log'], $log_entry);
        $_SESSION['analytics_log'] = array_slice($_SESSION['analytics_log'], 0, 50);
    }

    // হিস্ট্রিতে নতুন নাম্বার যোগ করা
    array_unshift($_SESSION['history'], $actual_num);
    $_SESSION['history'] = array_slice($_SESSION['history'], 0, 11);
}

// সর্বশেষ এন্ট্রি মুছে ফেলা (Undo Logic) - সংশোধিত
if (isset($_POST['delete_last']) && !empty($_SESSION['history'])) {
    $last_actual = array_shift($_SESSION['history']); // হিস্ট্রি থেকে শেষ নম্বর রিমুভ
    
    // যদি এনালাইটিক্স লগ থাকে তবেই রিমুভ করবে
    if (!empty($_SESSION['analytics_log'])) {
        array_shift($_SESSION['analytics_log']);
    }

    // ডাটাবেজ থেকে লার্নিং ডাটা কমানো
    $hist_before = $_SESSION['history'];
    for ($len = 1; $len <= 10; $len++) {
        if (count($hist_before) >= $len) {
            $pattern_segment = array_slice($hist_before, 0, $len);
            $pattern_key = implode(',', array_reverse($pattern_segment));
            
            if (isset($db['learned_patterns'][$pattern_key])) {
                // ওই নির্দিষ্ট নম্বরের কাউন্ট ১ কমিয়ে দেওয়া
                if ($db['learned_patterns'][$pattern_key][$last_actual] > 0) {
                    $db['learned_patterns'][$pattern_key][$last_actual]--;
                }
            }
        }
    }
    file_put_contents($db_file, json_encode($db));
    header("Location: ".$_SERVER['PHP_SELF']);
    exit();
}

// সিস্টেম রিসেট
if (isset($_POST['reset'])) {
    session_destroy();
    header("Location: ".$_SERVER['PHP_SELF']);
    exit();
}

// --- প্রেডিকশন ইঞ্জিন (নিখুঁত গ্লোবাল লার্নিং সিস্টেম) ---
$prediction = null;
if (count($_SESSION['history']) >= 5) {
    $hist = $_SESSION['history'];
    $best_match_key = "N/A";
    $final_pred_num = null;
    $found_mode = "";

    // ১০ থেকে ১ পর্যন্ত প্যাটার্ন চেক করা (সবচেয়ে বড় সিকোয়েন্স আগে চেক হবে)
    for ($len = 10; $len >= 1; $len--) {
        if (count($hist) >= $len) {
            $current_segment = array_slice($hist, 0, $len);
            $check_key = implode(',', array_reverse($current_segment));

            // ১. ফিক্সড রুল চেক
            if (isset($fixed_rules['num_rules'][$check_key])) {
                $final_pred_num = $fixed_rules['num_rules'][$check_key]['num'];
                $best_match_key = $check_key;
                $found_mode = "ELITE FIXED RULE";
                break;
            }

            // ২. গ্লোবাল লার্নিং ডাটাবেজ চেক
            if (isset($db['learned_patterns'][$check_key])) {
                $counts = $db['learned_patterns'][$check_key];
                if (max($counts) > 0) { // যদি ওই প্যাটার্নে কোনো ডাটা থাকে
                    arsort($counts); 
                    $final_pred_num = key($counts);
                    $best_match_key = $check_key;
                    $found_mode = "SMART LEARNED (DATA)";
                    break;
                }
            }
        }
    }

    // ৩. স্ট্রিক এনালাইসিস (যদি কোনো প্যাটার্ন ম্যাচ না করে)
    if ($final_pred_num === null) {
        $last_types = [];
        foreach(array_slice($hist, 0, 5) as $h) { $last_types[] = ($h >= 5) ? "Big" : "Small"; }
        $streak_count = 1;
        $first_type = $last_types[0];
        for($i=1; $i<count($last_types); $i++) {
            if($last_types[$i] == $first_type) $streak_count++; else break;
        }
        $streak_key = $streak_count . "_" . $first_type;
        if (isset($fixed_rules['streak_rules'][$streak_key])) {
            $s_rule = $fixed_rules['streak_rules'][$streak_key];
            $final_pred_num = ($s_rule['res_type'] == "Big") ? rand(7,9) : rand(1,3);
            $best_match_key = "STREAK: $streak_key";
            $found_mode = "STREAK ANALYSIS";
        }
    }

    // ৪. যদি কোনো উপায় না থাকে (Fallback AI)
    if ($final_pred_num === null) {
        $last_num = $hist[0];
        $final_pred_num = ($last_num >= 5) ? rand(0,4) : rand(5,9);
        $best_match_key = "TREND SYNC";
        $found_mode = "NEURAL SYNC (AI)";
    }

    $pred_data = $data_map[$final_pred_num];
    $clean_color = (strpos($pred_data['c'], '/') !== false) ? explode('/', $pred_data['c'])[0] : $pred_data['c'];

    $prediction = [
        'num' => $final_pred_num,
        'type' => $pred_data['t'],
        'color' => $clean_color,
        'mode' => $found_mode,
        'rule_key' => $best_match_key
    ];
    $_SESSION['current_prediction'] = $prediction;
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI SELF-LEARNING PRO</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700&display=swap" rel="stylesheet">
    <style>
        body { background: #080c14; color: #fff; font-family: 'Segoe UI', sans-serif; padding-bottom: 50px; }
        .container { max-width: 450px; margin-top: 20px; }
        .pred-card { background: linear-gradient(145deg, #1a2236, #0d121f); border: 2px solid #00f2fe; border-radius: 25px; padding: 25px; text-align: center; margin-bottom: 20px; box-shadow: 0 0 25px rgba(0, 242, 254, 0.2); }
        .neon-text { font-family: 'Orbitron', sans-serif; color: #00f2fe; text-shadow: 0 0 10px #00f2fe; }
        .big-num { font-size: 90px; line-height: 1; font-weight: 900; }
        .stat-table { background: #111827; border-radius: 15px; overflow: hidden; }
        .win { color: #00ff88; } .miss { color: #ff3131; }
        .key-badge { font-size: 8px; background: rgba(255,255,255,0.1); padding: 2px 5px; border-radius: 4px; color: #94a3b8; }
    </style>
</head>
<body>

<div class="container">
    <?php if (count($_SESSION['history']) < 5): ?>
        <div class="alert alert-warning text-center border-warning bg-dark text-warning" style="border-radius: 15px;">
            <b>DATA COLLECTING:</b> Please add <?php echo (5 - count($_SESSION['history'])); ?> more results to start prediction.
        </div>
    <?php endif; ?>

    <?php if ($prediction): ?>
    <div class="pred-card">
        <div class="small text-info opacity-75 mb-2"><?php echo $prediction['mode']; ?></div>
        <div class="neon-text big-num"><?php echo $prediction['num']; ?></div>
        <div class="h1 fw-bold <?php echo ($prediction['type']=='Big')?'text-warning':'text-info'; ?>">
            <?php echo strtoupper($prediction['type']); ?>
        </div>
        <div class="badge <?php echo ($prediction['color']=='Red')?'bg-danger':'bg-success'; ?> px-5 py-2 mt-2" style="font-size: 14px;">
            <?php echo strtoupper($prediction['color']); ?>
        </div>
        <div class="mt-3"><span class="key-badge">ACTIVE KEY: [<?php echo $prediction['rule_key']; ?>]</span></div>
    </div>
    <?php endif; ?>

    <?php if (!empty($_SESSION['history'])): ?>
    <div class="mb-2 px-2">
        <small class="text-secondary">Current Sequence: </small>
        <?php foreach(array_reverse($_SESSION['history']) as $h): ?>
            <span class="badge bg-secondary m-1"><?php echo $h; ?></span>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
    
    <div class="card bg-dark p-3 mb-4 border-info">
        <form method="POST" class="d-flex gap-2">
            <input type="number" name="new_num" class="form-control form-control-lg bg-black text-white border-secondary" placeholder="0-9" required min="0" max="9" autofocus>
            <button type="submit" name="add_number" class="btn btn-info px-4 fw-bold">ADD</button>
            <?php if (!empty($_SESSION['history'])): ?>
                <button type="submit" name="delete_last" class="btn btn-danger px-3 fw-bold" onclick="return confirm('Delete last entry?');">UNDO</button>
            <?php endif; ?>
        </form>
    </div>

    <div class="stat-table shadow-lg">
<div class="p-3 bg-info text-dark fw-bold d-flex justify-content-between align-items-center">
    <span>SYSTEM ANALYTICS</span>
    <form method="POST" onsubmit="return confirm('Delete last result?');">
        <button name="delete_last" class="btn btn-sm btn-danger fw-bold py-0" style="font-size: 10px;">UNDO LAST</button>
    </form>
</div>
        <table class="table table-dark table-hover mb-0 text-center">
            <thead>
                <tr class="text-secondary small"><th>ACTUAL</th><th>TARGET</th><th>B/S</th><th>COLOR</th></tr>
            </thead>
            <tbody>
                <?php foreach ($_SESSION['analytics_log'] as $log): ?>
                <tr class="align-middle">
                    <td><b class="fs-4"><?php echo $log['actual']; ?></b></td>
                    <td><b class="text-info fs-5"><?php echo $log['predicted']; ?></b></td>
                    <td><?php echo $log['type_match'] ? '<span class="win">✔</span>' : '<span class="miss">✘</span>'; ?></td>
                    <td><?php echo $log['color_match'] ? '<span class="win">✔</span>' : '<span class="miss">✘</span>'; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <form method="POST" class="mt-4">
        <button name="reset" class="btn btn-link text-danger w-100 text-decoration-none opacity-50 small">REBOOT & CLEAR MEMORY</button>
    </form>
</div>

</body>
</html>