@extends('layouts.default')

@section('title')
	@parent
	Бюджет для "{{ $workProject->name }}"
@stop

@section('breadcrumbs')
	{{ Breadcrumbs::render('budget', $workProject) }}
@stop

@section('js')
	<script src="{{ asset('js/plugin/x-editable/x-editable.min.js') }}"></script>
	<script src="{{ asset('js/kmk-support.js') }}"></script>
	<script src="{{ asset('js/deb-operation.js') }}"></script>
	<script>
		function reload () {
			var params = kmkGiveGetParams(location.search);
			params['endDate'] = $('#endDate').val();
			kmkSetBrowserAddressParams(kmkObjectToGetString(params, false));
			location.reload();
		}

		$(document).ready(function() {
			$('.editable').editable({
				url: '/budget/update',
				emptytext: 0
			}).on('hidden', function(e, reason) {
				if(reason === 'save') {
					$(this).html(humanizeNumber($(this).html()));
				}
			});

			$('.editable').on('save', function(e, params) {
				if (params.response.status == 'success') {
					$('#planAmountAll').html(humanizeNumber(params.response.planAmountAll));
					$('#profit').html(humanizeNumber(params.response.profit));
				}
			});

			$('.month-plan').editable({ // бюджет проекта на месяц
				url: '/budget/updatemonth',
				emptytext: 0
			}).on('hidden', function(e, reason) {
				if(reason === 'save') {
					var newMonthPlan = $(this).html(),
						  groupPercentSumTotal = 0,
			        groupSumRestTotal = 0;
					$(this).data('value', newMonthPlan);
					$(this).html(humanizeNumber(newMonthPlan));
					$('body').find('.groupPercentSum').each(function() { //пересчет полей при изменении суммы бюджета на месяц
					  var current = $(this),
					      groupMonthPlan = current.closest('tr').find('.group-month-plan').html(), // бюджет группы в процентах
							  groupFactSum = current.closest('tr').find('.groupFactSum').data('value'); // сумма расходов группы
						groupMonthPlan = groupMonthPlan.split(',').join('.');
						var groupPercentSum = Math.round(newMonthPlan*groupMonthPlan)/100; // бюджет группы в руб.
            current.data('value', groupPercentSum).html(humanizeNumber(groupPercentSum)); // поле бюджет в руб.
					  current.closest('tr').find('.groupSumRest').html(humanizeNumber( (Math.round(groupPercentSum*100 - groupFactSum*100))/100 )).data('value', (Math.round(groupPercentSum*100 - groupFactSum*100))/100 );// поле остаток
						groupPercentSumTotal += groupPercentSum;
          });
				  $('body').find('#groupPercentSumTotal').attr('title', 'Нераспределенный бюджет: '+ (Math.round(+newMonthPlan*100 - groupPercentSumTotal*100))/100 +' руб.').html(humanizeNumber((Math.round(groupPercentSumTotal*100))/100));
				  $('body').find('.groupSumRest').each(function() {//пересчет неиспользованного остатка бюджета проекта
						if($(this).data('value') > 0){
						  groupSumRestTotal += $(this).data('value');
						}
          });
					$('.planAmountRest').html(humanizeNumber((Math.round(groupSumRestTotal*100))/100));
	      }
			});

      $('.group-month-plan').editable({ //бюджет группы
				url: '/budget/updatepercent/'+$('#endDate').val(),
				emptytext: 0
			}).on('hidden', function(e, reason) {
				if(reason === 'save') {
					$(this).html($(this).html());
					$(this).data('value', $(this).html());
				}
			});

			$('.group-month-plan').on('save', function(e, params) {
				if (params.response.status == 'success') {
					var currentRow = $(this).closest('tr'),
					    groupPercentSumTotal = 0,
							groupSumRestTotal = 0,
							monthPlan = $('.month-plan').data('value');
				  currentRow.find('.groupPercentSum').data('value', params.response.groupPercentSum).html(humanizeNumber(params.response.groupPercentSum));
				  currentRow.find('.groupSumRest').html(humanizeNumber(params.response.groupSumRest));
					currentRow.find('.groupSumRest').data('value', params.response.groupSumRest);
					$('#groupPercentTotal').attr('title', 'Нераспределенный бюджет: '+ (Math.round(100*100 - params.response.groupPercentTotal*100))/100 +'%').html(params.response.groupPercentTotal);
					$('body').find('.groupPercentSum').each(function() {//пересчет общей распланированной суммы при изменении % групп
						groupPercentSumTotal += $(this).data('value');
          });
				$('#groupPercentSumTotal').attr('title', 'Нераспределенный бюджет: '+ (Math.round(monthPlan*100 - groupPercentSumTotal*100))/100 +' руб.').html(humanizeNumber((Math.round(groupPercentSumTotal*100))/100));
				}
				$('body').find('.groupSumRest').each(function() {//пересчет неиспользованного остатка бюджета проекта
					if($(this).data('value') > 0){
						groupSumRestTotal += $(this).data('value');
					}
          });
				$('.planAmountRest').html(humanizeNumber((Math.round(groupSumRestTotal*100))/100));
				var curr = $('#groupPercentTotal'),
				    groupPercentTotal = curr.html();
			  if (groupPercentTotal > 100) {
				  curr.removeClass('text-success').addClass('text-danger');
			  } else if (groupPercentTotal < 100) {
				  curr.removeClass('text-danger').addClass('text-success');
			  } else {
					curr.removeClass('text-success').removeClass('text-danger');
				}
			});

				var curr = $('#groupPercentTotal'),
				    groupPercentTotal = curr.html();
			  if (groupPercentTotal > 100) {
				  curr.addClass('text-danger');
			  } else if (groupPercentTotal < 100) {
				  curr.addClass('text-success');
			  }

			$('a.to-humanize').each(function() {
				$(this).html(humanizeNumber($(this).html()));
			});

			var endDate = $('#endDate')
				.datepicker({
					onClose: function( selectedDate ) {
						reload();
					}
				});

			var today = new Date();
			$("#todayDate").data('date', today.getDate()+'.'+(parseInt(today.getMonth())+1)+'.'+today.getFullYear());
			today.setDate(today.getDate()-1);
			$("#yeasterdayDate").data('date', today.getDate()+'.'+(parseInt(today.getMonth())+1)+'.'+today.getFullYear());

			$('.btn-set-date').unbind('click').on('click', function(){
				$('#startDate').val($(this).data('date'));
				$('#endDate').val($(this).data('date'));
				reload();
				return false;
			});
			// --> сворачивание групп в таблице Информация по расходам
			var minusSign = '<em class="fa fa-minus-circle"></em>',
			    plusSign = '<em class="fa fa-plus-circle"></em>';

		  $.fn.slideFadeToggle = function(speed, easing, callback){
        return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
      };

      $('body').on('click', '.group-header', function(){
				var raw = $(this).closest('.group-header-raw');
		    raw.nextUntil('.group-header-raw').slideFadeToggle('fast');

				if( raw.hasClass('open-header') ){
					raw.removeClass('open-header').addClass('close-header');
					$(this).find('.collapse-sign-my').html(plusSign);
				}else{
					raw.removeClass('close-header').addClass('open-header');
					$(this).find('.collapse-sign-my').html(minusSign);
				}
		    return false;
      });

			$('.collapse-sign-all').click(function(){
				var current = $(this);
				if( current.hasClass('open-group') ){
					current.html('<em class="fa fa-plus-circle" title="Развернуть детали групп"></em>');
					current.removeClass('open-group').addClass('close-group');

					$('.open-header').each(function(){
					  $(this).find('.group-header').click();
				  });
				}else{
					current.html('<em class="fa fa-minus-circle" title="Свернуть детали групп"></em>');
					current.removeClass('close-group').addClass('open-group');

					$('.close-header').each(function(){
					  $(this).find('.group-header').click();
				  });
				}
			});
			// <--
	  });
	</script>
