<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <title>Relatório Detalhado – Indicadores de TI</title>
    <style>
        body {
            font-family: 'DejaVu Sans', sans-serif;
            font-size: 9px;
            color: #000;
            margin: 12px 16px;
        }

        h1 {
            font-size: 14px;
            margin-bottom: 2px;
            color: #1a1a2e;
        }

        .meta {
            font-size: 8px;
            color: #444;
            margin-bottom: 10px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 12px;
        }

        th {
            background: #1a1a2e;
            color: #fff;
            padding: 5px;
            font-size: 8px;
            text-align: left;
        }

        td {
            padding: 4px;
            border-bottom: 1px solid #ddd;
        }

        tfoot tr {
            background: #e9ecef;
            font-weight: 700;
        }

        tfoot td {
            padding: 4px;
        }

        .badge {
            padding: 1px 5px;
            border-radius: 6px;
            font-size: 7px;
            font-weight: bold;
        }

        .b-ok {
            background: #10B981;
            color: #fff;
        }

        .b-pen {
            background: #F59E0B;
            color: #fff;
        }

        .b-prog {
            background: #4F46E5;
            color: #fff;
        }

        .b-canc {
            background: #6c757d;
            color: #fff;
        }

        .b-alta {
            background: #EF4444;
            color: #fff;
        }

        .b-media {
            background: #F59E0B;
            color: #fff;
        }

        .b-baixa {
            background: #10B981;
            color: #fff;
        }

        .text-right {
            text-align: right;
        }

        .text-center {
            text-align: center;
        }

        .text-muted {
            color: #6c757d;
        }

        .fw-bold {
            font-weight: 700;
        }

        .footer {
            margin-top: 18px;
            padding-top: 6px;
            border-top: 1px solid #ccc;
            font-size: 7px;
            color: #888;
        }
    </style>
</head>

