<?php

Class Compaign {

	function __construct($db){
		$this->db = $db;
	}


	function SetStart($setting){
		$id =$setting['compaign']; 
		$camp = $this->db->fetch('SELECT * FROM `compaigns` WHERE `id`=?',array($id));

		if($camp['status'] == 0 AND time() >= $camp['time_start']){
			//Расчет времени похода 
			$t = time();
			$start_time = 600;
			//Учитиваем количество игроков
			$players = $this->db->rows('SELECT * FROM `users` WHERE `compaign` = ?',array($id));
			$p = round($players/$camp['max_users']*100);
			$time = (($start_time/100) * (100 - $p));
			$time = $start_time + $time;

			// + к времени от сложности
			$time = round($time * (rand(($camp['power']-1)*100,$camp['power']*100)/100));
			$time = time()+$time;

			$this->db->query('UPDATE `compaigns` SET `time`=? , `status`= ?  WHERE `id` = ? LIMIT 1',array($time,1,$id));


		}

	}


	function save($setting){
		$t = time();
		$id =$setting['compaign']; 
		$camp = $this->db->fetch('SELECT * FROM `compaigns` WHERE `id`=?',array($id));
		$fond = array();
		$pl = $this->db->rows('SELECT * FROM `users` WHERE `compaign` = ?',array($id));
			$fond['gold'] = 100*$camp['power'];
			$fond['silver'] = 1000*$camp['power'];
			$power = 2000*$camp['power']+(100 * rand(1,$camp['max_users'])*$pl);
			if($camp['time'] <= $t AND $camp['status'] == 1 ){
				$players = $this->db->fetchAll('SELECT * FROM `users` WHERE `compaign` = ?',array($id));
				foreach ($players as $p) {
					$s = $p['def'] + $p['str'] + $p['max_hp'];
					$proc = ($s/$power*100);
					if($p['vip'] == 'yes'){
						$proc = $proc *2;
					}

					$gold = $p['gold'] + round($fond['gold']/100*$proc);
					$silver =$p['silver'] + round($fond['silver']/100*$proc);
					$exp =$p['exp'] + round($proc*$camp['power']);

					$this->db->query('UPDATE `users` SET `gold`=?, `silver`=?, `exp`=?, `compaign`=?, WHERE `id`=? LIMIT 1',array($gold,$silver,$exp,0,$p['id']));
				}

			$this->db->query('UPDATE `compaigns` SET `status`=? WHERE `id`=? LIMIT 1',array(2,$camp['id']));
			$this->db->query('UPDATE `setting` SET `compaign`=? WHERE `id`=? LIMIT 1', array(0,1));



			}

	}
}