<?php
if (isset($user_id)) {
    $days = 10;      # Количество дней
    $bonus = 10000;  # Сумма главного бонуса
    $restart = 1;    # Привязка по дням: 1 - вкл., 0 - выкл. 
    
    function restart($time, $user_id) {
        $sql = "UPDATE users SET balans_time = $time, balans_day = 0 WHERE id = $user_id";
        mysql_query($sql) or die(mysql_error());
        header('Location:'. $_SERVER['PHP_SELF']);
        exit;
    }

    $time = time();
    $lbl = array(0);
    for ($i = 1; $i <= $days; $i++) {
        $lbl[] = $time - 3600 * 24 * $i;
    }
    
    $sql = "SELECT balans_day, balans_time FROM users WHERE id = $user_id";
    $res = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_assoc($res);
    $day = (int)$row['balans_day'];
    $tm = (int)$row['balans_time'];
    !($tm == 0 || $lbl[$days] > $tm) ?: restart($time, $user_id);
    
    for ($i = 1; $i <= $days; $i++) {
        if ($tm >= $lbl[$i] && $day == 0) {
            $today = $i; 
            break;
        } elseif ($tm < $lbl[$i] && $tm >= $lbl[$i + 1] && $day <= $i) {
            $today = $i + 1;
        }
    }

    if (!empty($today)) {
        !($restart == 1 && $today - $day > 1) ?: restart($time, $user_id);
        $today == $days ? $balls = $bonus : $balls = mt_rand($today * $today, $today * $days) * 20;
        $sql = "UPDATE users SET balans = balans + $balls, balans_day = $today WHERE id = $user_id";
        mysql_query($sql) or die(mysql_error()); ?>
        <div class="kunlibonus" id="id01" style="display: block; text-align: center;">
              <div class="w3-white akbarbek"><h2>Salom  siz uchun maxsus</h2><b>Kunlik bonus!</b><br><h6>Kun 
        	<?php 
        for ($i = 1; $i <= $days; $i++) {
            if ($today == $i) {
                echo '&rarr;&nbsp;<span style="color:red"><b>'. $i .'-kun</b></span>&nbsp;';
            } else {
                echo '&rarr;&nbsp;'. ($i == $days ? "<b>$i</b>" : $i) .'&nbsp;';
            }
        }
        echo '</h6><div class="menu"><h2>Bugun sizga '. ($balls == $bonus ?'<span style="color:red"><br><b>'. $balls .'</b></span>' : $balls) .' bal berildi!</h2></div><br></div><br></div>'; 
         } 
     } ?>