<?php
// api/v1/markets/weekly-charts.php
declare(strict_types=1);
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, x-api-key, x-ts, x-sign");

require_once '../../db.php';
require_once '../../middleware.php';

verifyApiRequest();

$game_id = isset($_GET['game_id']) ? (int)$_GET['game_id'] : 1; 

$today_timestamp = strtotime('today');
$day_of_week = date('N', $today_timestamp); 

$monday_timestamp = ($day_of_week == 1) ? $today_timestamp : strtotime('last monday', $today_timestamp);
$db_monday = date("Y-m-d", $monday_timestamp);

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;
    }
}

try {
    // 🚀 1. AUTO-GENERATION CHECK (For the requested game)
    $days_count = ($game_id == 2) ? 5 : 6; // Main Bazar = 5 days, Kalyan = 6 days
    
    for ($i = 0; $i < $days_count; $i++) {
        $gen_date = date("Y-m-d", strtotime("+$i days", $monday_timestamp));
        
        $chk = $db->prepare("SELECT id FROM weekly_chart_guesses WHERE game_id=? AND guess_date=? LIMIT 1");
        $chk->bind_param("is", $game_id, $gen_date);
        $chk->execute();
        $exists = $chk->get_result()->num_rows > 0;
        $chk->close();
        
        if (!$exists) {
            $ins = $db->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", $game_id, $type, $gen_date, $o1, $o2, $o3, $o4); $ins->execute();

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

            $type = 'PATTI';
            $ins->bind_param("issssss", $game_id, $type, $gen_date, $p1, $p2, $p3, $p4); $ins->execute();
            $ins->close();
        }
    }

    // 📊 2. FETCH AND VERIFY RESULTS
    $days_names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    $response = ["success" => true, "data" => []];

    for ($i = 0; $i < $days_count; $i++) {
        $current_date = date("Y-m-d", strtotime("+$i days", $monday_timestamp));
        
        // Fetch actual result for Pass/Fail match
        $stmt_res = $db->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((string)($open_patti[0] + $open_patti[1] + $open_patti[2]), -1) : '';
        $actual_close_ank = $is_close_out ? substr((string)($close_patti[0] + $close_patti[1] + $close_patti[2]), -1) : '';
        $actual_jodi = ($is_open_out && $is_close_out) ? $actual_open_ank . $actual_close_ank : '';

        // Fetch Guesses
        $guess_data = ['OPEN' => [], 'JODI' => [], 'PATTI' => []];
        $stmt_guess = $db->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();

        // Add to JSON response
        $response['data'][] = [
            "day" => $days_names[$i],
            "date" => $current_date,
            "ank" => $guess_data['OPEN'] ?? [],
            "patti" => $guess_data['PATTI'] ?? [],
            "jodi" => $guess_data['JODI'] ?? []
        ];
    }

    echo json_encode($response);

} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(["success" => false, "message" => "Server Error"]);
}
?>