<body>

    <h1>Relatório Detalhado – Indicadores de TI</h1>
    <div class="meta">
        Gerado em {{ now()->format('d/m/Y H:i') }} | Total: {{ $total }} chamados
        @if (!empty($filters['data_inicio']) || !empty($filters['data_fim']))
            | Período:
            {{ !empty($filters['data_inicio']) ? \Carbon\Carbon::parse($filters['data_inicio'])->format('d/m/Y') : '—' }}
            a {{ !empty($filters['data_fim']) ? \Carbon\Carbon::parse($filters['data_fim'])->format('d/m/Y') : '—' }}
        @endif
        @if (!empty($filters['status']))
            | Status: {{ __(\App\Models\IndicadoresTi\Chamado::STATUS[$filters['status']] ?? $filters['status']) }}
        @endif
        @if (!empty($filters['prioridade']))
            | Prioridade:
            {{ __(\App\Models\IndicadoresTi\Chamado::PRIORIDADE[$filters['prioridade']] ?? $filters['prioridade']) }}
        @endif
    </div>

    <table style="margin-bottom:20px;">
        <tr>
            @include('admin.indicadoresTi.reports.partials._kpi_card', [
                'value' => $total,
                'label' => 'Total',
                'bg' => '#f4f4f4',
                'color' => '#111',
                'width' => '20%',
            ])
            @include('admin.indicadoresTi.reports.partials._kpi_card', [
                'value' => $porStatus['atendido'] ?? 0,
                'label' => 'Atendidos',
                'bg' => '#d1fae5',
                'color' => '#065f46',
                'width' => '20%',
            ])
            @include('admin.indicadoresTi.reports.partials._kpi_card', [
                'value' => $porStatus['pendente'] ?? 0,
                'label' => 'Pendentes',
                'bg' => '#fef3c7',
                'color' => '#92400e',
                'width' => '20%',
            ])
            @include('admin.indicadoresTi.reports.partials._kpi_card', [
                'value' => $porStatus['em_andamento'] ?? 0,
                'label' => 'Em Andamento',
                'bg' => '#dbeafe',
                'color' => '#1e40af',
                'width' => '20%',
            ])
            @include('admin.indicadoresTi.reports.partials._kpi_card', [
                'value' => $porStatus['cancelado'] ?? 0,
                'label' => 'Cancelados',
                'bg' => '#f1f5f9',
                'color' => '#475569',
                'width' => '20%',
            ])
        </tr>
    </table>

    @php
        use App\Services\Reports\SvgChartBuilder;
        use App\Models\IndicadoresTi\Chamado;

        $chart = new SvgChartBuilder();

        $statusColors = ['#4F46E5', '#F59E0B', '#10B981', '#6c757d'];
        $prioColors = ['#10B981', '#F59E0B', '#EF4444', '#8B5CF6'];
        $tipoColors = ['#4F46E5', '#10B981', '#F59E0B', '#EF4444', '#06B6D4'];
        $canalColors = ['#8B5CF6', '#06B6D4', '#F59E0B', '#10B981'];

        $statusData = [];
        foreach (Chamado::STATUS as $v => $l) {
            if (($porStatus[$v] ?? 0) > 0) {
                $statusData[__($l)] = $porStatus[$v];
            }
        }
        $prioData = [];
        foreach (Chamado::PRIORIDADE as $v => $l) {
            if (($porPrioridade[$v] ?? 0) > 0) {
                $prioData[__($l)] = $porPrioridade[$v];
            }
        }
        $tipoData = [];
        foreach (Chamado::TIPO as $v => $l) {
            if (($porTipo[$v] ?? 0) > 0) {
                $tipoData[__($l)] = $porTipo[$v];
            }
        }
        $canalData = [];
        foreach (Chamado::CANAL as $v => $l) {
            if (($porCanal[$v] ?? 0) > 0) {
                $canalData[__($l)] = $porCanal[$v];
            }
        }

        $setorData = collect($porSetor)
            ->sortByDesc('total')
            ->take(10)
            ->mapWithKeys(fn($r) => [$r['nome'] => $r['total']])
            ->toArray();

        $svgStatus = $chart->donutChart($statusData, 90, $statusColors);
        $svgPrio = $chart->donutChart($prioData, 90, $prioColors);
        $svgTipo = $chart->donutChart($tipoData, 90, $tipoColors);
        $svgCanal = $chart->donutChart($canalData, 90, $canalColors);
        $svgSetores = $chart->horizontalBars($setorData, 680, max(count($setorData) * 16, 60));
    @endphp

    @php
        $donuts = [
            [
                'svg' => $svgStatus,
                'title' => 'Por Status',
                'items' => Chamado::STATUS,
                'counts' => $porStatus,
                'colors' => $statusColors,
            ],
            [
                'svg' => $svgPrio,
                'title' => 'Por Prioridade',
                'items' => Chamado::PRIORIDADE,
                'counts' => $porPrioridade,
                'colors' => $prioColors,
            ],
            [
                'svg' => $svgTipo,
                'title' => 'Por Tipo',
                'items' => Chamado::TIPO,
                'counts' => $porTipo,
                'colors' => $tipoColors,
            ],
            [
                'svg' => $svgCanal,
                'title' => 'Por Canal',
                'items' => Chamado::CANAL,
                'counts' => $porCanal,
                'colors' => $canalColors,
            ],
        ];
    @endphp
    <table style="margin-bottom:20px;border-collapse:collapse;">
        <tr>
            @foreach ($donuts as $idx => $d)
                @php
                    $borderR = $idx < 3 ? 'border-right:1px solid #e5e7eb;' : '';
                    $padL = $idx > 0 ? 'padding-left:10px;' : '';
                    $padR = $idx < 3 ? 'padding-right:10px;' : '';
                @endphp
                <td style="width:25%;vertical-align:top;{{ $padL }}{{ $padR }}{{ $borderR }}">
                    <div
                        style="font-weight:bold;font-size:11px;border-left:3px solid #1a1a2e;padding-left:5px;margin-bottom:6px;">
                        {{ $d['title'] }}</div>
                    <div style="text-align:center;">
                        {!! $d['svg'] !!}
                    </div>
                    <table style="width:100%;border-collapse:collapse;margin-top:4px;margin-bottom:0;">
                        @php $ci = 0; @endphp
                        @foreach ($d['items'] as $v => $l)
                            @php $q = $d['counts'][$v] ?? 0; @endphp
                            @if ($q > 0)
                                @php $p = $total > 0 ? round($q / $total * 100, 1) : 0; @endphp
                                <tr>
                                    <td style="padding:2px 3px;border:none;font-size:10px;white-space:nowrap;">
                                        <span
                                            style="display:inline-block;width:9px;height:9px;background:{{ $d['colors'][$ci] ?? '#ccc' }};border-radius:2px;margin-right:3px;"></span>{{ __($l) }}
                                    </td>
                                    <td
                                        style="padding:2px 3px;border:none;font-size:10px;text-align:right;white-space:nowrap;">
                                        <strong>{{ $q }}</strong> ({{ $p }}%)
                                    </td>
                                </tr>
                                @php $ci++; @endphp
                            @endif
                        @endforeach
                    </table>
                </td>
            @endforeach
        </tr>
    </table>

    <div style="font-weight:bold;font-size:11px;border-left:3px solid #1a1a2e;padding-left:5px;margin-bottom:6px;">
        Volume por Setor</div>
    <div style="text-align:center;margin-bottom:25px;">
        {!! $svgSetores !!}
    </div>

    <div style="font-weight:bold;font-size:11px;border-left:3px solid #1a1a2e;padding-left:5px;margin:10px 0 5px;">
        Chamados por Setor</div>
    <table>
        <thead>
            <tr>
                <th>Setor</th>
                <th class="text-right">Total</th>
                <th class="text-right">Atend.</th>
                <th class="text-right">Pend.</th>
                <th class="text-right">Em And.</th>
                <th class="text-right">%</th>
            </tr>
        </thead>
        <tbody>
            @forelse ($porSetor as $row)
                @php $pct = $total > 0 ? round($row['total'] / $total * 100, 1) : 0; @endphp
                <tr>
                    <td class="fw-bold">{{ $row['nome'] }}</td>
                    <td class="text-right fw-bold">{{ $row['total'] }}</td>
                    <td class="text-right">{{ $row['atendidos'] }}</td>
                    <td class="text-right">{{ $row['pendentes'] }}</td>
                    <td class="text-right">{{ $row['em_andamento'] }}</td>
                    <td class="text-right text-muted">{{ $pct }}%</td>
                </tr>
            @empty
                <tr>
                    <td colspan="6" class="text-center text-muted">Nenhum dado encontrado.</td>
                </tr>
            @endforelse
        </tbody>
        <tfoot>
            <tr>
                <td>TOTAL</td>
                <td class="text-right">{{ $total }}</td>
                <td class="text-right">{{ $porStatus['atendido'] ?? 0 }}</td>
                <td class="text-right">{{ $porStatus['pendente'] ?? 0 }}</td>
                <td class="text-right">{{ $porStatus['em_andamento'] ?? 0 }}</td>
                <td class="text-right">100%</td>
            </tr>
        </tfoot>
    </table>

    <div style="font-weight:bold;font-size:11px;border-left:3px solid #1a1a2e;padding-left:5px;margin:10px 0 5px;">
        Chamados por Assunto</div>
    <table>
        <thead>
            <tr>
                <th>Assunto</th>
                <th>Setor</th>
                <th class="text-right">Total</th>
                <th class="text-right">Atend.</th>
                <th class="text-right">%</th>
            </tr>
        </thead>
        <tbody>
            @forelse ($porAssunto as $row)
                <tr>
                    <td>{{ $row['nome'] }}</td>
                    <td class="text-muted">{{ $row['setor'] }}</td>
                    <td class="text-right fw-bold">{{ $row['total'] }}</td>
                    <td class="text-right">{{ $row['atendidos'] }}</td>
                    <td class="text-right">{{ $total > 0 ? round(($row['total'] / $total) * 100, 1) : 0 }}%</td>
                </tr>
            @empty
                <tr>
                    <td colspan="5" class="text-center text-muted">Nenhum dado encontrado.</td>
                </tr>
            @endforelse
        </tbody>
    </table>

    <div style="font-weight:bold;font-size:11px;border-left:3px solid #1a1a2e;padding-left:5px;margin:10px 0 5px;">
        Chamados por Subassunto</div>
    <table>
        <thead>
            <tr>
                <th>Assunto &rsaquo; Subassunto</th>
                <th class="text-right">Total</th>
                <th class="text-right">Atend.</th>
                <th class="text-right">%</th>
            </tr>
        </thead>
        <tbody>
            @forelse ($porSubassunto as $row)
                <tr>
                    <td>{{ $row['chave'] }}</td>
                    <td class="text-right fw-bold">{{ $row['total'] }}</td>
                    <td class="text-right">{{ $row['atendidos'] }}</td>
                    <td class="text-right">{{ $total > 0 ? round(($row['total'] / $total) * 100, 1) : 0 }}%</td>
                </tr>
            @empty
                <tr>
                    <td colspan="4" class="text-center text-muted">Nenhum dado encontrado.</td>
                </tr>
            @endforelse
        </tbody>
    </table>

    <div class="footer">Sistema de Indicadores de TI – Confidencial</div>

    <script type="text/php">
    if (isset($pdf)) {
        $font = $fontMetrics->get_font("DejaVu Sans", "normal");
        $w    = $pdf->get_width();
        $h    = $pdf->get_height();
        $pdf->page_text($w / 2 - 15, $h - 16, "Página {PAGE_NUM} / {PAGE_COUNT}", $font, 6, [0.5, 0.5, 0.5]);
    }
</script>

</body>

</html>
