<?php
require_once 'config.php';

// Ambil semua market yang perlu diresult
$markets = $db->query("SELECT * FROM markets")->fetchAll(PDO::FETCH_ASSOC);

$current_time = date('H:i');
$current_date = date('Y-m-d');

foreach ($markets as $market) {
    // Cek apakah sudah waktunya result
    $result_time = date('H:i', strtotime($market['result_time']));
    
    if ($current_time == $result_time) {
        // Cek apakah result hari ini sudah ada
        $stmt = $db->prepare("SELECT COUNT(*) FROM lottery_results 
                             WHERE market_id = ? AND draw_date = ?");
        $stmt->execute([$market['id'], $current_date]);
        $exists = $stmt->fetchColumn();
        
        if (!$exists) {
            // Generate next draw number
            $stmt = $db->prepare("SELECT MAX(draw_number) as max_draw FROM lottery_results 
                                 WHERE market_id = ?");
            $stmt->execute([$market['id']]);
            $max_draw = $stmt->fetch(PDO::FETCH_ASSOC);
            $next_draw = str_pad((int)$max_draw['max_draw'] + 1, 4, '0', STR_PAD_LEFT);
            
            // Generate 1st prize (random 4 digit)
            $first_prize = str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
            
            // Generate other prizes
            $second_prize = substr($first_prize, 1, 3) . rand(0, 9);
            $third_prize = substr($first_prize, 2, 2) . rand(0, 9) . rand(0, 9);
            $starter_prize = substr($first_prize, 0, 1) . rand(0, 9) . rand(0, 9) . rand(0, 9);
            $consolation_prize = substr($first_prize, 3, 1) . rand(0, 9) . rand(0, 9) . rand(0, 9);
            
            // Simpan ke database
            $stmt = $db->prepare("INSERT INTO lottery_results 
                (market_id, market, draw_number, draw_date, result_time, 
                first_prize, second_prize, third_prize, 
                starter_prize, consolation_prize, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $market['id'], $market['market_name'], $next_draw, $current_date, $market['result_time'],
                $first_prize, $second_prize, $third_prize, $starter_prize, $consolation_prize
            ]);
            
            // Log atau kirim notifikasi
            file_put_contents('auto_result.log', 
                "[" . date('Y-m-d H:i:s') . "] Result generated for {$market['market_name']} - Draw #{$next_draw}\n", 
                FILE_APPEND);
        }
    }
}
?>