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



$id = (int)$_GET['id'];
$selected_market = strtolower($_GET['pasaran']);

// Get result data
try {
    $stmt = $db->prepare("SELECT * FROM lottery_results WHERE id = ?");
    $stmt->execute([$id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if(!$result) {
        $_SESSION['error'] = "Result tidak ditemukan!";
        header("Location: edit_result.php?pasaran=" . $selected_market);
        exit();
    }
} catch(PDOException $e) {
    $_SESSION['error'] = "Gagal mengambil data result: " . $e->getMessage();
    header("Location: edit_result.php?pasaran=" . $selected_market);
    exit();
}

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $draw_number = sanitizeInput($_POST['draw_number']);
    $draw_date = sanitizeInput($_POST['draw_date']);
    $result_time = sanitizeInput($_POST['result_time']);
    $first_prize = sanitizeInput($_POST['first_prize']);
    $second_prize = sanitizeInput($_POST['second_prize']);
    $third_prize = sanitizeInput($_POST['third_prize']);
    $starter_prize = sanitizeInput($_POST['starter_prize']);
    $consolation_prize = sanitizeInput($_POST['consolation_prize']);

    if(!preg_match('/^\d{4}$/', $first_prize)) {
        $error = '1st Prize harus 4 digit angka!';
    } else {
        try {
            $db->beginTransaction();

            // Update tabel utama
            $stmt = $db->prepare("UPDATE lottery_results SET 
                draw_number = ?, draw_date = ?, result_time = ?,
                first_prize = ?, second_prize = ?, third_prize = ?,
                starter_prize = ?, consolation_prize = ?
                WHERE id = ?");
            $stmt->execute([
                $draw_number, $draw_date, $result_time,
                $first_prize, $second_prize, $third_prize,
                $starter_prize, $consolation_prize, $id
            ]);


            if($selected_market == 'bogor') {
                $stmtFind = $db->prepare("SELECT id_bogor FROM bogor_results WHERE result_id = ?");
                $stmtFind->execute([$id]);
                $bogor = $stmtFind->fetch(PDO::FETCH_ASSOC);
                $id_bogor = $bogor ? $bogor['id_bogor'] : null;

                if ($id_bogor !== null) {
                    $stmtBogor = $db->prepare("UPDATE bogor_results SET 
                        draw_number_bogor = ?, draw_date_bogor = ?, result_time_bogor = ?,
                        first_prize_bogor = ?, second_prize_bogor = ?, third_prize_bogor = ?,
                        starter_prize_bogor = ?, consolation_prize_bogor = ?
                        WHERE id_bogor = ?");
                    $stmtBogor->execute([
                        $draw_number, $draw_date, $result_time,
                        $first_prize, $second_prize, $third_prize,
                        $starter_prize, $consolation_prize, $id_bogor
                    ]);
                }
            }

            $db->commit();
            $_SESSION['success'] = "Result berhasil diperbarui!";
            header("Location: edit_result.php?pasaran=" . $selected_market);
            exit();
        } catch(PDOException $e) {
            $db->rollBack();
            $error = 'Gagal memperbarui result: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Result - SOLOPOOLS Admin</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
</head>
<body>
    <?php include 'navbar.php'; ?>
            <ul class="nav nav-tabs mb-3" id="marketTabs" role="tablist">
                <li class="nav-item">
                    <a class="nav-link <?= $selected_market == 'Bandung' ? 'active' : '' ?>" href="?pasaran=Bandung">Bandung</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $selected_market == 'Bogor' ? 'active' : '' ?>" href="?pasaran=Bogor">Bogor</a>
                </li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane fade show active">
                    <?php
                    if ($selected_market == 'Bandung') {
                        include 'history_bandung.php';
                    } elseif ($selected_market == 'Bogor') {
                        include 'history_bogor.php';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    <?php if ($success): ?>
    document.getElementById("resultForm").reset();
    <?php endif; ?>
    $('#market_id').focus();
    $('input[pattern="\\d{4}"]').on('input', function () {
        this.value = this.value.replace(/[^0-9]/g, '');
        if (this.value.length > 4) {
            this.value = this.value.slice(0, 4);
        }
    });
});
</script>
</body>
</html>