@extends('layouts.app')

@section('title','Attendance Reports')

@section('content')
<div class="card">
  <div class="card-header" style="display:flex; align-items:center; justify-content:space-between;">
    <div>Attendance Report</div>
    <a class="btn" href="{{ route('reports.export', ['date' => $date, 'grade_id' => $selectedGradeId]) }}">Export CSV</a>
  </div>
  <div class="card-body" style="overflow-x:auto;">
    <form method="GET" action="{{ route('reports.index') }}" style="margin-bottom:16px; display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
      <div>
        <label>Date</label>
        <input type="date" name="date" value="{{ $date }}" style="padding:8px 10px; border-radius:8px; border:1px solid #cfd8dc;">
      </div>
      <div>
        <label>Grade</label>
        <select name="grade_id" style="padding:8px 10px; border-radius:8px; border:1px solid #cfd8dc;">
          <option value="">All Grades</option>
          @foreach ($grades as $g)
            <option value="{{ $g->id }}" {{ (string)$selectedGradeId === (string)$g->id ? 'selected' : '' }}>{{ $g->name }}</option>
          @endforeach
        </select>
      </div>
      <button class="btn" type="submit">Apply</button>
    </form>

    @php
      $present = collect($attendanceData)->where('status', '!=', 'Absent')->count();
      $absent = collect($attendanceData)->where('status', 'Absent')->count();
      $late = collect($attendanceData)->filter(fn($a) => str_contains($a['status'], 'Late'))->count();
      $total = count($attendanceData);
      $byGrade = collect($attendanceData)->groupBy(fn($a) => $a['student']->grade_name ?? 'Unassigned')
                  ->map(function($items){
                    $p = $items->where('status','!=','Absent')->count();
                    $l = $items->filter(fn($a)=> str_contains($a['status'],'Late'))->count();
                    $t = $items->count();
                    return ['present'=>$p,'late'=>$l,'total'=>$t];
                  });
    @endphp

    @if ($total === 0)
      <p>No students found for this filter.</p>
    @else
      <div style="margin-bottom:16px; display:flex; flex-direction:column; gap:10px;">
        <div style="display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
          <span style="font-weight:700;">Summary ({{ $date }}):</span>
          <span style="padding:4px 8px; border-radius:8px; background:rgba(76,175,80,0.1); color:#388E3C;">Present: {{ $present }}/{{ $total }}</span>
          <span style="padding:4px 8px; border-radius:8px; background:rgba(255,152,0,0.1); color:#F57C00;">Late: {{ $late }}</span>
          <span style="padding:4px 8px; border-radius:8px; background:rgba(211,47,47,0.1); color:#C62828;">Absent: {{ $absent }}</span>
        </div>
        <div style="display:flex; gap:8px; flex-wrap:wrap;">
          @foreach ($byGrade as $grade => $vals)
            <a href="{{ route('reports.index', ['date'=>$date,'grade_id'=>optional($grades->firstWhere('name',$grade))->id]) }}" style="text-decoration:none;">
              <span style="display:inline-flex; align-items:center; gap:6px; padding:6px 10px; border-radius:999px; border:1px solid #e0e0e0; background:#fff;">
                <strong style="color:#0D47A1;">{{ $grade }}</strong>
                <span class="muted">{{ $vals['present'] }}/{{ $vals['total'] }} present</span>
              </span>
            </a>
          @endforeach
        </div>
      </div>

      <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap:16px; margin-bottom:16px;">
        <div class="card" style="box-shadow:none;">
          <div class="card-header">Status Distribution</div>
          <div class="card-body"><canvas id="statusChart" height="180"></canvas></div>
        </div>
        <div class="card" style="box-shadow:none;">
          <div class="card-header">Present by Grade</div>
          <div class="card-body"><canvas id="gradeChart" height="180"></canvas></div>
        </div>
      </div>

      <table>
        <thead>
          <tr>
            <th>Student</th>
            <th>Grade</th>
            <th>Clock In</th>
            <th>Clock Out</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          @foreach ($attendanceData as $data)
            <tr>
              <td>{{ $data['student']->last_name }}, {{ $data['student']->first_name }}</td>
              <td>{{ $data['student']->grade_name }}</td>
              <td>
                @if ($data['clock_in'])
                  {{ date('H:i', strtotime($data['clock_in']->occurred_at)) }}
                @else
                  -
                @endif
              </td>
              <td>
                @if ($data['clock_out'])
                  {{ date('H:i', strtotime($data['clock_out']->occurred_at)) }}
                @else
                  -
                @endif
              </td>
              <td>
                <span style="
                  padding:4px 8px; 
                  border-radius:6px; 
                  font-size:12px; 
                  font-weight:600;
                  @if($data['status'] === 'Absent') background:rgba(211,47,47,0.1); color:#C62828;
                  @elseif(str_contains($data['status'], 'Late')) background:rgba(255,152,0,0.1); color:#F57C00;
                  @else background:rgba(76,175,80,0.1); color:#388E3C; @endif
                ">
                  {{ $data['status'] }}
                </span>
              </td>
            </tr>
          @endforeach
        </tbody>
      </table>
    @endif
  </div>
</div>

@if ($total ?? 0)
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function(){
    const statusCtx = document.getElementById('statusChart');
    if (statusCtx) {
      new Chart(statusCtx, {
        type: 'doughnut',
        data: {
          labels: ['Present','Late','Absent'],
          datasets: [{
            data: [{{ $present }}, {{ $late }}, {{ $absent }}],
            backgroundColor: ['#4CAF50','#FF9800','#D32F2F']
          }]
        },
        options: { plugins: { legend: { position: 'bottom' } } }
      });
    }
    const gradeCtx = document.getElementById('gradeChart');
    if (gradeCtx) {
      const labels = {!! json_encode($byGrade->keys()->values()) !!};
      const presentData = {!! json_encode($byGrade->map(fn($v)=>$v['present'])->values()) !!};
      new Chart(gradeCtx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{ label: 'Present', data: presentData, backgroundColor: '#0D47A1' }]
        },
        options: { scales: { y: { beginAtZero: true } } }
      });
    }
  });
  </script>
@endif
@endsection
