@extends('layout.base')

@section('content')
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3>Construcci&oacute;n Proyecto <a href="{{nUrl('proyectos', 'show', ['proyecto' => $proyecto->id])}}">{{$proyecto->descripcion}}</a></h3>
    </div>
    <div class="panel-body">
      <div class="panel panel-default">
        <div class="panel-heading">
          <div class="row">
            <div class="col-md-2"><b>Estado de Pago</b></div>
            <div class="col-md-10"><b>Avance</b></div>
          </div>
        </div>
        <div class="panel-body">
          @foreach ($proyecto->avances() as $avance)
            <div class="row">
              <div class="col-md-2">
                @if ($avance->numero == 0)
                  Anticipo
                @else
                  {{$avance->numero}}
                @endif
              </div>
              <div class="col-md-10">
                <div class="progress" style="margin: 2px 0;">
                  <div class="progress-bar" style="width: {{round($avance->avance * 100, 2)}}%">
                    <span class="sr-only">{{format('percent', round($avance->avance * 100, 2))}}%</span>
                    @if ($avance->avance > 0.3)
                      {{format('percent', round($avance->avance * 100, 2))}}%
                    @endif
                  </div>
                  <div class="progress-bar progress-bar-warning" style="width: {{round(100 - $avance->avance * 100, 2)}}%">
                    <span class="sr-only">{{format('percent', round(100 - $avance->avance * 100, 2))}}%</span>
                    @if ($avance->avance <= 0.3)
                      {{format('percent', round($avance->avance * 100, 2))}}%
                    @endif
                  </div>
                </div>
              </div>
            </div>
          @endforeach
        </div>
      </div>
      <table class="table table-bordered table-striped">
        <thead>
          <tr>
            <th rowspan="2">
              Estado de Pago
              <a href="{{nUrl('proyectos', 'advance', ['proyecto' => $proyecto->id])}}">
                <span class="glyphicon glyphicon-plus"></span>
              </a>
            </th>
            <th colspan="4" class="text-center">Pagado</th>
            <th rowspan="2">
              Pagar&eacute;
              <a href="{{nUrl('pagares', 'add', ['proyecto' => $proyecto->id])}}">
                <span class="glyphicon small glyphicon-plus"></span>
              </a>
            </th>
            <th colspan="4" class="text-center">Deuda</th>
          </tr>
          <tr>
            <th>Fecha</th>
            <th>Valor</th>
            <th>Real</th>
            <th>Diferencia</th>
            <th>Fecha</th>
            <th>Valor</th>
            <th>Abonado</th>
            <th>Diferencia</th>
            <th>Intereses</th>
            <th class="small">% Intereses</th>
          </tr>
        </thead>
        <tbody>
          <?php $totales = (object) [
            'avance' => (object) [
              'pagado' => 0,
              'real' => 0,
              'dif' => 0
            ],
            'deuda' => (object) [
              'pagare' => 0,
              'abonado' => 0,
              'dif' => 0,
              'intereses' => 0
            ],
            'dif' => 0,
            'dif_real' => 0
          ] ?>
          @foreach ($proyecto->avances() as $i => $avance)
            <?php
            $totales->avance->pagado += $avance->estado_pago;
            $totales->avance->real += $avance->pagado();
            if ($avance->pagado() > 0) {
              $totales->avance->dif += $avance->pagado() - $avance->estado_pago;
            }
            if ($avance->pagares()) {
              $arr = $avance->pagares();
              $totales->deuda->pagare += array_reduce($arr, function($sum, $item) {
                return $sum + $item->valor();
              });
              $totales->deuda->abonado += array_reduce($arr, function($sum, $item) {
                return $sum + $item->abonado();
              });
              $totales->deuda->dif += array_reduce($arr, function($sum, $item) {
                return $sum + $item->abonado() - $item->valor();
              });
              $totales->deuda->intereses += array_reduce($arr, function($sum, $item) {
                return $sum + $item->intereses();
              });
              $totales->dif += array_reduce($arr, function($sum, $item) {
                return $sum + $item->valor();
              }) - $avance->estado_pago;
            }
            ?>
            <tr>
              <td>
                <a href="{{nUrl('proyectos', 'editar_avance', ['avance' => $avance->id])}}">
                  @if ($avance->numero == 0)
                    Anticipo
                  @else
                    {{$avance->numero}}</a>
                  @endif
                </a>
              </td>
              <td>{{format('shortDate', $avance->fecha)}}</td>
              <td class="text-right">{{format('ufs', $avance->estado_pago)}}</td>
              <td class="text-right">
                @if ($avance->pagado() > 0)
                  {{format('ufs', $avance->pagado())}}
                @endif
              </td>
              <td class="text-right">
                @if ($avance->pagado() > 0)
                  {{format('ufs', $avance->estado_pago - $avance->pagado())}}
                @endif
              </td>
              <td>
                @if ($avance->pagares())
                  @foreach ($avance->pagares() as $pagare)
                    <a href="{{nUrl('pagares', 'show', ['pagare' => $pagare->id])}}">
                      {{$pagare->id}} ({{$pagare->moneda()->descripcion}})
                    </a><br />
                  @endforeach
                @else
                  --
                @endif
              </td>
              <td>
                @if ($avance->pagares())
                  @foreach ($avance->pagares() as $pagare)
                    {{format('shortDate', $pagare->fecha)}} ({{$pagare->duracion}})<br />
                  @endforeach
                @endif
              </td>
              <td class="text-right">
                @if ($avance->pagares())
                  @foreach ($avance->pagares() as $pagare)
                    {{format('ufs', $pagare->valor())}}<br />
                  @endforeach
                @endif
              </td>
              <td class="text-right">
                @if ($avance->pagares())
                  @foreach ($avance->pagares() as $pagare)
                    {{format('ufs', $pagare->abonado())}}<br />
                  @endforeach
                @endif
              </td>
              <td class="text-right">
                @if ($avance->pagare())
                  {{format('ufs', $pagare->abonado() - $pagare->valor())}}
                @endif
              </td>
              <td class="text-right">
                @if ($avance->pagares())
                  @foreach ($avance->pagares() as $pagare)
                    {{format('ufs', - $pagare->intereses())}}<br />
                  @endforeach
                @endif
              </td>
              <td class="text-right small">
                @if ($avance->pagares())
                  @foreach ($avance->pagares() as $pagare)
                    {{format('percent', round($pagare->intereses() / $pagare->valor() * 100, 2), null, true)}}<br />
                  @endforeach
                @endif
              </td>
            </tr>
          @endforeach
          <tr>
            <td><b>Total</b></td>
            <td></td>
            <td class="text-right"><b>{{format('ufs', $totales->avance->pagado)}}</b></td>
            <td class="text-right"><b>{{format('ufs', $totales->avance->real)}}</b></td>
            <td class="text-right"><b>{{format('ufs', - $totales->avance->dif)}}</b></td>
            <td colspan="2"></td>
            <td class="text-right"><b>{{format('ufs', $totales->deuda->pagare)}}</b></td>
            <td class="text-right"><b>{{format('ufs', $totales->deuda->abonado)}}</b></td>
            <td class="text-right"><b>{{format('ufs', $totales->deuda->dif)}}</b></td>
            <td class="text-right"><b>{{format('ufs', - $totales->deuda->intereses)}}</b></td>
          </tr>
        </tbody>
      </table>
      <div class="panel panel-default">
        <div class="panel-heading">
          <b>Diferencias en Caja</b>
        </div>
        <div class="panel-body">
          <canvas id="estados_pago"></canvas>
        </div>
      </div>
    </div>
  </div>
