<?php
session_start();
require_once 'config.php';
header('Content-Type: application/json');

try {
    global $pdo;
    
    // 1. Admin Settings Check
    $stmt = $pdo->query("SELECT * FROM cricket_settings LIMIT 1");
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
    $mode = $settings['mode'] ?? 'manual';
    $apiUrl = $settings['api_url'] ?? '';

    $finalMatches = [];

    // ==================================================
    // PART A: FETCH MANUAL MATCHES (From Database)
    // ==================================================
    $manualStmt = $pdo->query("SELECT * FROM live_matches WHERE is_active = 1 ORDER BY id DESC");
    $dbMatches = $manualStmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($dbMatches as $m) {
        $finalMatches[] = [
            "id" => $m['match_id'],
            "name" => $m['team1_name'] . " vs " . $m['team2_name'],
            "status" => $m['status'],
            "score" => $m['score'],
            "is_locked" => $m['is_locked'],
            "start_time" => $m['start_time'],
            "is_manual" => true, // Flag to identify manual matches
            "team1" => [
                "name" => $m['team1_name'], 
                "logo" => $m['team1_logo'],
                "back" => $m['t1_back'], 
                "lay" => $m['t1_lay']
            ],
            "team2" => [
                "name" => $m['team2_name'], 
                "logo" => $m['team2_logo'],
                "back" => $m['t2_back'], 
                "lay" => $m['t2_lay']
            ]
        ];
    }

    // ==================================================
    // PART B: FETCH API MATCHES (Auto Sync from Lotusbook)
    // ==================================================
    if ($mode === 'api' && !empty($apiUrl)) {
        
        // cURL setup for fast fetching
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5 seconds timeout so site doesn't hang
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);

        if ($response) {
            $apiData = json_decode($response, true);
            
            if (isset($apiData['success']) && $apiData['success'] == true) {
                
                // Fetch In-Play Events
                $inPlay = $apiData['result']['inPlayEvents'] ?? [];
                // Fetch Popular (Upcoming) Events
                $popular = $apiData['result']['popularEvents'] ?? [];
                
                $allApiMatches = array_merge($inPlay, $popular);

                foreach ($allApiMatches as $apiMatch) {
                    // Only process Cricket Matches to keep it clean
                    if ($apiMatch['eventType'] !== 'Cricket') continue;

                    $event = $apiMatch['event'];
                    $market = $apiMatch['market'];
                    $scores = $apiMatch['scores'];
                    
                    // Filter out null runners to safely get Back/Lay prices
                    $runners = $market['consolidatedRunner'] ?? [];
                    $backOdds = array_values(array_filter($runners['back'] ?? []));
                    $layOdds = array_values(array_filter($runners['lay'] ?? []));

                    // Safely get Team Names
                    $team1Name = $backOdds[0]['runner']['name'] ?? "Team 1";
                    $team2Name = $backOdds[1]['runner']['name'] ?? "Team 2";

                    // Safely get Odds
                    $t1Back = $backOdds[0]['price'] ?? 0;
                    $t1Lay = $layOdds[0]['price'] ?? 0;
                    $t2Back = $backOdds[1]['price'] ?? 0;
                    $t2Lay = $layOdds[1]['price'] ?? 0;

                    // Format Live Score
                    $scoreStr = "Starting Soon";
                    if (!empty($scores) && isset($scores['score'])) {
                        $battingTeam = $scores['battingTeamName'] ?? '';
                        $runs = $scores['score'] ?? 0;
                        $wickets = $scores['wickets'] ?? 0;
                        $overs = $scores['overs'] ?? 0;
                        $scoreStr = "$battingTeam $runs/$wickets ($overs Ov)";
                    }

                    // Check if Market is Suspended by API
                    $isLocked = ($market['status'] !== 'OPEN') ? 1 : 0;
                    $statusStr = $apiMatch['isInPlay'] ? 'LIVE' : 'UPCOMING';

                    // Prepare Match Object
                    $finalMatches[] = [
                        "id" => $event['id'], // Original API Match ID
                        "name" => $event['name'],
                        "status" => $statusStr,
                        "score" => $scoreStr,
                        "is_locked" => $isLocked,
                        "start_time" => $event['openDate'],
                        "is_manual" => false,
                        "team1" => [
                            "name" => $team1Name, 
                            "logo" => "default.png", // API doesn't give logos, we use default
                            "back" => $t1Back, 
                            "lay" => $t1Lay
                        ],
                        "team2" => [
                            "name" => $team2Name, 
                            "logo" => "default.png", 
                            "back" => $t2Back, 
                            "lay" => $t2Lay
                        ]
                    ];
                }
            }
        }
    }

    echo json_encode(["success" => true, "data" => $finalMatches]);

} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Sync Error"]);
}
?>