<form method="GET" class="mb-4">
  <div class="form-group">
    <label for="period">Periodo:</label>
    <select name="period" id="period" class="form-control" onchange="this.form.submit()">
      <?php foreach ($availablePeriods as $year): ?>
        <option value="<?= $year ?>" <?= $year == $currentPeriod ? 'selected' : '' ?>>
          <?= $year ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>
</form>



<div class="row mt-4">
  <!-- Cards iniciales -->
  <div class="col-md-6 col-xl-3 mb-4">
    <div class="card shadow-sm border-0">
      <div class="card-body d-flex align-items-center">
        <div class="bg-primary text-white rounded-circle p-3 mr-3">
          <i class="fe fe-folder-plus fe-24"></i>
        </div>
        <div>
          <p class="mb-0 text-muted">Trámites</p>
          <h4 class="mb-0"><?= $cardCounts['Trámites totales']; ?></h4>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-xl-3 mb-4">
    <div class="card shadow-sm border-0">
      <div class="card-body d-flex align-items-center">
        <div class="bg-warning text-white rounded-circle p-3 mr-3">
          <i class="fe fe-refresh-cw fe-24"></i>
        </div>
        <div>
          <p class="mb-0 text-muted">En Proceso</p>
          <h4 class="mb-0"><?= $cardCounts['En proceso']; ?></h4>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-xl-3 mb-4">
    <div class="card shadow-sm border-0">
      <div class="card-body d-flex align-items-center">
        <div class="bg-danger text-white rounded-circle p-3 mr-3">
          <i class="fe fe-alert-triangle fe-24"></i>
        </div>
        <div>
          <p class="mb-0 text-muted">Observados</p>
          <h4 class="mb-0"><?= $cardCounts['Observado']; ?></h4>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-xl-3 mb-4">
    <div class="card shadow-sm border-0">
      <div class="card-body d-flex align-items-center">
        <div class="bg-success text-white rounded-circle p-3 mr-3">
          <i class="fe fe-check-circle fe-24"></i>
        </div>
        <div>
          <p class="mb-0 text-muted">Resueltos</p>
          <h4 class="mb-0"><?= $cardCounts['Resuelto']; ?></h4>
        </div>
      </div>
    </div>
  </div>

  <!-- Gráficos -->
    <div class="col-md-12">
        <div class="card shadow-sm border-0">
            <div class="card-header">
                <strong class="card-title">Gráfico de Trámites por Estado</strong>
            </div>
            <div class="card-body">
                <canvas id="barChart" height="100"></canvas>
            </div>
        </div>
    </div>
</div>



<div class="row mt-4">
  <!-- Gráfico de Resumen de Trámites -->
  <div class="col-lg-6 mb-4">
    <div class="card shadow-sm border-0">
      <div class="card-header">
        <strong class="card-title">Trámites por Prioridad</strong>
      </div>
        <div class="card-body">
            <canvas id="priorityChart" height="100"></canvas>
        </div>
    </div>
  </div>

  <div class="col-md-6">
    <div class="card shadow-sm">
      <div class="card-body">
        <h6 class="card-title mb-3">Algunos Trámites Urgentes</h6>
        <div class="table-responsive">
          <table class="table table-bordered mb-0">
            <thead>
              <tr>
                <th>Expediente</th>
                <th>Asunto</th>
                <th>Fecha de Ingreso</th>
                <th>Área Actual</th>
                <th>Acción</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($urgentProcesses)): ?>
                <tr>
                  <td colspan="5" class="text-center">No hay trámites urgentes.</td>
                </tr>
              <?php else: ?>
                <?php foreach ($urgentProcesses as $process): ?>
                  <?php 
                    $location = $process->lastLocation();
                    $areaActual = $location?->subgroup()->description ?? $location?->group()->description ?? '—';
                  ?>
                  <tr>
                    <td><?= htmlspecialchars($process->num_exped); ?></td>
                    <td><?= htmlspecialchars($process->subject); ?></td>
                    <td><?= date('d/m/Y', strtotime($process->entry_date)) ?></td>
                    <td><?= htmlspecialchars($areaActual); ?></td>
                    <td>
                      <a href="<?= BASE_HREF ?>processes/<?= htmlspecialchars($process->id); ?>/show-process" class="btn btn-sm btn-primary">
                        Ver
                      </a>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-12">
      <div class="card shadow-sm">
          <div class="card-body">
              <h6 class="card-title mb-3">Estado Actual de Trámites por Área</h6>
              <div class="table-responsive">
              <table class="table table-bordered mb-0">
          <thead>
              <tr>
              <th>Área</th>
              <th>Pendiente</th>
              <th>Recibido</th>
              <th>Derivado</th>
              <th>Observado</th>
              <th>Resuelto</th>
              </tr>
          </thead>
          <tbody>
              <?php foreach ($processStatesByArea as $item): ?>
              <tr>
                  <td><?= htmlspecialchars($item['area']); ?></td>
                  <td><?= $item['PENDIENTE'] ?? 0; ?></td>
                  <td><?= $item['RECIBIDO'] ?? 0; ?></td>
                  <td><?= $item['DERIVADO'] ?? 0; ?></td>
                  <td><?= $item['OBSERVADO'] ?? 0; ?></td>
                  <td><?= $item['RESUELTO'] ?? 0; ?></td>
              </tr>
              <?php endforeach; ?>
          </tbody>
          </table>

              </div>
          </div>
      </div>
  </div>
</div>





<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    var data = <?php echo json_encode($processesByAreaAndState); ?>;

    var areas = data.map(function(item) { return item.area; });
    var enProceso = data.map(function(item) { return item.en_proceso; });
    var observado = data.map(function(item) { return item.observado; });
    var resuelto = data.map(function(item) { return item.resuelto; });

    var ctx = document.getElementById('barChart').getContext('2d');
    var barChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: areas,
            datasets: [
                {
                    label: 'En Proceso',
                    data: enProceso,
                    backgroundColor: '#efa302',
                    borderColor: '#efa302', 
                    borderWidth: 1
                },
                {
                    label: 'Observado',
                    data: observado,
                    backgroundColor: '#dd3445',
                    borderColor: '#dd3445',
                    borderWidth: 1
                },
                {
                    label: 'Resuelto',
                    data: resuelto,
                    backgroundColor: '#3ad29f',
                    borderColor: '#3ad29f',
                    borderWidth: 1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        display: false
                    },
                    ticks: {
                        stepSize: 5
                    }
                },
                x: {
                    grid: {
                        display: false 
                    }
                }
            },
            
        }
    });
</script>


<script>
    var ctx = document.getElementById('priorityChart').getContext('2d');
    var priorityData = <?php echo json_encode($processesByPriority); ?>;

    var labels = priorityData.map(function(item) {
        return item.priority;
    });

    var data = priorityData.map(function(item) {
        return item.count;
    });

    var priorityChart = new Chart(ctx, {
        type: 'doughnut', 
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: ['#42A5F5', '#efa302', '#dd3445'],
                hoverBackgroundColor: ['#2196F3', '#FBC02D', '#c62828']
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
                tooltip: {
                    callbacks: {
                        label: function(tooltipItem) {
                            return tooltipItem.raw + " trámites";
                        }
                    }
                }
            }
        }
    });
</script>