<?php
/**
 * Win Racing - 雙核心大數據四軌合流 API (get_analysis_trend_ajax.php)
 * 終極完全體：【遵照指令：由3位改4位強推名家組合大數據累加版】
 * 1. 【名家基準還原】機率、總勝出率、動態門檻勝率 100% 還原為常規 3軌制平均運算，絕不交叉干擾。
 * 2. 【四核名家組合勝率累加】從10月1日起遍歷追蹤，計算哪四位名家同時強力推薦(6分)時頭馬勝出率最高，並動態累加注入最右側加權總分。
 * 【只加不減】完全獨立通道，4場賽果 meta 管線完好無損，100% 完整代碼平鋪。
 */
ob_start(); 
error_reporting(0);
ini_set('display_errors', 0);
date_default_timezone_set('Asia/Hong_Kong');

require_once 'config/config.php';
if (!isset($conn)) { $conn = $db; }
$conn->set_charset("utf8mb4");

$race_id = isset($_GET['race_id']) ? intval($_GET['race_id']) : 0;
if ($race_id <= 0) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array());
    exit;
}

// 1. 自動定位當前 race_id 的真實賽事日期
$d_stmt = $conn->prepare("SELECT racing_date FROM racing_date_2025_2026 WHERE id = ?");
$d_stmt->bind_param("i", $race_id);
$d_stmt->execute();
$d_res = $d_stmt->get_result();

if (!$d_row = $d_res->fetch_assoc()) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array());
    $d_stmt->close();
    exit;
}
$target_date = $d_row['racing_date'];
$d_stmt->close();

// 2. 預載全局實際歷史賽果 Map
$results_map = array();
$results_map_7 = array();
$res_query = $conn->query("SELECT race_date, race_number, win_horse, place_horse, third_horse FROM racing_results");
if ($res_query) {
    while ($res = $res_query->fetch_assoc()) {
        $rd = $res['race_date'];
        $rn = intval($res['race_number']);
        $results_map[$rd][$rn] = intval($res['win_horse']);
        $results_map_7[$rd][$rn] = array(intval($res['win_horse']), intval($res['place_horse']), intval($res['third_horse']));
    }
}

// =========================================================================
// 🚀 [7 分表歷史特徵密碼庫重構]
// =========================================================================
$globalPatternStats = array();
$tempRaces_7 = array();
$scoreQuery_7 = $conn->query("SELECT race_date, race_no, horse_number, score FROM race_7_scores ORDER BY race_date ASC, race_no ASC, id ASC");
if ($scoreQuery_7) {
    while ($row = $scoreQuery_7->fetch_assoc()) {
        $tempRaces_7[$row['race_date']][intval($row['race_no'])][] = array(
            'horse' => intval($row['horse_number']), 
            'score' => intval($row['score'])
        );
    }
}
foreach ($tempRaces_7 as $date => $races) {
    foreach ($races as $r_no => $horses) {
        if ($date === $target_date) continue; 
        if (!isset($results_map_7[$date][$r_no]) || count($horses) < 3) continue;

        $patternKey = "{$horses[0]['score']},{$horses[1]['score']},{$horses[2]['score']}";
        if (!isset($globalPatternStats[$patternKey])) {
            $globalPatternStats[$patternKey] = array('total' => 0, 'first_in_q' => 0, 'second_in_q' => 0);
        }
        $globalPatternStats[$patternKey]['total']++;
        $q_horses = $results_map_7[$date][$r_no];
        if (in_array($horses[0]['horse'], $q_horses)) $globalPatternStats[$patternKey]['first_in_q']++;
        if (in_array($horses[1]['horse'], $q_horses)) $globalPatternStats[$patternKey]['second_in_q']++;
    }
}

// 提取今日當天 7 分表的分數排位
$today7ScoresMap = array();
$todayQuery_7 = $conn->query("SELECT race_no, horse_number, score FROM race_7_scores WHERE race_date = '$target_date' ORDER BY race_no ASC, id ASC");
if ($todayQuery_7) {
    while ($row = $todayQuery_7->fetch_assoc()) {
        $today7ScoresMap[intval($row['race_no'])][] = array(
            'horse' => intval($row['horse_number']),
            'score' => intval($row['score'])
        );
    }
}

// =========================================================================
// 🚀 [核心名家矩陣縱向大數據開火管線 - 100% 完整平鋪]
// =========================================================================
$tables = array('expert_ai', 'expert_ball', 'expert_racingpost', 'expert_siu_siu', 'expert_horse_king', 'expert_happy_bird');
$season_expert_matrix = array();

