<?php

namespace App\Controllers;

use App\Services\ScoreSheetService;

final class ExportController
{
    public function standingsCsv(array $params): void
    {
        $rows = (new ScoreSheetService())->standings((int) $params['id']);
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="tabla-posiciones.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['Equipo', 'PJ', 'G', 'P', 'SF', 'SC', 'Puntos']);
        foreach ($rows as $row) {
            fputcsv($out, [$row['name'], $row['played'], $row['won'], $row['lost'], $row['sets_for'], $row['sets_against'], $row['points']]);
        }
    }

    public function standingsPdf(array $params): void
    {
        $rows = (new ScoreSheetService())->standings((int) $params['id']);
        header('Content-Type: text/html; charset=utf-8');
        echo '<!doctype html><title>Tabla de posiciones</title><style>body{font-family:Arial}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccc;padding:8px}</style>';
        echo '<h1>Tabla de posiciones</h1><p>Usar imprimir / guardar como PDF desde el navegador.</p><table><tr><th>Equipo</th><th>PJ</th><th>G</th><th>P</th><th>SF</th><th>SC</th><th>Pts</th></tr>';
        foreach ($rows as $row) {
            echo sprintf('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',
                htmlspecialchars($row['name']), $row['played'], $row['won'], $row['lost'], $row['sets_for'], $row['sets_against'], $row['points']);
        }
        echo '</table>';
    }
}
