@tykus
if($this->pay($id)) {
$level = BuildingUser::where('user_id', Auth::user()->id)->where('building_id',$id)->first();
$level->update(['level' => $level->level + 1]);
//$this->addResourceGain($id);
return redirect()->route('palace');
}
else {
return redirect()->back()->with('failure2', 'You do not have the required resources to upgrade this building.');
}
public function pay($id) {
$cost = Building::where('id', $id)->first(['cost_gold','cost_wood','cost_stone','cost_sand','cost_copper','cost_tin','cost_iron','cost_silver','cost_bronze','cost_steel','cost_glass','cost_mithril']);
$resources = Resource::where('user_id', Auth::user()->id)->first(['gold','wood','stone','sand','copper','tin','iron','silver','bronze','steel','glass','mithril']);
$costArray = $cost->toArray();
$level = BuildingUser::where('user_id', Auth::user()->id)->where('building_id',$id)->first();
$costNotNull = array_filter($costArray);
$resourceName = array_keys($costNotNull);
$true = 0;
//check if user can afford
foreach($resourceName as $resource) {
$resourceKey = str_replace("cost_","",$resource);
if(($resources->$resourceKey - ($cost->$resource*5*$level->level)) >= 0) {
$true++;
}
}
//deduct resources now that we know the user can afford it all
if(count($resourceName) === $true) {
foreach($resourceName as $resource) {
$resourceKey = str_replace("cost_","",$resource);
$resources->$resourceKey = $resources->$resourceKey - ($cost->$resource*5*$level->level);
$resources->save();
}
return true;
}
else {
return false;
}
}