// 💡 建立 4名家綁定為 1個組合 的累積戰績庫，統計範圍：精確限制從2025年10月1日起累加起來
$expert_quad_win_stats = array(); 

foreach ($tables as $table) {
    $check_table = $conn->query("SHOW TABLES LIKE '$table'");
    if($check_table->num_rows == 0) continue;

    $fields = ($table === 'expert_happy_bird') ? "race_date, race_num, pick_1, pick_2, pick_3, pick_4, pick_5" : "race_date, race_num, pick_1, pick_2, pick_3, pick_4";
    $h_sql = "SELECT $fields FROM `$table` WHERE race_date >= '2025-10-01' AND race_date <= ? ORDER BY race_date ASC, race_num ASC";
    $h_stmt = $conn->prepare($h_sql);
    if ($h_stmt) {
        $h_stmt->bind_param("s", $target_date);
        $h_stmt->execute();
        $h_res = $h_stmt->get_result();
        while ($h_row = $h_res->fetch_assoc()) {
            $hd = $h_row['race_date'];
            $rn = intval($h_row['race_num']);
            
            $all_picks = array('pick_1', 'pick_2', 'pick_3', 'pick_4');
            if ($table === 'expert_happy_bird') { $all_picks[] = 'pick_5'; }
            
            foreach ($all_picks as $p_fld) {
                if (isset($h_row[$p_fld]) && $h_row[$p_fld] > 0) {
                    $h_num = intval($h_row[$p_fld]);
                    if (!isset($season_expert_matrix[$hd][$rn][$h_num])) {
                        $season_expert_matrix[$hd][$rn][$h_num] = array(
                            'horse_num' => $h_num, 'total_score' => 0, 'hit_count' => 0,
                            'p1_from' => array(), 'p2_from' => array(), 'supporters' => array(), 'expert_count' => 0
                        );
                    }
                    $season_expert_matrix[$hd][$rn][$h_num]['expert_count']++;
                    
                    if ($p_fld === 'pick_1') {
                        $season_expert_matrix[$hd][$rn][$h_num]['total_score'] += 6; // 強力推薦得6分
                        $season_expert_matrix[$hd][$rn][$h_num]['hit_count'] += 1;
                        $season_expert_matrix[$hd][$rn][$h_num]['p1_from'][] = $table; 
                    } elseif ($p_fld === 'pick_2') {
                        $season_expert_matrix[$hd][$rn][$h_num]['total_score'] += 1; // 次選得1分
                        $season_expert_matrix[$hd][$rn][$h_num]['hit_count'] += 1;
                        $season_expert_matrix[$hd][$rn][$h_num]['p2_from'][] = $table;
                    } else {
                        $season_expert_matrix[$hd][$rn][$h_num]['hit_count'] += 1;
                        $season_expert_matrix[$hd][$rn][$h_num]['supporters'][] = $table;
                    }
                }
            }
        }
        $h_stmt->close();
    }
}

