<?php


define('_IN_JOHNCMS', 1);

$headmod = 'bookmaker';
$textl = 'Futbol bashorati | Adminka';
require_once '../incfiles/core.php';
require_once '../incfiles/head.php';

if ($rights >= 7) {
    switch ($mod) {

        case 'add':
            echo '<div class="phdr"><a href="./">Futbol bashorati</a>&nbsp;|&nbsp;Добавить матч</div>';

            if (isset($_POST['submit'])) {
                $team_1 = isset($_POST['team_1']) ? substr(functions::checkin($_POST['team_1']), 0, 30) : null;
                $team_2 = isset($_POST['team_2']) ? substr(functions::checkin($_POST['team_2']), 0, 30) : null;
                $champ = isset($_POST['champ']) ? substr(functions::checkin($_POST['champ']), 0, 30) : null;
                $time = abs(strtotime($_POST['day'] . '.' . $_POST['moth'] . '.' . $_POST['year'] . ' ' . $_POST['hour'] . ':' . $_POST['minute']));
                $developments = implode('|', $_POST['development']);
                $developments = htmlspecialchars($developments);

                $error = array();
                if (empty($team_1))
                    $error[] = 'Mezbon jamoani kiriting';
                if (empty($team_2))
                    $error[] = 'Mehmon jamoani kiriting';
                if ($time == 0)
                    $error[] = 'O\'yin vaqti xato kiritildi';
                if ($time < time())
                    $error[] = 'Hozirgi vaqtda oldingi sanani kiritmang';

                if ($error) {
                    echo functions::display_error($error, '<a href="?mod=add">Qayta urinish</a>');
                }
                else {
                    mysql_query("INSERT INTO `bookmaker_matches` SET
                      `team_1` = '" . mysql_real_escape_string($team_1) . "',
                      `team_2` = '" . mysql_real_escape_string($team_2) . "',
                      `champ` = '" . mysql_real_escape_string($champ) . "',
                      `time` = " . $time . ",
                      `developments` = '" . mysql_real_escape_string($developments) . "'");
                    header('location: ./?act=list_matches');
                }
            }
            else {
                echo '<div class="gmenu"><form action="?mod=add" method="post">'
                    . '<p>Mezbon (max 30):</p>'
                    . '<input type="text" name="team_1">'
                    . '<p>Mehmon (max 30):</p>'
                    . '<input type="text" name="team_2">'
                    . '<p>Chempionat (max 30):</p>'
                    . '<input type="text" name="champ">'
                    . '<p>O\'yin vaqti (kun/oy/yil soat:daqiqa):</p>'
                    . '<select name="day">';
                for ($i = 1; $i < 32; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                echo '</select><select name="moth">';
                for ($i = 1; $i < 13; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                echo '</select><select name="year">';
                for ($i = 2016; $i < 2020; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                echo '</select>&nbsp;<select name="hour">';
                for ($i = 0; $i < 24; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                echo '</select>&nbsp;:&nbsp;<select name="minute">';
                for ($i = 0; $i < 60; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                echo '</select><p>Koefficient (P1:Durrang:P2)</p><select name="development[]">';
                for ($i = 2; $i < 5; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                    echo'</select><select name="development[]">';
					for ($i = 2; $i < 5; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                    echo'</select><select name="development[]">';
					for ($i = 2; $i < 5; $i++) {
                    echo '<option value="' . $i . '">' . $i . '</option>';
                }
                   echo'<p><input type="submit" name="submit" value="Qo\'shish"></p>'
                    . '</form></div>';
            }

            echo '<div class="menu"><a href="./">Orqaga</a></div>';
            break;

        case 'edit':
            $res = mysql_fetch_assoc(mysql_query("SELECT * FROM `bookmaker_matches` WHERE `id` = '$id'"));
            $developments = explode('|', $res['developments']);
            echo '<div class="phdr"><a href="./">Futbol bashorati</a>&nbsp;|&nbsp;O\'yinni o\'zgartirish</div>';

            if ($res['time'] > time()) {
                if (isset($_POST['submit'])) {
                    $team_1 = isset($_POST['team_1']) ? substr(functions::checkin($_POST['team_1']), 0, 30) : null;
                    $team_2 = isset($_POST['team_2']) ? substr(functions::checkin($_POST['team_2']), 0, 30) : null;
                    $champ = isset($_POST['champ']) ? substr(functions::checkin($_POST['champ']), 0, 30) : null;
                    $time = abs(strtotime($_POST['day'] . '.' . $_POST['moth'] . '.' . $_POST['year'] . ' ' . $_POST['hour'] . ':' . $_POST['minute']));
                    $developments = implode('|', $_POST['development']);
                    $developments = htmlspecialchars($developments);

                    $error = array();
                    if (empty($team_1))
                        $error[] = 'Mezbon jamoani kiriting';
                    if (empty($team_2))
                        $error[] = 'Mehmon jamoani kiriting';
                    if ($time == 0)
                        $error[] = 'O\'yin vaqti xato';
                    if ($time < time())
                        $error[] = 'Hozirgi vaqtda avvalgi vaqtga o\'yin qo\'shish mumkin emas';

                    if ($error) {
                        echo functions::display_error($error, '<a href="?mod=edit&amp;id=' . $id . '">Qayta urinish</a>');
                    }
                    else {
                        mysql_query("UPDATE `bookmaker_matches` SET
                          `team_1` = '" . mysql_real_escape_string($team_1) . "',
                          `team_2` = '" . mysql_real_escape_string($team_2) . "',
                          `champ` = '" . mysql_real_escape_string($champ) . "',
                          `time` = " . $time . ",
                          `developments` = '" . mysql_real_escape_string($developments) . "' WHERE `id` = '$id'");
                        header('location: ./?act=list_matches');
                    }
                }
                else {
                    echo '<div class="gmenu"><form action="?mod=edit&amp;id=' . $id . '" method="post">'
                        . '<p>Mezbon (max 30):</p>'
                        . '<input type="text" name="team_1" value="' . $res['team_1'] . '">'
                        . '<p>Mehmon (max 30):</p>'
                        . '<input type="text" name="team_2" value="' . $res['team_2'] . '">'
                        . '<p>Chempionat (max 30):</p>'
                        . '<input type="text" name="champ" ' . (!empty($res['champ']) ? 'value="' . $res['champ'] . '"' : null) . '>'
                        . '<p>O\'yin vaqti (kun/oy/yil soat:daqiqa):</p>'
                        . '<select name="day">';
                    for ($i = 1; $i < 32; $i++) {
                        echo '<option value="' . $i . '" ' . ($i == date('j', $res['time']) ? 'selected' : null) . '>' . $i . '</option>';
                    }
                    echo '</select><select name="moth">';
                    for ($i = 1; $i < 13; $i++) {
                        echo '<option value="' . $i . '" ' . ($i == date('n', $res['time']) ? 'selected' : null) . '>' . $i . '</option>';
                    }
                    echo '</select><select name="year">';
                    for ($i = 2016; $i < 2020; $i++) {
                        echo '<option value="' . $i . '" ' . ($i == date('Y', $res['time']) ? 'selected' : null) . '>' . $i . '</option>';
                    }
                    echo '</select>&nbsp;<select name="hour">';
                    for ($i = 0; $i < 24; $i++) {
                        echo '<option value="' . $i . '" ' . ($i == date('G', $res['time']) ? 'selected' : null) . '>' . $i . '</option>';
                    }
                    echo '</select>&nbsp;:&nbsp;<select name="minute">';
                    for ($i = 0; $i < 60; $i++) {
                        echo '<option value="' . $i . '" ' . ($i == date('i', $res['time']) ? 'selected' : null) . '>' . $i . '</option>';
                    }
                    echo '</select><p>Koefficientlar:</p><select name="development[]">';
                    for ($i = 2; $i < 5; $i++) {
                        echo '<option value="' . $developments[0] . '">' . $developments[0] . '</option>';
                    }
					echo'</select><select name="development[]">';
					for ($i = 2; $i < 5; $i++) {
                        echo '<option value="' . $developments[1] . '">' . $developments[1] . '</option>';
                    }
					echo'</select><select name="development[]">';
					for ($i = 2; $i < 5; $i++) {
                        echo '<option value="' . $developments[2] . '">' . $developments[2] . '</option>';
                    }
					
                      
                        echo'</select><p><input type="submit" name="submit" value="Saqlash"></p>'
                        . '</form></div>';
                }
            }
            else {
                echo functions::display_error('O\'yinni o\'zgartirish vaqti o\'tib ketdi');
            }

            echo '<div class="menu"><a href="./?act=list_matches">Orqaga</a></div>';
            break;

        case 'del':
            echo '<div class="phdr"><a href="./">Futbol bashorati</a>&nbsp;|&nbsp;Matchni o\'chirish</div>';

            if (isset($_GET['yes'])) {
                $total_bets = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `bookmaker_bets` WHERE `match_id` = '$id'"), 0);
                if ($total_bets)
                    mysql_query("DELETE FROM `bookmaker_bets` WHERE `match_id` = '$id'");
                mysql_query("DELETE FROM `bookmaker_matches` WHERE `id` = '$id'");
                header('location: ./?act=list_matches');
            }
            else {
                echo '<div class="rmenu"><p>Siz rostadan ham ushbu matchni o\'chirmoqchimisiz?</p>'
                    . '<a href="?mod=del&amp;id=' . $id . '&amp;yes">Ha</a>&nbsp;|&nbsp;<a href="./?act=list_matches">Yo\'q</a>'
                    . '</div>';
            }

            echo '<div class="menu"><a href="./?act=list_matches">Orqaga</a></div>';
            break;

        case 'moderation':
            echo '<div class="phdr"><a href="./">Futbol bashorati</a>&nbsp;|&nbsp;Moderatsiya</div>';

            switch ($do) {
                case 'mod':
                    if (isset($_GET['yes'])) {
                        mysql_query("UPDATE `users` SET `balans` = `balans` + 100, `forecasts` = `forecasts` + 1 WHERE `id` = '$user'");
                        mysql_query("UPDATE `bookmaker_forecasts` SET `status` = 1 WHERE `id` = '$id'");
                        mysql_query("DELETE FROM `bookmaker_forecasts` WHERE `match_id` = " . abs($_GET['match']) . " AND `status` = '0'");
                        header('location: ./?act=list_forecasts');
                    }
                    else {
                        echo '<div class="gmenu"><p>Siz rostda ham ushbu tahminni moderatsiyadan o\'tkazmoqchimisiz? Ushbu matchga boshqa tahminlar o\'chiriladi!</p>'
                            . '<a href="?mod=moderation&amp;do=mod&amp;user=' . $user . '&amp;id=' . $id . '&amp;match=' . abs($_GET['match']) . '&amp;yes">Ha</a>&nbsp;|&nbsp;'
                            . '<a href="./?act=forec&amp;id=' . $id . '">Yo\'q</a>'
                            . '</div>';
                    }
                    break;

                case 'del':
                    if (isset($_GET['yes'])) {
                        mysql_query("DELETE FROM `bookmaker_forecasts` WHERE `id` = '$id'");
                        header('location: ./?act=list_forecasts');
                    }
                    else {
                        echo '<div class="rmenu"><p>Siz rostda ham ushbu tahminni moderatsiyasini bekorlamoqchimsiz?</p>'
                            . '<a href="?mod=moderation&amp;do=del&amp;id=' . $id . '&amp;yes">Ha</a>&nbsp;|&nbsp;'
                            . '<a href="./?act=forec&amp;id=' . $id . '">Yo\'q</a>'
                            . '</div>';
                    }
                    break;
            }

            echo '<div class="menu"><a href="./?act=forec&amp;id=' . $id . '">Назад</a></div>';
            break;

        case 'play':
            $match = mysql_fetch_assoc(mysql_query("SELECT * FROM `bookmaker_matches` WHERE `id` = '$id'"));
            echo '<div class="phdr"><a href="./">Futbol bashorati</a>&nbsp;|&nbsp;O\'yinni tugatish</div>';

            if (($match['time'] + 7200) < time()) {
                if (isset($_POST['submit'])) {
                    foreach ($_POST['score'] as $value) $array[] = abs(intval($value));
                    $score = implode('|', $array);
                    mysql_query("UPDATE `bookmaker_matches` SET `score` = '$score', `status` = 1 WHERE `id` = '$id'");

                    $total_bets = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `bookmaker_bets` WHERE `match_id` = '$id'"), 0);
                    if ($total_bets) {
                        $coefs = explode('|', $match['developments']);
                        $req = mysql_query("SELECT * FROM `bookmaker_bets` WHERE `match_id` = '$id'");
                        while ($res = mysql_fetch_assoc($req)) {
                            if ($array[0] > $array[1] && $res['bet'] == 'П1') {
                                $balans = $coefs[0] * $res['summ'];
                                $win = 1;
                            }
                            elseif ($array[0] == $array[1] && $res['bet'] == 'Х') {
                                $balans = $coefs[1] * $res['summ'];
                                $win = 1;
                            }
                            elseif ($array[0] < $array[1] && $res['bet'] == 'П2') {
                                $balans = $coefs[2] * $res['summ'];
                                $win = 1;
                            }
                            else {
                                $balans = 0; // не выиграл
                                $win = 0;
                            }
                            mysql_query("UPDATE `bookmaker_bets` SET `win` = `win` + $win WHERE `id` = " . $res['id'] . "");
                            mysql_query("UPDATE `users` SET `balans` = `balans` + $balans WHERE `id` = " . $res['user_id'] . "");
                        }
                    }
                    header('location: ./?act=list_matches');
                }
                else {
                    echo '<div class="bmenu"><p>Match:&nbsp;<b>' . functions::checkout($match['team_1']) . ' - ' . functions::checkout($match['team_2']) . '</b></p>'
                        . '<p>O\'yin vaqti:&nbsp;' . functions::display_date($match['time']) . '</p>'
                        . '</div>'
                        . '<div class="gmenu"><form action="?mod=play&amp;id=' . $id . '" method="post">'
                        . '<p>Match hisobi:&nbsp;<input type="text" name="score[]" size="2" placeholder="Team 1">&nbsp;:'
                        . '&nbsp;<input type="text" name="score[]" size="2" placeholder="Team 2"></p>'
                        . '<p><li>Hisobni etinborli kiriting, qayta kiritish mumkin emas!</li></p>'
                        . '<p><input type="submit" name="submit" value="O\'ynash"></p>'
                        . '</form></div>';
                }
            }
            else {
                echo functions::display_error('Match hali tugamadi, hisobni kirita olmaysiz!');
            }

            echo '<div class="menu"><a href="./?act=list_matches">Orqaga</a></div>';
            break;

        case 'restart':
            echo '<div class="phdr"><a href="./">Futbol bashorati</a>&nbsp;|&nbsp;Restart</div>';

            if (isset($_GET['yes'])) {
                function count_files($dir) {
                    $c = 0;
                    $d = dir($dir);
                    while ($str = $d->read()){
                        if($str{0} != '.'){
                            if(is_dir($dir.'/'.$str)) $c+=count_files($dir.'/'.$str);
                            else $c++;
                        }
                    }
                    $d->close();
                    return $c;
                }
                $count = count_files('archive/');
                $count = $count == 0 ? 1 : $count + 1;
                $total =  mysql_result(mysql_query("SELECT COUNT(`id`) FROM `users` WHERE `balans` != 0"), 0);

                if ($total) {
                    $req = mysql_query("SELECT `name`, `balans` FROM `users` WHERE `balans` != 0 ORDER BY `balans` DESC");
                    $i = 1;
                    while ($res = mysql_fetch_assoc($req)) {
                        $res['place'] = $i;
                        $a = implode(' || ', $res);
                        $a .= "\r\n";
                        $file = fopen('archive/' . $count . '.txt', 'a+');
                        fwrite($file, $a);
                        fclose($file);
                        $i++;
                    }

                    mysql_query("TRUNCATE `bookmaker_bets`");
                    mysql_query("TRUNCATE `bookmaker_forecasts`");
                    mysql_query("TRUNCATE `bookmaker_matches`");
                    mysql_query("TRUNCATE `book_comments_likes`");
                    mysql_query("TRUNCATE `book_forecasts_comments`");
                    mysql_query("TRUNCATE `book_forecast_likes`");
                    mysql_query("UPDATE `users` SET `balans` = 1000, `forecasts` = 0, `comments` = 0");
                    header('location: ./');
                }
            }
            else {
                echo '<div class="rmenu"><p>Diqqat! Bu sozlama barcha o\'yin ma\'lumotlarini o\'chiradi. TOP liderlar arxiv bo\'limga qo\'shiladi. Rozimisiz?</p>'
                    . '<a href="?mod=restart&amp;yes">Да</a>&nbsp;|&nbsp;<a href="./">Нет</a>'
                    . '</div>';
            }

            echo '<div class="menu"><a href="./">Orqaga</a></div>';
            break;
    }
}
else {
    echo functions::display_error('Xizmat yopiq!');
}

require_once '../incfiles/end.php';