<?php
require_once 'config.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $market_id = isset($_POST['market_id']) ? (int)$_POST['market_id'] : 0;
    $draw_date = isset($_POST['draw_date']) ? $_POST['draw_date'] : '';
    
    if ($market_id && $draw_date) {
        try {
            // Cari draw number terakhir untuk pasaran dan tanggal ini
            $stmt = $db->prepare("SELECT draw_number FROM lottery_results 
                                 WHERE market_id = ? AND draw_date = ? 
                                 ORDER BY draw_number DESC LIMIT 1");
            $stmt->execute([$market_id, $draw_date]);
            $last_draw = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($last_draw) {
                $next_draw_number = str_pad((intval($last_draw['draw_number']) + 1), 4, '0', STR_PAD_LEFT);
            } else {
                // Jika tidak ada result untuk tanggal ini, cari yang terakhir
                $stmt = $db->prepare("SELECT draw_number FROM lottery_results 
                                     WHERE market_id = ? 
                                     ORDER BY draw_date DESC, draw_number DESC LIMIT 1");
                $stmt->execute([$market_id]);
                $last_draw = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($last_draw) {
                    $next_draw_number = str_pad((intval($last_draw['draw_number']) + 1), 4, '0', STR_PAD_LEFT);
                } else {
                    $next_draw_number = '0001';
                }
            }
            
            echo json_encode(['next_draw_number' => $next_draw_number]);
        } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
        }
    } else {
        echo json_encode(['error' => 'Invalid parameters']);
    }
} else {
    echo json_encode(['error' => 'Invalid request method']);
}