// =========================================================================
// 🚀 [大數據深度演算：由3位改4位名家組合，計算 4個名家強推組合 的累積頭馬勝率]
// =========================================================================
foreach ($season_expert_matrix as $h_date => $h_races) {
    if ($h_date === $target_date) continue; // 刨除今日
    
    foreach ($h_races as $hr_no => $h_horses) {
        if (!isset($results_map[$h_date][$hr_no])) continue;
        $actual_win_horse = $results_map[$h_date][$hr_no]; 

        foreach ($h_horses as $horse_id => $h_data) {
            $p1_experts = $h_data['p1_from']; // 收集這匹馬在歷史上同時被哪些名家選為強力推薦(6分)
            $p1_count = count($p1_experts);
            
            // 💡 核心指令改動：當強力推薦的名家數量達到或超過 4 位時，執行「四核心組合」戰績累積
            if ($p1_count >= 4) {
                sort($p1_experts); // 排序
                // 4人為1個組合進行排列組合迴圈
                for ($i = 0; $i < $p1_count; $i++) {
                    for ($j = $i + 1; $j < $p1_count; $j++) {
                        for ($k = $j + 1; $k < $p1_count; $k++) {
                            for ($l = $k + 1; $l < $p1_count; $l++) {
                                $ex1 = $p1_experts[$i]; $ex2 = $p1_experts[$j];
                                $ex3 = $p1_experts[$k]; $ex4 = $p1_experts[$l];
                                
                                $quad_key = "{$ex1}+{$ex2}+{$ex3}+{$ex4}";
                                
                                if (!isset($expert_quad_win_stats[$quad_key])) {
                                    $expert_quad_win_stats[$quad_key] = array('total' => 0, 'wins' => 0);
                                }
                                $expert_quad_win_stats[$quad_key]['total']++;
                                if (intval($h_data['horse_num']) === $actual_win_horse) {
                                    $expert_quad_win_stats[$quad_key]['wins']++;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

// 整理 10月1日起累積下來各四核組合的真實頭馬勝出率
$quad_win_rates_map = array();
foreach ($expert_quad_win_stats as $quad => $s) {
    if ($s['total'] > 0) {
        $quad_win_rates_map[$quad] = $s['wins'] / $s['total'];
    }
}

// 建立排名序列
$season_ranked_flow = array();
foreach ($season_expert_matrix as $h_date => $h_races) {
    foreach ($h_races as $hr_no => $h_horses) {
        uasort($h_horses, function($a, $b) {
            if ($a['total_score'] == $b['total_score']) { return ($a['horse_num'] < $b['horse_num']) ? -1 : 1; }
            return ($b['total_score'] <=> $a['total_score']);
        });
        $season_ranked_flow[$h_date][$hr_no] = array_values($h_horses);
    }
}

$today_races_nodes = $season_ranked_flow[$target_date] ?? array();

// 預算重心場次
$zhongxin_candidates = array(); 
foreach ($today_races_nodes as $r_num => $horses) {
    if (empty($horses)) continue;
    $top_score_1 = $horses[0];
    $top_score_2 = isset($horses[1]) ? $horses[1] : null;
    $score_gap = $top_score_2 ? ($top_score_1['total_score'] - $top_score_2['total_score']) : $top_score_1['total_score'];

    $is_qualified = ($score_gap >= 4 && $top_score_1['total_score'] >= 11 && $top_score_1['hit_count'] >= 2);
    if ($is_qualified) {
        $strength = ($top_score_1['total_score'] * 10) + ($score_gap * 5) + $top_score_1['hit_count'];
        $zhongxin_candidates[$r_num] = $strength;
    }
}
arsort($zhongxin_candidates);
$top_3_races = array_slice(array_keys($zhongxin_candidates), 0, 3);

$final_dashboard = array();

// 10級階梯配置
function getScoreBandConfig($score) {
    $s = floatval($score);
    if ($s >= 19 && $s <= 20) return array('min' => 19, 'max' => 20, 'boost' => 1.10);
    if ($s >= 21 && $s <= 22) return array('min' => 21, 'max' => 22, 'boost' => 1.20);
    if ($s >= 23 && $s <= 24) return array('min' => 23, 'max' => 24, 'boost' => 1.30);
    if ($s >= 25 && $s <= 26) return array('min' => 25, 'max' => 26, 'boost' => 1.45);
    if ($s >= 27 && $s <= 28) return array('min' => 27, 'max' => 28, 'boost' => 1.60);
    if ($s >= 29 && $s <= 30) return array('min' => 29, 'max' => 30, 'boost' => 1.80);
    if ($s >= 31 && $s <= 32) return array('min' => 31, 'max' => 32, 'boost' => 2.00);
    if ($s >= 33 && $s <= 34) return array('min' => 33, 'max' => 34, 'boost' => 2.25);
    if ($s >= 35 && $s <= 36) return array('min' => 35, 'max' => 36, 'boost' => 2.50);
    if ($s > 36)              return array('min' => 36.1, 'max' => 999, 'boost' => 3.00);
    return array('min' => 0, 'max' => 18.9, 'boost' => 1.00);
}

function isScoreInBand($score, $band) {
    $s = floatval($score);
    if ($band['min'] == 36.1) { return $s > 36; }
    return ($s >= $band['min'] && $s <= $band['max']);
}

// 今日賽日 1 至 11 場，縱向大數據滾動追蹤
foreach ($today_races_nodes as $r_num => $sorted_horses) {
    if (empty($sorted_horses)) continue;

    $top_score_1 = $sorted_horses[0];
    $top_score_2 = isset($sorted_horses[1]) ? $sorted_horses[1] : null;
    $score_gap = $top_score_2 ? ($top_score_1['total_score'] - $top_score_2['total_score']) : $top_score_1['total_score'];

    $type = "CIXUAN"; $dan_text = "-"; $jiao_text = "-"; $exclude_dans = array();

    if (in_array($r_num, $top_3_races)) {
        if ($top_score_1['total_score'] >= 24 && count($top_score_1['p1_from']) >= 4 && $score_gap > 11) { $type = "ZHONGXIN_3"; $dan_text = "【超級鐵膽】 " . $top_score_1['horse_num'] . " 號馬"; }
        else if ($top_score_1['total_score'] >= 13 && $score_gap >= 5 && $top_score_1['hit_count'] >= 3) { $type = "ZHONGXIN_2"; $dan_text = "【聚焦精選膽】 " . $top_score_1['horse_num'] . " 號馬"; }
        else { $type = "ZHONGXIN_1"; $dan_text = "【正路穩健膽】 " . $top_score_1['horse_num'] . " 號馬"; }
        $exclude_dans[] = $top_score_1['horse_num'];
    } else if ($top_score_1['total_score'] < 10) {
        $type = "LENGBAO"; $dan_text = "【隱藏冷膽】 " . $top_score_1['horse_num'] . " 號馬";
        $exclude_dans[] = $top_score_1['horse_num'];
    } else {
        $type = "CIXUAN"; 
        $h2_id = isset($sorted_horses[1]) ? $sorted_horses[1]['horse_num'] : '?';
        $dan_text = "【雙膽互托】 " . $top_score_1['horse_num'] . " 號 及 " . $h2_id . " 號馬";
        $exclude_dans[] = $top_score_1['horse_num'];
        if (isset($sorted_horses[1])) { $exclude_dans[] = $sorted_horses[1]['horse_num']; }
    }

    $probability_output = array(); $total_win_ratio_output = array(); $over22_win_ratio_output = array(); 
    $weighted_score_output = array(); $raw_prob_data = array(); $raw_win_data = array(); $raw_threshold_data = array();
    $history_success_q_output = array();

    // 🔒 100% 還原名家原始大滾動計數器
    $c1_total = 0; $c1_win = 0; $c2_total = 0; $c2_win1 = 0; $c2_win2 = 0; $c3_total = 0; $c3_win1 = 0; $c3_win2 = 0; 
    $c4_total = 0; $c4_win = 0; $c5_total = 0; $c5_win1 = 0; $c5_win2 = 0; $c7_total = 0; $c7_win1 = 0; $c7_win2 = 0; 
    $r1_total = 0; $r1_win = 0; $r2_total = 0; $r2_win1 = 0; $r2_win2 = 0; $r3_total = 0; $r3_win1 = 0; $r3_win2 = 0; 
    $r4_total = 0; $r4_win = 0; $r5_total = 0; $r5_win1 = 0; $r5_win2 = 0; $r7_total = 0; $r7_win1 = 0; $r7_win2 = 0; 
    $v1_total = 0; $v1_win = 0; $v2_total = 0; $v2_win1 = 0; $v2_win2 = 0; $v3_total = 0; $v3_win1 = 0; $v3_win2 = 0; 
    $v4_total = 0; $v4_win = 0; $v5_total = 0; $v5_win1 = 0; $v5_win2 = 0; $v7_total = 0; $v7_win1 = 0; $v7_win2 = 0;

    $is_probability_pattern = false;
    if (($ec1 == 6 && $ec2 != 6) || ($ec1 == 6 && $ec2 == 6) || ($ec1 == 5 && $ec2 == 5) || ($ec1 > 6) || ($ec2 > 6) || ($ec1 == 5 && $ec2 == 4) || ($ec1 == 4 && $ec2 == 5)) {
        $is_probability_pattern = true;
    }

    if ($is_probability_pattern) {
        foreach ($season_ranked_flow as $h_date => $h_races) {
            foreach ($h_races as $hr_no => $h_horses) {
                if ($h_date === $target_date && $hr_no == $r_num) { if (!isset($results_map[$h_date][$hr_no]) || $results_map[$h_date][$hr_no] <= 0) { continue 2; } }
                if ($h_date === $target_date && $hr_no > $r_num) { continue 2; }
                if (count($h_horses) < 2) continue;

                $act_win_uid = intval($results_map[$h_date][$hr_no] ?? 0);
                $hec1 = intval($h_horses[0]['expert_count']); $hec2 = intval($h_horses[1]['expert_count']);
                $h_score1 = floatval($h_horses[0]['total_score']); $h_score2 = floatval($h_horses[1]['total_score']);
                $hist_h1 = intval($h_horses[0]['horse_num']); $hist_h2 = intval($h_horses[1]['horse_num']);

                if ($ec1 == 6 && $ec2 != 6) {
                    if ($hec1 == 6 && $hec2 != 6) {
                        $c1_total++; if ($hist_h1 == $act_win_uid) $c1_win++;
                        if ($h_score1 > 20) { $r1_total++; if ($hist_h1 == $act_win_uid) $r1_win++; }
                        if (isScoreInBand($h_score1, $band_config1)) { $v1_total++; if ($hist_h1 == $act_win_uid) $v1_win++; }
                    }
                }
                elseif ($ec1 == 6 && $ec2 == 6) {
                    if ($hec1 == 6 && $hec2 == 6) {
                        $c2_total++; if ($hist_h1 == $act_win_uid) $c2_win1++; if ($hist_h2 == $act_win_uid) $c2_win2++;
                        if ($h_score1 > 20 || $h_score2 > 20) { $r2_total++; }
                        if ($h_score1 > 20 && $hist_h1 == $act_win_uid) $r2_win1++;
                        if ($h_score2 > 20 && $hist_h2 == $act_win_uid) $r2_win2++;
                        if (isScoreInBand($h_score1, $band_config1) || isScoreInBand($h_score2, $band_config2)) { $v2_total++; }
                        if (isScoreInBand($h_score1, $band_config1) && $hist_h1 == $act_win_uid) $v2_win1++;
                        if (isScoreInBand($h_score2, $band_config2) && $hist_h2 == $act_win_uid) $v2_win2++;
                    }
                }
                elseif ($ec1 == 5 && $ec2 == 5) {
                    if ($hec1 == 5 && $hec2 == 5) {
                        $c3_total++; if ($hist_h1 == $act_win_uid) $c3_win1++; if ($hist_h2 == $act_win_uid) $c3_win2++;
                        if ($h_score1 > 20 || $h_score2 > 20) { $r3_total++; }
                        if ($h_score1 > 20 && $hist_h1 == $act_win_uid) $r3_win1++;
                        if ($h_score2 > 20 && $hist_h2 == $act_win_uid) $r3_win2++;
                        if (isScoreInBand($h_score1, $band_config1) || isScoreInBand($h_score2, $band_config2)) { $v3_total++; }
                        if (isScoreInBand($h_score1, $band_config1) && $hist_h1 == $act_win_uid) $v3_win1++;
                        if (isScoreInBand($h_score2, $band_config2) && $hist_h2 == $act_win_uid) $v3_win2++;
                    }
                }
                elseif ($ec1 == 5 && $ec2 == 4) {
                    if ($hec1 == 5 && $hec2 == 4) {
                        $c5_total++; if ($hist_h1 == $act_win_uid) $c5_win1++; if ($hist_h2 == $act_win_uid) $c5_win2++;
                        if ($h_score1 > 20 || $h_score2 > 20) { $r5_total++; }
                        if ($h_score1 > 20 && $hist_h1 == $act_win_uid) $r5_win1++;
                        if ($h_score2 > 20 && $hist_h2 == $act_win_uid) $r5_win2++;
                        if (isScoreInBand($h_score1, $band_config1) || isScoreInBand($h_score2, $band_config2)) { $v5_total++; }
                        if (isScoreInBand($h_score1, $band_config1) && $hist_h1 == $act_win_uid) $v5_win1++;
                        if (isScoreInBand($h_score2, $band_config2) && $hist_h2 == $act_win_uid) $v5_win2++;
                    }
                }
                elseif ($ec1 == 4 && $ec2 == 5) {
                    if ($hec1 == 4 && $hec2 == 5) {
                        $c7_total++; if ($hist_h1 == $act_win_uid) $c7_win1++; if ($hist_h2 == $act_win_uid) $c7_win2++;
                        if ($h_score1 > 20 || $h_score2 > 20) { $r7_total++; }
                        if ($h_score1 > 20 && $hist_h1 == $act_win_uid) $r7_win1++;
                        if ($h_score2 > 20 && $hist_h2 == $act_win_uid) $r7_win2++;
                        if (isScoreInBand($h_score1, $band_config1) || isScoreInBand($h_score2, $band_config2)) { $v7_total++; }
                        if (isScoreInBand($h_score1, $band_config1) && $hist_h1 == $act_win_uid) $v7_win1++;
                        if (isScoreInBand($h_score2, $band_config2) && $hist_h2 == $act_win_uid) $v7_win2++;
                    }
                }
                
                if ($ec1 > 6 || $ec2 > 6) {
                    if ($hec1 > 6 && $hec2 <= 6) {
                        $c4_total++; if ($hist_h1 == $act_win_uid) $c4_win++;
                        if ($h_score1 > 20) { $r4_total++; if ($hist_h1 == $act_win_uid) $r4_win++; }
                        if (isScoreInBand($h_score1, $band_config1)) { $v4_total++; if ($hist_h1 == $act_win_uid) $v4_win++; }
                    } elseif ($hec1 <= 6 && $hec2 > 6) {
                        $c4_total++; if ($hist_h2 == $act_win_uid) $c4_win++;
                        if ($h_score2 > 20) { $r4_total++; if ($hist_h2 == $act_win_uid) $r4_win++; }
                        if (isScoreInBand($h_score2, $band_config2)) { $v4_total++; if ($hist_h2 == $act_win_uid) $v4_win++; }
                    } elseif ($hec1 > 6 && $hec2 > 6) {
                        $c4_total++; if ($hist_h1 == $act_win_uid || $hist_h2 == $act_win_uid) { $c4_win++; }
                        if ($h_score1 > 20 || $h_score2 > 20) { $r4_total++; if (($h_score1 > 20 && $hist_h1 == $act_win_uid) || ($h_score2 > 20 && $hist_h2 == $act_win_uid)) { $r4_win++; } }
                        if (isScoreInBand($h_score1, $band_config1) || isScoreInBand($h_score2, $band_config2)) { $v4_total++; if ((isScoreInBand($h_score1, $band_config1) && $hist_h1 == $act_win_uid) || (isScoreInBand($h_score2, $band_config2) && $hist_h2 == $act_win_uid)) { $v4_win++; } }
                    }
                }
            }
        }
    }

    if ($ec1 == 6 && $ec2 != 6) {
        if ($c1_total > 0) { $probability_output[$h1_num] = "<b>{$c1_win} / {$c1_total}</b><br><small class='text-success'>(".round(($c1_win / $c1_total) * 100, 1)."%)</small>"; $raw_prob_data[$h1_num] = ($c1_win / $c1_total) * 100; }
        if ($r1_total > 0) { $total_win_ratio_output[$h1_num] = "<b>{$r1_win} / {$r1_total}</b><br><small class='text-success'>(".round(($r1_win / $r1_total) * 100, 1)."%)</small>"; $raw_win_data[$h1_num] = ($r1_win / $r1_total) * 100; }
        if ($v1_total > 0) { $over22_win_ratio_output[$h1_num] = "<b>{$v1_win} / {$v1_total}</b><br><small class='text-success'>(".round(($v1_win / $v1_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h1_num] = ($v1_win / $v1_total) * 100; }
    } 
    elseif ($ec1 == 6 && $ec2 == 6) {
        if ($c2_total > 0) {
            $probability_output[$h1_num] = "<b>{$c2_win1} / {$c2_total}</b><br><small class='text-warning'>(".round(($c2_win1 / $c2_total) * 100, 1)."%)</small>"; $raw_prob_data[$h1_num] = ($c2_win1 / $c2_total) * 100;
            $probability_output[$h2_num] = "<b>{$c2_win2} / {$c2_total}</b><br><small class='text-warning'>(".round(($c2_win2 / $c2_total) * 100, 1)."%)</small>"; $raw_prob_data[$h2_num] = ($c2_win2 / $c2_total) * 100;
        }
        if ($r2_total > 0) {
            $total_win_ratio_output[$h1_num] = "<b>{$r2_win1} / {$r2_total}</b><br><small class='text-warning'>(".round(($r2_win1 / $r2_total) * 100, 1)."%)</small>"; $raw_win_data[$h1_num] = ($r2_win1 / $r2_total) * 100;
            $total_win_ratio_output[$h2_num] = "<b>{$r2_win2} / {$r2_total}</b><br><small class='text-warning'>(".round(($r2_win2 / $r2_total) * 100, 1)."%)</small>"; $raw_win_data[$h2_num] = ($r2_win2 / $r2_total) * 100;
        }
        if ($v2_total > 0) {
            $over22_win_ratio_output[$h1_num] = "<b>{$v2_win1} / {$v2_total}</b><br><small class='text-warning'>(".round(($v2_win1 / $v2_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h1_num] = ($v2_win1 / $v2_total) * 100;
            $over22_win_ratio_output[$h2_num] = "<b>{$v2_win2} / {$v2_total}</b><br><small class='text-warning'>(".round(($v2_win2 / $v2_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h2_num] = ($v2_win2 / $v2_total) * 100;
        }
    } 
    elseif ($ec1 == 5 && $ec2 == 5) {
        if ($c3_total > 0) {
            $probability_output[$h1_num] = "<b>{$c3_win1} / {$c3_total}</b><br><small class='text-info'>(".round(($c3_win1 / $c3_total) * 100, 1)."%)</small>"; $raw_prob_data[$h1_num] = ($c3_win1 / $c3_total) * 100;
            $probability_output[$h2_num] = "<b>{$c3_win2} / {$c3_total}</b><br><small class='text-info'>(".round(($c3_win2 / $c3_total) * 100, 1)."%)</small>"; $raw_prob_data[$h2_num] = ($c3_win2 / $c3_total) * 100;
        }
        if ($r3_total > 0) {
            $total_win_ratio_output[$h1_num] = "<b>{$r3_win1} / {$r3_total}</b><br><small class='text-info'>(".round(($r3_win1 / $r3_total) * 100, 1)."%)</small>"; $raw_win_data[$h1_num] = ($r3_win1 / $r3_total) * 100;
            $total_win_ratio_output[$h2_num] = "<b>{$r3_win2} / {$r3_total}</b><br><small class='text-info'>(".round(($r3_win2 / $r3_total) * 100, 1)."%)</small>"; $raw_win_data[$h2_num] = ($r3_win2 / $r3_total) * 100;
        }
        if ($v3_total > 0) {
            $over22_win_ratio_output[$h1_num] = "<b>{$v3_win1} / {$v3_total}</b><br><small class='text-info'>(".round(($v3_win1 / $v3_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h1_num] = ($v3_win1 / $v3_total) * 100;
            $over22_win_ratio_output[$h2_num] = "<b>{$v3_win2} / {$v3_total}</b><br><small class='text-info'>(".round(($v3_win2 / $v3_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h2_num] = ($v3_win2 / $v3_total) * 100;
        }
    }

    // =========================================================================
    // ⚙️ 雙軌獨立隔離區：左軌加權總分不動（除以3），右軌精確引入「四核組合累計勝率」
    // =========================================================================
    foreach ($sorted_horses as $horse_node) {
        $h_id = intval($horse_node['horse_num']);
        
        $p1 = floatval(($raw_prob_data[$h_id] ?? 0) / 100);
        $p2 = floatval(($raw_win_data[$h_id] ?? 0) / 100);
        $p3 = floatval(($raw_threshold_data[$h_id] ?? 0) / 100);
        
        // 原始三軌期望值公式（除以3，基本能力盤面 100% 對齊不變）
        $p_base_avg = ($p1 + $p2 + $p3) / 3;
        if ($p_base_avg == 0 && floatval($horse_node['total_score']) > 0) { $p_base_avg = (floatval($horse_node['total_score']) / 18.0) * 0.42; }
        $boost = ($h_id === $h1_num) ? $band_config1['boost'] : (($h_id === $h2_num) ? $band_config2['boost'] : 1.0);
        $prem = ($h_id === $h1_num) ? $premium_mult1 : (($h_id === $h2_num) ? $premium_mult2 : 1.0);
        $base_ev_score = $p_base_avg * 100 * floatval($boost) * $prem;

        // 🚀【四核心開火軌】：尋找今日強力推薦名家群中，10月1日起累積勝率最高的「四核心配對組合」
        $today_p1_experts = $horse_node['p1_from']; $today_p1_count = count($today_p1_experts);
        $highest_quad_name = "無四核共識"; $highest_quad_win_rate = 0.0; $highest_quad_text = "暫無四核強推";

        if ($today_p1_count >= 4) {
            sort($today_p1_experts);
            // 四四配對排列組合
            for ($i = 0; $i < $today_p1_count; $i++) {
                for ($j = $i + 1; $j < $today_p1_count; $j++) {
                    for ($k = $j + 1; $k < $today_p1_count; $k++) {
                        for ($l = $k + 1; $l < $today_p1_count; $l++) {
                            $quad_key = "{$today_p1_experts[$i]}+{$today_p1_experts[$j]}+{$today_p1_experts[$k]}+{$today_p1_experts[$l]}";
                            
                            // 比對從10月1日起累積計算出來的四核心組合勝率
                            if (isset($quad_win_rates_map[$quad_key]) && $quad_win_rates_map[$quad_key] > $highest_quad_win_rate) {
                                $highest_quad_win_rate = $quad_win_rates_map[$quad_key];
                                $nameMap = array('expert_ai' => 'AI', 'expert_ball' => '波仔', 'expert_racingpost' => '賽報', 'expert_siu_siu' => '蕭蕭', 'expert_horse_king' => '馬至尊', 'expert_happy_bird' => 'Happy Bird');
                                $highest_quad_name = "[" . ($nameMap[$today_p1_experts[$i]] ?? $today_p1_experts[$i]) . "+" . ($nameMap[$today_p1_experts[$j]] ?? $today_p1_experts[$j]) . "+" . ($nameMap[$today_p1_experts[$k]] ?? $today_p1_experts[$k]) . "+" . ($nameMap[$today_p1_experts[$l]] ?? $today_p1_experts[$l]) . "]";
                                $highest_quad_text = "最強四核: <b>{$highest_quad_name}</b> 勝率: <b>" . round($highest_quad_win_rate * 100, 1) . "%</b> (" . $expert_quad_win_stats[$quad_key]['wins'] . "/" . $expert_quad_win_stats[$quad_key]['total'] . ")";
                            }
                        }
                    }
                }
            }
        }
        if ($highest_quad_win_rate === 0.0) { $highest_quad_text = "<small class='text-muted'>暫無四核強推</small>"; }

        // 四軌合流最終分值 = 三軌基礎得分 + 7分表位置Q分 + 四核組合增益紅利分
        $add_7_bonus = 0.0;
        if ($has_7_data) { $add_7_bonus = ($h_id === $first_horse_7) ? ($first_q_pct * 100) : (($h_id === $second_horse_7) ? ($second_q_pct * 100) : 0.0); }

        $trend_score = $base_ev_score + ($add_7_bonus * 0.15) + ($highest_quad_win_rate * 100 * 0.40); // 0.40 為四核超維增益系數
        if ($trend_score > 100) $trend_score = 100;
        $final_scores_temp[$h_id] = round($trend_score, 1);
        
        $weighted_score_output[$h_id] = "<span>" . round($trend_score, 1) . "分</span><br><small style='color:#ca8a04; font-size:0.75rem; font-weight:normal;'>{$highest_quad_text}</small>";
    }

    // 萬能補償
    foreach ($sorted_horses as $h_bk) {
        $uid = intval($h_bk['horse_num']);
        if (!isset($final_scores_temp[$uid])) {
            $sc_raw = floatval($h_bk['total_score']); $final_fallback = ($sc_raw / 18.0) * 36.0; if ($final_fallback == 0 && $sc_raw == 0) { $final_fallback = 2.5; }
            $final_scores_temp[$uid] = round($final_fallback, 1);
            $weighted_score_output[$uid] = "<strong style='color:#ff7675; font-size:1.15rem;'>".round($final_fallback, 1)."分</strong><br><small class='text-muted' style='font-size:0.75rem; font-weight:normal;'>暫無四核強推</small>";
        }
    }

    // =========================================================================
    // 🔒 [自動快照落地管線] —— 100% 寫入真大數據總分
    // =========================================================================
    $chk_stmt = $conn->prepare("SELECT id FROM race_score_snapshot WHERE race_date = ? AND race_num = ? LIMIT 1");
    $chk_stmt->bind_param("si", $target_date, $r_num);
    $chk_stmt->execute();
    $chk_res = $chk_stmt->get_result();
    $already_saved = ($chk_res->num_rows > 0);
    $chk_stmt->close();

    if (!$already_saved) {
        $stmt = $conn->prepare("INSERT INTO race_score_snapshot (race_date, race_num, horse_num, expert_count, prob_rate, win_rate, threshold_rate, weighted_score) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt) {
            foreach ($sorted_horses as $h_snap) {
                $h_id = intval($h_snap['horse_num']);
                $score_to_save = $final_scores_temp[$h_id] ?? 0.0;
                if ($score_to_save > 2.5) {
                    $dummy_rate = 0.00;
                    $stmt->bind_param("siiiiddd", $target_date, $r_num, $h_id, $h_snap['expert_count'], $dummy_rate, $dummy_rate, $dummy_rate, $score_to_save);
                    $stmt->execute();
                }
            }
            $stmt->close();
        }
    }

    foreach ($sorted_horses as $idx => $h_info) {
        $uid = intval($h_info['horse_num']);
        $sorted_horses[$idx]['probability_output'] = $probability_output[$uid] ?? "-";
        $sorted_horses[$idx]['ratio_output'] = $total_win_ratio_output[$uid] ?? "-"; 
        $sorted_horses[$idx]['over22_output'] = $over22_win_ratio_output[$uid] ?? "-"; 
        $sorted_horses[$idx]['weighted_score_output'] = $weighted_score_output[$uid] ?? "-"; 
    }

    $final_dashboard[$r_num] = array(
        'meta' => array( 'type' => $type, 'target' => array( 'dan' => $dan_text, 'jiao' => $jiao_text ), 'race_tag' => $race_tag, 'pattern_key' => $pKey ),
        'horses' => $sorted_horses
    );
}

ob_end_clean(); 
header('Content-Type: application/json; charset=utf-8');
echo json_encode($final_dashboard);
?>