<?php
require_once 'config.php';

// Set timezone
date_default_timezone_set('Asia/Jakarta');

// Logging
file_put_contents('generate_log.txt', "[" . date('Y-m-d H:i:s') . "] Script started\n", FILE_APPEND);

try {
    // Get markets that should have results generated now
    $now = date('H:i:s');
    $stmt = $db->prepare("SELECT * FROM markets WHERE auto_generate_end <= ? AND auto_generate_active = 1");
    $stmt->execute([$now]);

    while ($market = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // Log proses
        file_put_contents('generate_log.txt', "Processing market: " . $market['market_name'] . "\n", FILE_APPEND);

        // Generate random numbers
        $first_prize = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $second_prize = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $third_prize = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $starter_prize = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $consolation_prize = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        
        // Get next draw number
        $draw_number = getNextDrawNumber($market['id']);
        
        // Insert into database
        $insert = $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())");
        
        $insert->execute([
            $market['id'], 
            $market['market_name'],
            $draw_number,
            date('Y-m-d'),
            $market['result_time'],
            $first_prize,
            $second_prize,
            $third_prize,
            $starter_prize,
            $consolation_prize
        ]);
        
        // Disable auto-generation
        $update = $db->prepare("UPDATE markets SET auto_generate_active = 0 WHERE id = ?");
        $update->execute([$market['id']]);
        
        // Log success
        file_put_contents('generate_log.txt', "Successfully generated results for " . $market['market_name'] . 
                           " (Draw #$draw_number)\n", FILE_APPEND);
    }
    
    // Aktifkan auto generate untuk yang sudah masuk waktunya
    $activate_stmt = $db->prepare("UPDATE markets SET auto_generate_active = 1 
                                  WHERE auto_generate_start <= ? AND auto_generate_end >= ?");
    $activate_stmt->execute([$now, $now]);
    
    file_put_contents('generate_log.txt', "[" . date('Y-m-d H:i:s') . "] Script finished\n", FILE_APPEND);
    
} catch (PDOException $e) {
    file_put_contents('generate_log.txt', "ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
    exit(1);
}