<?php
require_once 'admin/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) {
        $stmt = $db->prepare("SELECT MAX(draw_number) as last_draw FROM lottery_results 
                             WHERE market_id = ? AND draw_date = ?");
        $stmt->execute([$market_id, $draw_date]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $last_draw = $result['last_draw'];
        if ($last_draw) {
            // Increment draw number
            $next_draw = str_pad((int)$last_draw + 1, 4, '0', STR_PAD_LEFT);
        } else {
            // Jika belum ada draw untuk tanggal ini, mulai dari 0001
            $next_draw = '0001';
        }
        
        echo json_encode(['success' => true, 'next_draw' => $next_draw]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid parameters']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}