@stop

@section('content')
	<div class="row">
		<div class="col-md-12">
			<div class="panel panel-default">
				@include('budget/menu')
				<div class="panel-body">
					<form class="form-inline" role="form">
						<div class="form-group">
							Состояние на <input id="endDate" name="endDate" class="form-control input-sm" value="{{ $endDate }}"/>
						</div>
						<div class="form-group">
							<button id="yeasterdayDate" class="btn btn-default btn-set-date" data-date="">Вчера</button>
							<button id="todayDate" class="btn btn-default btn-set-date">Сегодня</button>
						</div>
					</form>
					<br/>
					<div class="row">
						<div class="col-md-6">
							<div class="well well-sm">
								<div class="table-responsive">
									<table class="table table-condensed">
										<thead>
											<tr>
												<th>Информация по счетам</th>
												<th></th>
											</tr>
										</thead>
										<tbody>
											@foreach ($workProject->budgetAccounts as $budgetAccount)
											<tr>
												<td>{{ $budgetAccount->name }}</td>
												<td class="text-right"><span class="to-humanize">{{ $budgetAccount->getSum($endDate) }}</span> <i class="fa fa-rub"></i></td>
											</tr>
											@endforeach
											<tr>
												<td><b>Всего</b></td>
												<td class="text-right"><b><span class="to-humanize">{{ $workProject->getSum($endDate) }}</span> <i class="fa fa-rub"></i></b></td>
											</tr>
											@if (User::find(Auth::user()->id)->hasRole(Role::ROLE_BUDGET))
											<tr>
												<td><b>Остаток после полной оплаты<br/>всех планируемых расходов</b></td>
												<td class="text-right"><b><span id="profit" class="to-humanize">{{ $workProject->getProfit() }}</span> <i class="fa fa-rub"></i></b></td>
											</tr>
											<tr>
												<td><b>Остаток после полной оплаты<br/>всех планируемых расходов<br/>и возврата/получения всех долгов</b></td>
												<td class="text-right"><b><span id="profit" class="to-humanize">{{ $workProject->getProfitAll() }}</span> <i class="fa fa-rub"></i></b></td>
											</tr>
											@endif
										</tbody>
									</table>
								</div>
								<div class="table-responsive">
									<table class="table table-condensed">
										<thead>
											<tr>
												<th>Cчет</th>
												<th class="text-right">Приход</th>
												<th class="text-right">Расход</th>
											</tr>
										</thead>
										<tbody>
											@foreach ($workProject->budgetAccounts as $budgetAccount)
											<tr>
												<td>{{ $budgetAccount->name }}</td>
												<td class="text-right" style="white-space:nowrap"><span class="to-humanize">{{ $budgetAccount->getInSum($endDate) }}</span> <i class="fa fa-rub"></i></td>
												<td class="text-right" style="white-space:nowrap"><span class="to-humanize">{{ $budgetAccount->getOutSum($endDate) }}</span> <i class="fa fa-rub"></i></td>
											</tr>
											@endforeach
											<tr>
												<td><b>Итого</b></td>
												<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize">{{ $workProject->getInSum($endDate) }}</span> <i class="fa fa-rub"></i></b></td>
												<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize">{{ $workProject->getOutSum($endDate) }}</span> <i class="fa fa-rub"></i></b></td>
											</tr>
											<tr>
												<td><b>Прибыль</b></td>
												<td colspan="2" class="text-right" style="white-space:nowrap"><b><span class="to-humanize">{{ round( ($workProject->getInSum($endDate) - $workProject->getOutSum($endDate)), 2 ) }}</span> <i class="fa fa-rub"></i></b></td>
											</tr>
										</tbody>
									</table>
								</div>
							</div>
						</div>
						<div class="col-md-6">
							<div class="well well-sm">
								<div class="table-responsive">
									<table class="table table-condensed">
										<thead>
											<tr>
												<th>Информация по долговым контрагентам</th>
												<th>Долг нам</th>
												<th>Долг ему</th>
											</tr>
										</thead>
										<tbody>
											@foreach ($workProject->budgetDebtPartners as $debtPartner)
											<tr>
												<td><a href="#" class="debt-partners" data-action="{{ action('BudgetController@showDebtPartnersOperations', array($workProject->id, '', '', '') ) }}" data-project-id="{{ $workProject->id }}" data-partner-id="{{ $debtPartner->id }}">{{ $debtPartner->name? $debtPartner->name : $debtPartner->deb_project['name'] }}</a></td>
												<?php
													$debt = $debtPartner->getSum($endDate);
												?>
												<td class="text-right" style="white-space:nowrap">@if($debt > 0) <span class="to-humanize">{{ round($debt, 2) }}</span> <i class="fa fa-rub"></i> @else 0 @endif</td>
												<td class="text-right" style="white-space:nowrap">@if($debt < 0) <span class="to-humanize">{{ round(abs($debt), 2) }}</span> <i class="fa fa-rub"></i> @else 0 @endif</td>
											</tr>
											@endforeach
											<tr>
												<td><b>Всего</b></td>
												<?php
													$debt = $workProject->getDebtSum($endDate);
												?>
												<td class="text-right" style="white-space:nowrap">@if($debt > 0) <span class="to-humanize">{{ round($debt, 2) }}</span> <i class="fa fa-rub"></i> @else 0 @endif</td>
												<td class="text-right" style="white-space:nowrap">@if($debt < 0) <span class="to-humanize">{{ round(abs($debt), 2) }}</span> <i class="fa fa-rub"></i> @else 0 @endif</td>
											</tr>
										</tbody>
									</table>
								</div>
							</div>
						</div>
					</div>
					<div class="row">
						@if (User::find(Auth::user()->id)->hasAnyRole(array(Role::ROLE_BUDGET_VIEW_OPERATIONS, Role::ROLE_BUDGET)))
			      <?php
						  $budgetCostsGroups = BudgetCostGroup::whereIn('project_id', array($workProject->id, 0))
							                                    ->orderBy('name')
																                  ->get();
						  $groupPercentTotal = 0; // сумма процентов всех групп
							$groupPercentSumTotal = 0; // сумма бюджетов групп
							$noDebtNoPlanGroups = ''; // часть таблицы с группами без плана и расходов
							$noDebtOrNoPlanGroups = ''; // часть таблицы с группами c планом и без расходов (+ есть расход, нет плана)
					  ?>
						<div class="col-md-12 col-lg-12">
							<div class="well well-sm">
								<p class="text-center"><b>Информация по расходам за {{ $workProject->getMonthName() }}</b></p>
								<div class="table-responsive">
									<table class="table table-condensed table-hover">
										<thead>
											<tr>
												<th>
													<button class="btn-info collapse-sign-all close-group">
														<em class="fa fa-plus-circle" title="Развернуть детали групп"></em>
													</button>
													Группы расходов</th>
												<th class="text-right col-md-6">План, %</th>
												<th class="text-right">План, <i class="fa fa-rub"></i></th>
												<th class="text-right">Факт</th>
												<th class="text-right">Остаток</th>
											</tr>
										</thead>
										<tbody>
										@foreach ($budgetCostsGroups as $budgetCostsGroup)
										  <?php
											  $groupFactSum        = $budgetCostsGroup->getGroupSum($workProject->id, $endDate);
											  $groupFactSumOutcome = $budgetCostsGroup->getGroupSumOutcome($workProject->id, $endDate);
												$groupPercent = $budgetCostsGroup->getGroupPercent($workProject->id);
												$groupPercentAmount = round($groupPercent['amount'] / 100, 2); // бюджет группы в процентах
												$groupPercentId = $groupPercent['id'];
												$groupPercentSum = round($workProject->getCurrentBudgetMonthPlan()*$groupPercentAmount / 100, 2); // бюджет группы в руб.
												$groupPercentTotal += $groupPercentAmount; // сумма процентов всех групп
												$groupPercentSumTotal += $groupPercentSum;
											?>
										  @if($groupFactSum && $groupPercentAmount)
											  <?php $noDebtCosts = ''; // часть группы без расходов	?>
											  <tr class="group-header-raw close-header">
												  <td class="group-header">
														<b class="collapse-sign-my">
															<em class="fa fa-plus-circle"></em>
														</b>
													  <b>
													  	<a href="#">{{ $budgetCostsGroup->name }}</a>
													  </b>
												  </td>
												  <td class="text-right col-md-6" style="white-space:nowrap"><b><a href="#" class="group-month-plan" data-name="{{ $workProject->id }}_{{ $budgetCostsGroup->id }}" data-type="text" data-pk="{{ $groupPercentId }}" data-value="{{ $groupPercentAmount }}">{{ ($groupPercentAmount)? round($groupPercentAmount, 2):0 }} </a></b></td>
													<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupPercentSum" data-value="{{ ($groupPercentSum)? $groupPercentSum:0 }}">{{ ($groupPercentSum)? round($groupPercentSum, 2):0 }}</span> <i class="fa fa-rub"></i></b></td>
												  <td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupFactSumOutcome" data-value="{{ $groupFactSumOutcome }}">{{ round($groupFactSumOutcome, 2) }}</span> <i class="fa fa-rub"></i></b>
												    <b class="text-td-small"><span class="to-humanize groupFactSum" data-value="{{ $groupFactSum }}">{{ round($groupFactSum, 2) }}</span> <i class="fa fa-rub"></i></b>
													</td>
											  	<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupSumRestOutcome" data-value="{{ round($groupPercentSum-$groupFactSumOutcome, 2) }}">{{ round($groupPercentSum-$groupFactSumOutcome, 2) }}</span> <i class="fa fa-rub"></i></b>
										        <b class="text-td-small"><span class="to-humanize groupSumRest" data-value="{{ round($groupPercentSum-$groupFactSum, 2) }}">{{ round($groupPercentSum-$groupFactSum, 2) }}</span> <i class="fa fa-rub"></i></b>
													</td>
											  </tr>
												<?php
												  $budgetCostsGroup->budgetCosts = $budgetCostsGroup->budgetCosts->sortBy(function ($budgetCost) {
                            return $budgetCost->name;
                          });
												?>
											  @foreach ($budgetCostsGroup->budgetCosts as $budgetCost)
											  <?php
												  $costSum        = $budgetCost->getSum($workProject->id, $endDate);
												  $costSumOutcome = $budgetCost->getSumOutcome($workProject->id, $endDate);
												?>
												  @if($costSum)
													  <tr style="display: none;">
														  <td><span class="table-list-child">{{ str_replace($budgetCostsGroup->name . '. ', '', $budgetCost->name) }}</span></td>
														  <td></td>
														  <td></td>
														  <td class="text-right" style="white-space:nowrap"><span class="to-humanize">{{ $costSumOutcome }}</span> <i class="fa fa-rub"></i>
														    <span class="text-right text-td-small" style="white-space:nowrap"><span class="to-humanize">{{ $costSum }}</span> <i class="fa fa-rub"></i></span>
															</td>
														  <td></td>
														  <td></td>
													  </tr>
													@endif
													@if(!$costSum)
													  <?php
													  $noDebtCosts .=
														  '<tr style="display: none;">
														    <td><span class="table-list-child">'. str_replace($budgetCostsGroup->name . '. ', '', $budgetCost->name).'</span></td>
														    <td></td>
														    <td></td>
														    <td class="text-right" style="white-space:nowrap"><span class="to-humanize">'. $costSumOutcome .'</span> <i class="fa fa-rub"></i>
																  <span class="text-right text-td-small" style="white-space:nowrap"><span class="to-humanize">'. $costSum .'</span> <i class="fa fa-rub"></i></span>
																</td>
														    <td></td>
														    <td></td>
													    </tr>';
													  ?>
													@endif
											  @endforeach
												{{ $noDebtCosts }}
											@endif
											@if( (!$groupFactSum && $groupPercentAmount) || ($groupFactSum && !$groupPercentAmount))
											  <?php
												  $noDebtCosts = ''; // часть группы без расходов
													$noDebtOrNoPlanGroups .=
											  '<tr class="group-header-raw close-header">
												  <td class="group-header">
														<b class="collapse-sign-my">
															<em class="fa fa-plus-circle"></em>
														</b>

													  	<a href="#">'. $budgetCostsGroup->name .'</a>

												  </td>
												  <td class="text-right col-md-6" style="white-space:nowrap"><b><a href="#" class="group-month-plan" data-name="'. $workProject->id .'_'. $budgetCostsGroup->id .'" data-type="text" data-pk="'. $groupPercentId .'" data-value="'. $groupPercentAmount .'">'. round($groupPercentAmount, 2) .' </a></b></td>
													<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupPercentSum" data-value="'.$groupPercentSum.'">'. $groupPercentSum .'</span> <i class="fa fa-rub"></i></b></td>
												  <td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupFactSumOutcome" data-value="'. $groupFactSumOutcome .'">'. round($groupFactSumOutcome, 2) .'</span> <i class="fa fa-rub"></i></b>
												    <span class="text-right text-td-small" style="white-space:nowrap"><b><span class="to-humanize groupFactSum" data-value="'. $groupFactSum .'">'. round($groupFactSum, 2) .'</span> <i class="fa fa-rub"></i></b></span>
													</td>
											  	<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupSumRestOutcome" data-value="'.round($groupPercentSum-$groupFactSumOutcome, 2) .'">'. round($groupPercentSum-$groupFactSumOutcome, 2) .'</span> <i class="fa fa-rub"></i></b>
											  	  <b class="text-td-small"><span class="to-humanize groupSumRest" data-value="'.round($groupPercentSum-$groupFactSum, 2) .'">'. round($groupPercentSum-$groupFactSum, 2) .'</span> <i class="fa fa-rub"></i></b>
													</td>
											  </tr>';

												  $budgetCostsGroup->budgetCosts = $budgetCostsGroup->budgetCosts->sortBy(function ($budgetCost) {
                            return $budgetCost->name;
                          });
												?>
											  @foreach ($budgetCostsGroup->budgetCosts as $budgetCost)
											  <?php
												  $costSum        = $budgetCost->getSum($workProject->id, $endDate);
												  $costSumOutcome = $budgetCost->getSumOutcome($workProject->id, $endDate);
												?>
												  @if($costSum)
													<?php
													  $noDebtOrNoPlanGroups .=
													  '<tr style="display: none;">
														  <td><span class="table-list-child">'. str_replace($budgetCostsGroup->name . '. ', '', $budgetCost->name) .'</span></td>
														  <td></td>
														  <td></td>
														  <td class="text-right" style="white-space:nowrap"><span class="to-humanize">'. $costSumOutcome .'</span> <i class="fa fa-rub"></i>
														    <span class="text-right text-td-small" style="white-space:nowrap"><span class="to-humanize">'. $costSum .'</span> <i class="fa fa-rub"></i></span>
															</td>
														  <td></td>
													  </tr>';
													?>
													@endif
													@if(!$costSum)
													  <?php
													  $noDebtCosts .=
														  '<tr style="display: none;">
														    <td><span class="table-list-child">'. str_replace($budgetCostsGroup->name . '. ', '', $budgetCost->name).'</span></td>
														    <td></td>
														    <td></td>
														    <td class="text-right" style="white-space:nowrap"><span class="to-humanize">'. $costSumOutcome .'</span> <i class="fa fa-rub"></i>
														      <span class="text-right text-td-small" style="white-space:nowrap"><span class="to-humanize">'. $costSum .'</span> <i class="fa fa-rub"></i></span>
																</td>
														    <td></td>
													    </tr>';
													  ?>
													@endif
											  @endforeach
												<?php  $noDebtOrNoPlanGroups .= $noDebtCosts; ?>
											@endif
											@if(!$groupFactSum && !$groupPercentAmount)
											<?php
											  $noDebtNoPlanGroups .=
											  '<tr class="group-header-raw ">
												  <td><b>'.$budgetCostsGroup->name.'</b></td>
												  <td class="text-right col-md-6" style="white-space:nowrap"><b><a href="#" class="group-month-plan" data-name="'. $workProject->id .'_'. $budgetCostsGroup->id .'" data-type="text" data-pk="'. $groupPercentId .'" data-value="'. $groupPercentAmount .'">'.round($groupPercentAmount, 2).' </a></b></td>
													<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupPercentSum" data-value="'.$groupPercentSum.'">'. $groupPercentSum.'</span> <i class="fa fa-rub"></i></b></td>
												  <td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupFactSumOutcome" data-value="'. $groupFactSumOutcome .'">'. round($groupFactSumOutcome, 2) .'</span> <i class="fa fa-rub"></i></b>
												    <span class="text-right text-td-small" style="white-space:nowrap"><b><span class="to-humanize groupFactSum" data-value="'. $groupFactSum .'">'. round($groupFactSum, 2) .'</span> <i class="fa fa-rub"></i></b></span>
													</td>
												  <td class="text-right" style="white-space:nowrap"><b><span class="to-humanize groupSumRestOutcome" data-value="'. round($groupPercentSum-$groupFactSumOutcome, 2) .'">'. round($groupPercentSum-$groupFactSumOutcome, 2) .'</span> <i class="fa fa-rub"></i></b>
												    <b class="text-td-small"><span class="to-humanize groupSumRest" data-value="'. round($groupPercentSum-$groupFactSum, 2) .'">'. round($groupPercentSum-$groupFactSum, 2) .'</span> <i class="fa fa-rub"></i></b>
												  </td>
											  </tr>';
											?>
											@endif
										@endforeach
										{{ $noDebtOrNoPlanGroups }}
										{{ $noDebtNoPlanGroups }}
										<?php
										  $budgetCostsUnknown = BudgetCost::whereIn('project_id', array($workProject->id, 0))
							                                        ->whereBudgetCostGroupId(0)
														                          ->orderBy('name')
															                        ->get();
										?>
										@if	($budgetCostsUnknown)
										  <tr class="group-header-raw">
												<td><b>Без группы</b></td>
												<td></td>
												<td class="text-right"></td>
												<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize">{{ $workProject->getUnknownGroupSumOutcome($endDate) }}</span> <i class="fa fa-rub"></i></b>
												  <b class="text-td-small"><span class="to-humanize">{{ $workProject->getUnknownGroupSum($endDate) }}</span> <i class="fa fa-rub"></i></b>
									      </td>
												<td></td>
											</tr>
										  @foreach ($budgetCostsUnknown as $budgetCostUnknown)
											  <tr>
													<td><span class="table-list-child">{{ $budgetCostUnknown->name }}</span></td>
													<td></td>
													<td></td>
												  <td class="text-right" style="white-space:nowrap"><span class="to-humanize">{{ $budgetCostUnknown->getSumOutcome($workProject->id, $endDate) }}</span> <i class="fa fa-rub"></i>
												    <span class="text-right text-td-small" style="white-space:nowrap"><span class="to-humanize">{{ $budgetCostUnknown->getSum($workProject->id, $endDate) }}</span> <i class="fa fa-rub"></i>
													</td>
												  <td></td>
											  </tr>
											@endforeach
										@endif
											<tr>
												<td title="Включено в итоговую сумму"><b>Без категории</b></td>
												<td></td>
												<td class="text-right"></td>
												<td class="text-right" style="white-space:nowrap" title="Включено в итоговую сумму"><b><span class="to-humanize">{{ $workProject->getUnknownSumOutcome($endDate) }}</span> <i class="fa fa-rub"></i></b>
												  <b class="text-td-small"><span class="to-humanize">{{ $workProject->getUnknownSum($endDate) }}</span> <i class="fa fa-rub"></i></b>
												</td>
											  <td></td>
											</tr>
											<tr>
												<td><b>На долги (входит в сумму итога)</b>
												    <span class="text-td-small">На долги (не входит в сумму итога)</span>
												</td>
												<td></td>
												<td class="text-right"></td>
												<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize" title="Включено в итоговую сумму факт. расходов">{{ $unknownDebtSumOutcome = $workProject->getUnknownDebtSumOutcome($endDate) }}</span> <i class="fa fa-rub"></i></b>
											    <b class="text-td-small"><span class="to-humanize" title="Не включено в итоговую сумму факт. расходов">{{ $unknownDebtSum = $workProject->getUnknownDebtSum($endDate) }}</span> <i class="fa fa-rub"></i></b>
												</td>
											  <td></td>
											</tr>
											<tr>
												<td><b>Всего</b></td>
												<td class="text-right" style="white-space:nowrap"><b><span id="groupPercentTotal" title="Нераспределенный бюджет:  {{ round((100 - $groupPercentTotal), 2) }}%">{{ round($groupPercentTotal, 2) }}</span> %</b></td>
												<td class="text-right" style="white-space:nowrap"><b><span class="to-humanize" id="groupPercentSumTotal" title="Нераспределенный бюджет:  {{ round(($workProject->getCurrentBudgetMonthPlan() - $groupPercentSumTotal), 2) }} руб.">{{ round($groupPercentSumTotal, 2) }}</span></b> <i class="fa fa-rub"></i></td>
												<td class="text-right" style="white-space:nowrap">
													<b><span class="to-humanize">{{ $workProject->getAllCostOutcome($endDate) }}</span> <i class="fa fa-rub"></i></b>
													<b class="text-td-small"><span class="to-humanize">{{ $workProject->getAllCost($endDate) - $unknownDebtSum }}</span> <i class="fa fa-rub"></i></b>
												</td>
												<td class="text-right" style="white-space:nowrap"> <b><span class="to-humanize planAmountRestOutcome">{{ round($workProject->getPlanAmountRestOutcome(), 2) }}</span></b><!-- !! Уточнить как считать остаток -->
													<b class="text-td-small"><span class="to-humanize planAmountRest">{{ round($workProject->getPlanAmountRest(), 2) }}</span></b>
												</td>
											</tr>
										</tbody>
									</table>
									@if ($user->hasRole(Role::ROLE_BUDGET))
										<a class="btn btn-sm btn-default pull-right" href="{{ action('BudgetController@costExport', array($workProject->id, $endDate)) }}" target="_blank">Экспорт в Excel</a>
										<a class="btn btn-sm btn-primary pull-right" href="{{ action('BudgetController@ddsReport', array($workProject->id, $endDate)) }}" target="_blank">Отчет ДДС</a>
										<div class="clearfix"></div>
									@endif
								</div>
							</div>
						</div>
						@endif
						<div class="col-md-4 pull-right">
							<div class="well well-sm">
							  <b>Сумма расходов на {{ $workProject->getMonthName() }}</b>
								<div class="pull-right">
									<a href="#" class="to-humanize month-plan" data-type="text" data-pk="{{ $workProject->id }}" data-value="{{ $workProject->getCurrentBudgetMonthPlan() }}">{{ $workProject->getCurrentBudgetMonthPlan() }}</a> <i class="fa fa-rub"></i>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
  @section('modals')
	  @include('budget/modal')
	@stop
@stop
