<?php
require_once 'config.php';
checkLogin();

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $required_fields = [
            'market_id', 'draw_date', 'result_time',
            'first_prize', 'second_prize', 'third_prize',
            'starter_prize', 'consolation_prize'
        ];

        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                $_SESSION['error_message'] = "Semua field harus diisi!";
                redirect('index.php');
            }
        }

        $stmt = $db->prepare("UPDATE lottery_results SET 
            market_id = ?,
            draw_date = ?,
            result_time = ?,
            first_prize = ?,
            second_prize = ?,
            third_prize = ?,
            starter_prize = ?,
            consolation_prize = ?,
            updated_at = NOW()
            WHERE id = ?");

        $stmt->execute([
            $_POST['market_id'],
            $_POST['draw_date'],
            $_POST['result_time'],
            $_POST['first_prize'],
            $_POST['second_prize'],
            $_POST['third_prize'],
            $_POST['starter_prize'],
            $_POST['consolation_prize'],
            $_POST['id']
        ]);

        $_SESSION['success_message'] = "Result berhasil diperbarui!";
    }
} catch (Exception $e) {
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
}

redirect('index.php');