<?php
include 'config.php';
date_default_timezone_set('Asia/Jakarta');

// Handle form submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $pasaran = $_POST['pasaran'];
    $prize_type = $_POST['prize_type'];
    $result_time = $_POST['result_time'];

    // Cek apakah jadwal sudah ada
    $check = $conn->prepare("SELECT * FROM auto_result_schedule WHERE pasaran = ? AND prize_type = ?");
    $check->bind_param("ss", $pasaran, $prize_type);
    $check->execute();
    $result = $check->get_result();

    if ($result->num_rows > 0) {
        $stmt = $conn->prepare("UPDATE auto_result_schedule SET result_time = ? WHERE pasaran = ? AND prize_type = ?");
        $stmt->bind_param("sss", $result_time, $pasaran, $prize_type);
    } else {
        $stmt = $conn->prepare("INSERT INTO auto_result_schedule (pasaran, prize_type, result_time, last_generated) VALUES (?, ?, ?, '')");
        $stmt->bind_param("sss", $pasaran, $prize_type, $result_time);
    }
    $stmt->execute();
    echo "<p>Jadwal berhasil disimpan!</p>";
}

// Ambil semua jadwal
$jadwal = $conn->query("SELECT * FROM auto_result_schedule ORDER BY pasaran, prize_type");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Atur Jadwal Prize Otomatis</title>
</head>
<body>
    <h2>Form Atur Jadwal Prize</h2>
    <form method="POST">
        <label>Pasaran:</label>
        <input type="text" name="pasaran" required><br>
        <label>Prize:</label>
        <select name="prize_type">
            <option value="2nd">2nd</option>
            <option value="3rd">3rd</option>
            <option value="Starter">Starter</option>
            <option value="Consolation">Consolation</option>
        </select><br>
        <label>Jam Result:</label>
        <input type="time" name="result_time" required><br>
        <button type="submit">Simpan</button>
    </form>

    <h3>Daftar Jadwal Saat Ini</h3>
    <table border="1">
        <tr><th>Pasaran</th><th>Prize</th><th>Jam</th><th>Terakhir Generate</th></tr>
        <?php while($row = $jadwal->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($row['pasaran']) ?></td>
                <td><?= htmlspecialchars($row['prize_type']) ?></td>
                <td><?= htmlspecialchars($row['result_time']) ?></td>
                <td><?= htmlspecialchars($row['last_generated']) ?></td>
            </tr>
        <?php endwhile; ?>
    </table>
</body>
</html>
