<?php
include __DIR__ . '/../../common/config.php';

/* =========================================================
   CONFIG
========================================================= */
$BOOK_MARGIN = 0.06; // 6% bookmaker margin
$MIN_PROB = 0.01;
$MAX_PROB = 0.99;

/* =========================================================
   HELPERS
========================================================= */
function clamp($v, $min, $max) {
    return max($min, min($max, $v));
}

/**
 * Convert ICC numeric rating (eg 124, 110, 15)
 * into betting strength (0.70 – 1.30)
 */
function ratingToStrength($rating) {

    $min = 40;   // weakest teams
    $max = 130;  // top ICC teams

    $rating = max($min, min($max, (int)$rating));

    return 0.70 + (($rating - $min) / ($max - $min)) * 0.60;
}

/**
 * Betfair-style odds ladder
 */
function ladderOdds($odds) {
    if ($odds < 2)   return round($odds, 2);
    if ($odds < 3)   return round($odds, 2);
    if ($odds < 4)   return round($odds, 2);
    if ($odds < 6)   return round($odds, 2);
    if ($odds < 10)  return round($odds, 1);
    if ($odds < 20)  return round($odds, 1);
    return round($odds, 0);
}

/**
 * Lay spread based on Betfair behaviour
 */
function laySpread($back) {
    if ($back <= 1.05) return 0.01;
    if ($back <= 1.20) return 0.02;
    if ($back <= 2.00) return 0.04;
    if ($back <= 4.00) return 0.06;
    return 0.12;
}

function maxOversByFormat($format) {
    switch ($format) {
        case 'T10': return 10;
        case 'ODI': return 50;
        case 'TEST': return 90;
        default: return 20; // T20
    }
}

/* =========================================================
   FETCH EVENTS (UPCOMING + LIVE)
========================================================= */
$events = mysqli_query($conn, "
    SELECT match_id, format, team1_id, team2_id,team1,team2
    FROM events
    WHERE status IN ('upcoming','in progress','innings break')
");

while ($event = mysqli_fetch_assoc($events)) {

    $match_id = (int)$event['match_id'];
    $format   = $event['format'];

    $team1_id = $event['team1'];
    $team2_id = $event['team2'];

    /* =====================================================
       TEAM RATINGS → STRENGTH
    ===================================================== */
    $t1 = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT rating FROM team WHERE id = '$team1_id' AND format='$format'"
    ));
    $t2 = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT rating FROM team WHERE id = '$team2_id' AND format='$format'"
    ));

    $team1_rating = $t1['rating'] ?? rand(60,90);
    $team2_rating = $t2['rating'] ?? rand(60,90);

    $team1_strength = ratingToStrength($team1_rating);
    $team2_strength = ratingToStrength($team2_rating);

    /* =====================================================
       INITIAL (PRE-MATCH) PROBABILITY
    ===================================================== */
    $team1_prob = $team1_strength / ($team1_strength + $team2_strength);
    $team2_prob = 1 - $team1_prob;

    /* =====================================================
       LIVE SCORE (IF AVAILABLE)
    ===================================================== */
    $score_q = mysqli_query($conn, "
        SELECT *
        FROM score
        WHERE match_id = $match_id
        ORDER BY innings_number DESC
        LIMIT 1
    ");

    if ($score = mysqli_fetch_assoc($score_q)) {

        $innings = (int)$score['innings_number'];
        $batting = (int)$score['batting_team_id'];

        $runs   = (int)$score['runs'];
        $wkts   = (int)$score['wickets'];
        $balls  = (int)$score['balls'];
        $target = (int)$score['target'];

        $maxOvers   = maxOversByFormat($format);
        $totalBalls = $maxOvers * 6;

        /* ================= FIRST INNINGS ================= */
        if ($innings === 1 && $balls > 0) {

            $progress = $balls / $totalBalls;
            $wkt_left = (10 - $wkts) / 10;
            $rr       = ($runs / $balls) * 6;

            $rr_boost = clamp($rr / 8, 0.7, 1.3);

            $shift = ($progress * 0.30 + $wkt_left * 0.20) * $rr_boost;

            if ($batting === $team1_id) {
                $team1_prob += $shift;
            } else {
                $team2_prob += $shift;
            }
        }

        /* ================= SECOND INNINGS ================= */
        if ($innings === 2 && $target > 0) {

            $runs_req   = max(0, $target - $runs);
            $balls_left = max(1, $totalBalls - $balls);

            if ($runs_req === 0) {
                if ($batting === $team1_id) {
                    $team1_prob = 0.99;
                    $team2_prob = 0.01;
                } else {
                    $team2_prob = 0.99;
                    $team1_prob = 0.01;
                }
            } else {
                $req_rr = ($runs_req / $balls_left) * 6;
                $rr_pressure = clamp($req_rr / 8, 0, 1);
                $wkt_left = (10 - $wkts) / 10;

                $chase_prob =
                    (1 - $rr_pressure) * 0.55 +
                    $wkt_left * 0.35 +
                    (1 - ($runs_req / $target)) * 0.10;

                if ($batting === $team1_id) {
                    $team1_prob = $chase_prob;
                    $team2_prob = 1 - $team1_prob;
                } else {
                    $team2_prob = $chase_prob;
                    $team1_prob = 1 - $team2_prob;
                }
            }
        }
    }

    /* =====================================================
       NORMALIZE
    ===================================================== */
    $team1_prob = clamp($team1_prob, $MIN_PROB, $MAX_PROB);
    $team2_prob = clamp($team2_prob, $MIN_PROB, $MAX_PROB);

    $sum = $team1_prob + $team2_prob;
    $team1_prob /= $sum;
    $team2_prob /= $sum;

    /* =====================================================
       ODDS (BETFAIR STYLE)
    ===================================================== */
    $team1_back = ladderOdds(1 / ($team1_prob * (1 + $BOOK_MARGIN)));
    $team2_back = ladderOdds(1 / ($team2_prob * (1 + $BOOK_MARGIN)));

    if ($team1_back == $team2_back) {
        $team2_back += 0.02;
    }

    $team1_lay = ladderOdds($team1_back + laySpread($team1_back));
    $team2_lay = ladderOdds($team2_back + laySpread($team2_back));

    /* =====================================================
       SAVE ODDS
    ===================================================== */
    mysqli_query($conn, "
        DELETE FROM odds
        WHERE match_id = $match_id
          AND market_name = 'Match Odds'
    ");

    mysqli_query($conn, "
        INSERT INTO odds
        (
            match_id, market_name,
            team1_odds_back, team2_odds_back,
            team1_odds_lay, team2_odds_lay,
            created_at, updated_at
        )
        VALUES
        (
            $match_id, 'Match Odds',
            $team1_back, $team2_back,
            $team1_lay, $team2_lay,
            NOW(), NOW()
        )
    ");
}

echo json_encode([
    'success' => true,
    'message' => 'Match Odds updated (ICC rating + live, Betfair ladder)'
]);
