<?php
require __DIR__ . '/core/vendor/autoload.php';
$app = require_once __DIR__ . '/core/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

$apiKey = '12f43100981670ce367e3aabff6f3bb4';
// Fetching IPL specifically and some other cricket types
$sports = ['cricket_ipl', 'cricket_international_t20', 'cricket_odi', 'soccer_uefa_champs_league', 'tennis_atp_french_open'];

$count = 0;

foreach ($sports as $sport) {
    $url = "https://api.the-odds-api.com/v4/sports/{$sport}/odds/?apiKey={$apiKey}&regions=uk,us&markets=h2h";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($response, true);
    
    if (!is_array($data)) {
        echo "Error fetching data for {$sport}: " . $response . "\n";
        continue;
    }

    foreach ($data as $matchData) {
        if ($count >= 100) break; 
        
        $sportTitle = $matchData['sport_title'];
        $homeTeam = $matchData['home_team'];
        $awayTeam = $matchData['away_team'];
        $matchName = $homeTeam . ' vs ' . $awayTeam;
        $startTime = Carbon::parse($matchData['commence_time'])->setTimezone('Asia/Kolkata')->format('Y-m-d H:i:s');
        
        // 1. Category (e.g. Cricket)
        $categoryName = explode(' ', $sportTitle)[0];
        $category = DB::table('categories')->where('name', $categoryName)->first();
        if (!$category) {
            $categoryId = DB::table('categories')->insertGetId([
                'name' => $categoryName,
                'status' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        } else {
            $categoryId = $category->id;
        }

        // 2. League (e.g. IPL)
        $leagueName = $sportTitle;
        $league = DB::table('leagues')->where('name', $leagueName)->where('category_id', $categoryId)->first();
        if (!$league) {
            $leagueId = DB::table('leagues')->insertGetId([
                'category_id' => $categoryId,
                'name' => $leagueName,
                'status' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        } else {
            $leagueId = $league->id;
        }

        // 3. Match
        $match = DB::table('matches')->where('name', $matchName)->where('league_id', $leagueId)->first();
        if (!$match) {
            $matchId = DB::table('matches')->insertGetId([
                'category_id' => $categoryId,
                'league_id' => $leagueId,
                'name' => $matchName,
                'start_time' => $startTime,
                'end_time' => Carbon::parse($startTime)->addHours(8)->format('Y-m-d H:i:s'), 
                'status' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        } else {
            $matchId = $match->id;
            // Update start time if it changed
            DB::table('matches')->where('id', $matchId)->update(['start_time' => $startTime]);
        }

        // 4. Question
        $questionName = "Match Winner";
        $question = DB::table('questions')->where('match_id', $matchId)->where('name', $questionName)->first();
        if (!$question) {
            $questionId = DB::table('questions')->insertGetId([
                'match_id' => $matchId,
                'name' => $questionName,
                'status' => 1,
                'result' => 0,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        } else {
            $questionId = $question->id;
        }

        // 5. Options (Odds)
        if (isset($matchData['bookmakers']) && count($matchData['bookmakers']) > 0) {
            $bookmaker = $matchData['bookmakers'][0];
            $markets = $bookmaker['markets'];
            foreach ($markets as $market) {
                if ($market['key'] == 'h2h') {
                    foreach ($market['outcomes'] as $outcome) {
                        $optionName = $outcome['name'];
                        $price = $outcome['price']; 
                        
                        $dividend = (int)($price * 100);
                        $divisor = 100;
                        
                        $option = DB::table('options')->where('question_id', $questionId)->where('name', $optionName)->first();
                        if (!$option) {
                            DB::table('options')->insert([
                                'question_id' => $questionId,
                                'name' => $optionName,
                                'dividend' => $dividend,
                                'divisor' => $divisor,
                                'status' => 1,
                                'created_at' => now(),
                                'updated_at' => now(),
                            ]);
                        } else {
                            DB::table('options')->where('id', $option->id)->update([
                                'dividend' => $dividend,
                                'divisor' => $divisor,
                                'updated_at' => now(),
                            ]);
                        }
                    }
                }
            }
        }
        $count++;
    }
}

echo "Successfully synced {$count} matches and odds to the database.";
?>

