<?php
include "../koneksi.php";

// Ambil data dari form
$tanggal = $_POST['tanggal'];
$winner_prize = $_POST['winner_prize'];
$prize2 = $_POST['prize2'];
$prize3 = $_POST['prize3'];
$draw_type = $_POST['draw_type'];
$draw_id = $_POST['draw_id'];
$draw_time = $_POST['draw_time'];
$draw_end = $_POST['draw_end'];

// Spesial dan Consolation
$spesial = [];
$consolation = [];

for ($i = 1; $i <= 6; $i++) {
    $spesial[$i] = isset($_POST["spesial$i"]) && $_POST["spesial$i"] !== '' ? $_POST["spesial$i"] : NULL;
    $consolation[$i] = isset($_POST["consolation$i"]) && $_POST["consolation$i"] !== '' ? $_POST["consolation$i"] : NULL;
}

// Siapkan query untuk result_talaga
$query_talaga = "INSERT INTO result_talaga (
    draw_type, tanggal, winner_prize, prize2, draw_id, prize3, 
    spesial1, spesial2, spesial3, spesial4, spesial5, spesial6,
    consolation1, consolation2, consolation3, consolation4, consolation5, consolation6
) VALUES (
    '$draw_type', '$tanggal', '$winner_prize', '$prize2', '$draw_id', '$prize3', " .
    "'" . implode("','", array_map(function ($v) {
        return $v !== NULL ? $v : ''; }, $spesial)) . "', " .
    "'" . implode("','", array_map(function ($v) {
        return $v !== NULL ? $v : ''; }, $consolation)) . "'
)";

$proses = mysqli_query($koneksi, $query_talaga);

// Jika berhasil, lanjut insert ke result_lengkap
if ($proses) {
    $query_lengkap = "INSERT INTO result_lengkap (
        tanggal, draw_time, draw_end, draw_type, draw_id, 
        winner_prize, prize2, prize3, 
        spesial1, spesial2, spesial3, spesial4, spesial5, spesial6,
        consolation1, consolation2, consolation3, consolation4, consolation5, consolation6
    ) VALUES (
        '$tanggal', '$draw_time', '$draw_end', '$draw_type', '$draw_id', 
        '$winner_prize', '$prize2', '$prize3', " .
        "'" . implode("','", array_map(function ($v) {
            return $v !== NULL ? $v : ''; }, $spesial)) . "', " .
        "'" . implode("','", array_map(function ($v) {
            return $v !== NULL ? $v : ''; }, $consolation)) . "'
    )";

    $result_lengkap = mysqli_query($koneksi, $query_lengkap);

    if ($result_lengkap) {
        header("Location: result.php?alert=berhasil");
        exit();
    } else {
        echo "Proses Gagal pada result_lengkap<br>Error: " . mysqli_error($koneksi);
    }
} else {
    echo "Proses Gagal pada result_talaga<br>Error: " . mysqli_error($koneksi);
}

mysqli_close($koneksi);
