<?php
	require_once('session.php');
    $users = $u['user'];
    $pid = $_GET['pid'];
    $periode = $_GET['periode'];

    $getPeriode = mysqli_query($conn,"SELECT * FROM `tb_periode` WHERE `pid` = '$pid' AND `no` = '$periode'") or die(mysqli_error());
    $gpp = mysqli_fetch_array($getPeriode);
    if($gpp['status'] == 0){
        $kabupaten = mysqli_query($conn,"SELECT * FROM `tb_pasaran_result` WHERE pid = '$pid' AND periode = '$periode' ORDER BY cuid ASC") or die(mysqli_error($conn));
        while($kk = mysqli_fetch_array($kabupaten)){
            $gameid = $kk['gameid'];
            $resultAngka = $kk['p_result'];
            $posisi = $kk['posisi'];
            $cekMenang1 = mysqli_query($conn,"SELECT * FROM `tb_taruhan` WHERE `pid` = '$pid' AND `gameid` = '$gameid' AND `periode` = '$periode' AND `tebak` = '$resultAngka' AND `posisi` = '$posisi'") or die(mysqli_error());
            $cmm1 = mysqli_num_rows($cekMenang1);
            if($cmm1 > 0){
                while($cm1 = mysqli_fetch_array($cekMenang1)){
                    $cuid = $cm1['cuid'];
                    $pemenang = $cm1['userID'];
                    $jumlah = $cm1['jumlah'];
                    $setWin = mysqli_query($conn,"UPDATE `tb_taruhan` SET `keterangan` = 'Menang', status = 1 WHERE cuid = '$cuid'") or die(mysqli_error());
                    $setBalance = mysqli_query($conn,"UPDATE `tb_balance` SET `active` = active + '$jumlah' WHERE userID = '$pemenang'") or die(mysqli_error());

                }
            }
        }

        $update = mysqli_query($conn,"UPDATE `tb_periode` SET status = 1 WHERE `pid` = '$pid' AND `no` = '$periode'") or die(mysqli_error());
    }
    
    header('location:../betting/?pid='.$pid.'&periode='.$periode);
    exit();
    
?>