<?php 

include_once $_SERVER['DOCUMENT_ROOT'].'/sys/inc/home.php';
include_once H.'sys/inc/start.php';
include_once H.'sys/inc/sess.php';
include_once H.'sys/inc/settings.php';
include_once H.'sys/inc/db_connect.php';
include_once H.'sys/inc/ipua.php';
include_once H.'sys/inc/fnc.php';
include_once H.'sys/inc/user.php';

only_reg();

require 'config.php';

$act = (isset($_GET['act']) ? $_GET['act'] : '-'); 

if ($act == 'search') {
    $tower = mysql_fetch_assoc(mysql_query("SELECT * FROM tower WHERE userId != '" . $user['id'] . "' AND height > '9' ORDER BY rand() LIMIT 1"));
    if (empty($tower)) {
        $tower_notification_html = '<h3>Oppenent Not Found!</h3>';
        $tower_notification_html .= '<h1>:(</h1>';
        $_SESSION['TOWER_NOTIFICATION'] = $tower_notification_html;
    }
    header('Location: ?uid=' . (!empty($tower) ? $tower['userId'] : $user['id']));
    exit;
}

$uid = (isset($_GET['uid']) ? (int) $_GET['uid'] : $user['id']); 
$tower = mysql_fetch_assoc(mysql_query("SELECT * FROM tower WHERE userId = " . $uid));

if (empty($tower)) {
    if ($uid == $user['id'] && mysql_result(mysql_query("SELECT COUNT(*) FROM tower WHERE userId = " . $uid), 0) == 0) {
        mysql_query("INSERT INTO `tower`(`userId`, `color`) VALUES ('" . $user['id'] . "', '" . mt_rand(1, 4) . "')");
        $tower = mysql_fetch_assoc(mysql_query("SELECT * FROM tower WHERE userId = " . $uid));
    }
    
    else {
        $tower = array(
            'userId' => $uid, 
            'height' => 0, 
            'step' => 0, 
            'color' => 1, 
            'lastfreebox' => time(), 
        ); 
    }
}

if ($uid != $user['id']) {
    $userTower = mysql_fetch_assoc(mysql_query("SELECT * FROM tower WHERE userId = '" . $user['id'] . "' LIMIT 1"));
}

else {
    $userTower = $tower; 
}

// Цена за восстановление башни
$TOWER_LOS_PRICE = ($tower['los'] ? $_TOWER_HEIGHT_COST[array_search($tower['los'], $_TOWER_HEIGHT_LOSE)] : 0); 

$shield = $TOWER_TIME_SHIED_FULL - (time() - $tower['heartTime']); 