@endsection

@push('scripts')
  <script type="text/javascript">
    var estados_pago = []
    var pagado = []
    var abonado = []
    var diferencia = []
    var intereses = []
    var colores_dif = []
    function setUp() {
      @foreach ($proyecto->avances() as $avance)
        estados_pago.push({{$avance->numero}})
        pagado.push(({{$avance->pagado()}}).toFixed(2))
        valor = 0
        if (diferencia.length > 0) {
          valor = parseFloat(diferencia[diferencia.length - 1])
        }
        valor2 = 0
        if (intereses.length > 0) {
          valor2 = parseFloat(intereses[intereses.length - 1])
        }
        @if ($avance->pagares())
          <?php $arr = $avance->pagares() ?>
          abonado.push({{array_reduce($arr, function($sum, $item) {return $sum + $item->abonado();})}}.toFixed(2))
          diferencia.push((valor + {{array_reduce($arr, function($sum, $item) {return $sum + $item->abonado();}) - $avance->pagado()}}).toFixed(2))
          intereses.push((valor2 + {{array_reduce($arr, function($sum, $item) {return $sum + $item->intereses();})}}).toFixed(2))
        @else
          abonado.push(0)
          diferencia.push((valor + {{-$avance->pagado()}}).toFixed(2))
          intereses.push(valor2.toFixed(2))
        @endif
        if (diferencia[diferencia.length - 1] < 0) {
          colores_dif.push('rgba(255, 0, 0, 1)')
        } else {
          colores_dif.push('rgba(0, 255, 0, 1)')
        }
      @endforeach
      console.debug(intereses)
    }
    function formatNumber(number, decimals = 2, dec_sep = ',', thou_sep = '.') {
      var arr = ('' + number).split('.')
      var num = arr[0]
      var dec = arr.length > 1 ? dec_sep + arr[1] : ''
      var rgx = /(\d+)(\d{3})/
      while (rgx.test(num)) {
        num = num.replace(rgx, '$1' + thou_sep + '$2')
      }
      return num + dec
    }
    function build() {
      var ctx = $('#estados_pago').get(0).getContext('2d')
      var chart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: estados_pago,
          datasets: [
            {
              label: 'Abonado por Banco',
              data: abonado,
              backgroundColor: 'rgba(0, 255, 255, 1)'
            },
            {
              label: 'Pagado a Constructora',
              data: pagado,
              backgroundColor: 'rgba(0, 0, 255, 1)'
            },
            {
              label: 'Diferencia',
              data: diferencia,
              backgroundColor: colores_dif
            },
            {
              label: 'Intereses',
              data: intereses,
              backgroundColor: 'rgba(255, 255, 0, 1)'
            }
          ]
        },
        options: {
          scales: {
            yAxes: [{
              afterTickToLabelConversion: (axis) => {
                $.each(axis.ticks, (i, el) => {
                  axis.ticks[i] = formatNumber(parseInt(el))
                })
                return axis
              }
            }]
          },
          tooltips: {
            callbacks: {
              title: (tooltipItem, data) => {
                var ep = data.labels[tooltipItem[0].index]
                var label = 'Anticipo'
                if (ep > 0) {
                  label = 'EP ' + ep
                }
                return label
              },
              label: (tooltipItem, data) => {
                var label = data.datasets[tooltipItem.datasetIndex].label || ''
                if (label) {
                    label += ': '
                }
                label += formatNumber(tooltipItem.yLabel)
                return label
              }
            }
          }
        }
      })
    }
    $(document).ready(function() {
      setUp()
      build()
    })
  </script>
@endpush