if ($shield <= 0 && $tower['heart'] > 0 && $tower['height'] >= 10) {
    $percent = abs(floor($shield / 60));
    $result = $tower['heart'] - ($percent * 10); 
    $shield = abs($shield); 
    
    for($i = 1; $i <= ($percent < 10 ? $percent : 10); $i++) {
        $tower['heartTime'] += $TOWER_TIME_SHIED; 
        
        if ($shield > 0) {
            break; 
        }
    }
    
    $shield = $TOWER_TIME_SHIED_FULL - (time() - $tower['heartTime']); 
    $tower['heart'] = ($result <= 0 ? 0 : $result);
    
    if ($tower['heart'] <= 0) {
        $tower['heartTime'] = 0;
    }
    
    mysql_query("UPDATE tower SET heartTime = '" . $tower['heartTime'] . "', heart = '" . $tower['heart'] . "' 
                  WHERE userId = '" . $uid . "' LIMIT 1");
}

$box_is = ($tower['lastfreebox'] > (time() - $TOWER_FREE_TIME) ? false : true);

if (!empty($act)) {
    if ($act == 'box') {
        $lastfreebox = time(); 
        if (!$box_is) {
            if ($user[$TOWER_PRICE_TABLE] >= $TOWER_PRICE) {
                mysql_query("UPDATE user SET `" . $TOWER_PRICE_TABLE . "` = `" . $TOWER_PRICE_TABLE . "` - '" . $TOWER_PRICE . "' WHERE id = '" . $user['id'] . "' LIMIT 1");
                $box_is = true;
                $lastfreebox = $tower['lastfreebox'];
            }
        }
        
        if ($box_is) {
            $box = getTowerBox(); 
            $tower_notification_html = '<div class="tower-modal-title" style="padding: 20px 10px 10px 10px;">Bilder box you found</div>';
            
            if ($box['type'] == 1) {
                foreach($box['item'] AS $key) {
                    $tower_notification_html .= '<div><img src="components/img/blocks/' . $key . '.png" /></div>';
                    mysql_query("INSERT INTO `tower_blocks`(`uid`, `userId`, `colorTop`, `colorBottom`) 
                                  VALUES ('" . $key . "', '" . $user['id'] . "', '" . $TOWER_BLOCKS[$key][0] . "', '" . $TOWER_BLOCKS[$key][1] . "')");
                }
                
                $_SESSION['TOWER_NOTIFICATION_CLASS'] = 'towerBlocks';
                mysql_query("UPDATE tower SET lastfreebox = '" . $lastfreebox . "' 
                               WHERE userId = '" . $user['id'] . "' LIMIT 1");
            }
            
            else {
                $_SESSION['TOWER_NOTIFICATION_CLASS'] = 'towerBomb';
                $tower_notification_html .= '<div class="tower-box"><img src="components/img/bomb.png" /></div>';
                mysql_query("UPDATE tower SET bomb = bomb + '" . $box['item'] . "', lastfreebox = '" . $lastfreebox . "' 
                               WHERE userId = '" . $user['id'] . "' LIMIT 1");
            }
            $tower_notification_html .= '<div class="tower-modal-title" style="font-size: small; padding: 10px;">You can open the box at any time.!<br />Cost of ' . des2num($TOWER_PRICE, $TOWER_COINS_NAME) . '!</div>';
            
            $_SESSION['TOWER_NOTIFICATION'] = $tower_notification_html; 
        }
        
        header('Location: ?');
        exit; 
    }
    
    elseif ($act == 'build') {
        $key = (isset($_GET['key']) ? (int) $_GET['key'] : 0); 
        $block = mysql_fetch_assoc(mysql_query("SELECT * FROM tower_blocks WHERE uid = '" . $key . "' AND userId = " . $user['id']));
        
        if (!empty($block) && $block['colorBottom'] == $tower['color']) {
            if ($tower['step'] == 2) {
                $tower['height'] += 1; 
                $tower['step'] = 0; 
                
                if ($tower['heart'] == 100 || $tower['height'] <= 10) {
                    if ($TOWER_USER_RATING) {
                        mysql_query("UPDATE user SET `".$TOWER_USER_RATING_TABLE."` = `".$TOWER_USER_RATING_TABLE."` + '".$TOWER_USER_RATING_COUNT."' WHERE id = '" . $user['id'] . "' LIMIT 1");
                    }                    
                }
                
            } else {
                $tower['step'] += 1;
            }
        
            if ($tower['heart'] != 100 && $tower['height'] >= 10) {
                $tower['heartTime'] = time();
                $tower['heart'] = 100;
            }
            
            mysql_query("UPDATE tower SET step = '" . $tower['step'] . "', height = '" . $tower['height'] . "', heartTime = '" .  $tower['heartTime'] . "', heart = '" . $tower['heart'] . "', color = '" . $block['colorTop'] . "'
                           WHERE userId = '" . $tower['userId'] . "' LIMIT 1");
            mysql_query("DELETE FROM tower_blocks WHERE userId = '" . $user['id'] . "' AND uid = '" . $key . "' LIMIT 1");
        }
        
        header('Location: ?');
        exit; 
    }
    
    if ($act == 'los' && $user['id'] == $uid && $user[$TOWER_PRICE_TABLE] >= $TOWER_LOS_PRICE) {
        if ($TOWER_USER_RATING) {
            $tower['height'] += $tower['los'];
            mysql_query("UPDATE user SET `".$TOWER_USER_RATING_TABLE."` = `".$TOWER_USER_RATING_TABLE."` + '" . ($TOWER_USER_RATING_COUNT * $tower['los']) . "', `" . $TOWER_PRICE_TABLE . "` = `" . $TOWER_PRICE_TABLE . "` - '" . $TOWER_LOS_PRICE . "' WHERE id = '" . $tower['userId'] . "' LIMIT 1");
            $tower['los'] = 0;
            mysql_query("UPDATE tower SET height = '" . $tower['height'] . "', heartTime = '" .  time() . "', heart = '100' , los = '0' WHERE userId = '" . $tower['userId'] . "' LIMIT 1");
            
        }     
        header('Location: ?uid=' . $uid); 
        exit; 
    }
}

if ($act == 'fire' && $tower['userId'] != $user['id'] && $tower['height'] >= 10) {
    $fire = ($tower['heart'] == 0 ? 100 : mt_rand(1, 10) * 10); 
    $tower_notification_html = '';
    
    if ($fire >= $tower['heart']) {
        foreach($_TOWER_HEIGHT_LOSE AS $key => $value) {
            $tower_height = $value; 
            $tower['los'] = $value;
            $user_rating = $value; 
            
            if (!empty($_TOWER_HEIGHT_LOSE[$key+1]) && $_TOWER_HEIGHT_LOSE[$key+1] > $tower['height']) {
                break;
            } 
        }
        
        if (!empty($TOWER_GIFT)) {
            $win =  array_rand($TOWER_GIFT, 1); 
            
            if (is_file('components/gift/' . $win . '.php')) {
                require('components/gift/' . $win . '.php');
            }
        }
        
        $tower['height'] -= $tower_height; 
        $tower['notifyId'] = 1; 
        $tower['heartTime'] = time(); 
        $tower['heart'] = 90; 
        
        $tower_notification_html .= '<h3>YOU DESTROYED THE TOWER!</h3>';
        $tower_notification_html .= '<div><img src="components/img/win@2x.png" /></div>';
        $tower_notification_html .= '<h3>DAMAGE ' . des2num($tower['los'], array('METER', 'METER', 'METER')) . '</h3>';
        if (!empty($win)) {
            $tower_notification_html .= '<div class="tower-modal-title" style="font-weight: normal; padding: 10px;">Your prize:</div>';
            $tower_notification_html .= '<div><img src="' . $TOWER_GIFT[$win]['img_big'] . '" /></div>';
            $tower_notification_html .= '<div class="tower-modal-title" style="padding: 10px;">' . $TOWER_GIFT[$win]['name'] . '</div>';
        }
        $_SESSION['TOWER_NOTIFICATION_CLASS'] = 'towerWin';
    }
    
    else {
        $tower_notification_html .= '<h3>TOWER DECLINED!</h3>';
        $tower_notification_html .= '<div><img src="components/img/shield@2x.png" /></div>';
        $tower_notification_html .= '<div class="tower-modal-title" style="font-weight: normal; padding: 10px;">Try Once More!</div>';
        $_SESSION['TOWER_NOTIFICATION_CLASS'] = 'towerLose';
    }
    
    if ($TOWER_USER_RATING) {
        mysql_query("UPDATE user SET `".$TOWER_USER_RATING_TABLE."` = `".$TOWER_USER_RATING_TABLE."` - '" . ($TOWER_USER_RATING_COUNT * $user_rating) . "' 
                        WHERE id = '" . $tower['userId'] . "' LIMIT 1");
    }      
    
    mysql_query("UPDATE tower SET height = '" . $tower['height'] . "', 
                                  los = '" .  $tower['los'] . "', 
                                  notifyId = '" .  $tower['notifyId'] . "', 
                                  heartTime = '" .  $tower['heartTime'] . "', 
                                  heart = '" .  $tower['heart'] . "' WHERE userId = '" . $tower['userId'] . "' LIMIT 1");
    
    mysql_query("UPDATE tower SET bomb = bomb - '1' WHERE userId = '" . $user['id'] . "' LIMIT 1");
    
    $_SESSION['TOWER_NOTIFICATION'] = $tower_notification_html;
    header('Location: ?uid=' . $uid); 
    exit;
}

if ($tower['height'] > 17) {
    $level = 9; 
} elseif ($tower['height'] >= 16) {
    $level = 8; 
} elseif ($tower['height'] >= 15) {
    $level = 7; 
} elseif ($tower['height'] >= 14) {
    $level = 6; 
} elseif ($tower['height'] >= 13) {
    $level = 5; 
} elseif ($tower['height'] >= 12) {
    $level = 4; 
} elseif ($tower['height'] >= 11) {
    $level = 3; 
} elseif ($tower['height'] >= 10) {
    $level = 2; 
} else {
    $level = 1;
}

if ($tower['height'] > 10000) {
    $level = 9; 
} elseif ($tower['height'] >= 5000) {
    $level = 8; 
} elseif ($tower['height'] >= 1000) {
    $level = 7; 
} elseif ($tower['height'] >= 500) {
    $level = 6; 
} elseif ($tower['height'] >= 250) {
    $level = 5; 
} elseif ($tower['height'] >= 100) {
    $level = 4; 
} elseif ($tower['height'] >= 30) {
    $level = 3; 
} elseif ($tower['height'] >= 10) {
    $level = 2; 
} else {
    $level = 1;
}

if ($level > 6) {
    $top = 3; 
} elseif ($level > 2) {
    $top = 2; 
} else {
    $top = 1;
}

if ($level >= 5) {
    $topAction = 3; 
} elseif ($level >= 3) {
    $topAction = 2; 
} else {
    $topAction = 1;
}

$height_end = (int) substr($tower['height'], -1); 
if ($height_end > 9) {
    $height_end -= 9; 
}

elseif ($height_end == 0) {
    $height_end = 1;
}

$count = array(); 

if ($user['id'] == $uid) {
    $count['blocks'] = mysql_result(mysql_query("SELECT COUNT(*) FROM tower_blocks WHERE userId = " . $user['id']), 0); 
}

if ($user['id'] == $tower['userId'] && $tower['notifyId'] == 1) {
    $tower_notification_html .= '<h3>YOUR TOWER DESTROYED!</h3>';
    $tower_notification_html .= '<div><img src="components/img/lose@2x.png" /></div>';
    $tower_notification_html .= '<h3>DAMAGE ' . des2num($tower['los'], array('METER', 'METER', 'METERS')) . '</h3>';
    $tower_notification_html .= '<div class="tower-modal-title" style="font-weight: normal; padding: 10px;">Consolation prizes:</div>';
    
    $box = getTowerBox(); 
    
    if ($box['type'] == 1) {
        foreach($box['item'] AS $key) {
            $tower_notification_html .= '<img style="width: 30%;" src="components/img/blocks/' . $key . '.png" />';
            
            mysql_query("INSERT INTO `tower_blocks`(`uid`, `userId`, `colorTop`, `colorBottom`) 
                          VALUES ('" . $key . "', '" . $user['id'] . "', '" . $TOWER_BLOCKS[$key][0] . "', '" . $TOWER_BLOCKS[$key][1] . "')");
                          
        }
    }
    
    else {
        $tower['bomb'] += 1;
        $tower_notification_html .= '<div class="tower-box"><img src="components/img/bomb.png" /></div>';
    }
    
    mysql_query("UPDATE tower SET notifyId = '0', bomb = '" . $tower['bomb'] . "' WHERE userId = '" . $user['id'] . "' LIMIT 1");
    
    $TOWER_NOTIFICATION = $tower_notification_html;
    $TOWER_NOTIFICATION_CLASS = 'towerLose';
}

$set['title'] = 'Tower ' . ($user['id'] != $uid ? user::nick($uid, 0, 0, 0) : '');

include_once H.'sys/inc/thead.php';
title();
aut();
err(); 

echo '<link rel="stylesheet" href="components/css/style.css?' . filemtime('components/css/style.css') . '" type="text/css" />';

if ($act == 'rating') {
    require('components/includes/view.top.php');
}

else {
    require('components/includes/view.tower.php');
}

include_once H.'sys/inc/tfoot.php';
