<?php
namespace App\Http\Controllers\Tabelas;
 
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
 
class RecordsController extends Controller
{
    public function index(Request $request)
    {
        $busca = trim($request->input('q', ''));
 
        $query = DB::table('records')->orderBy('category');
        if ($busca) {
            $query->where(function($q) use ($busca) {
                $q->where('category',     'like', "%{$busca}%")
                  ->orWhere('callsign_ant','like', "%{$busca}%")
                  ->orWhere('callsign_atu','like', "%{$busca}%");
            });
        }
 
        $records = $query->get();
        $total   = DB::table('records')->count();
        $comAnt  = DB::table('records')
                     ->whereNotNull('callsign_ant')
                     ->where('callsign_ant', '!=', '')
                     ->count();
        $semAnt  = $total - $comAnt;
 
        return view('tabelas.records', compact('records','busca','total','comAnt','semAnt'));
    }
 
    /** Baixar CSV modelo com todas as categorias */
    public function modelo()
    {
        $records  = DB::table('records')->orderBy('category')->get();
        $filename = 'records_modelo_' . date('Ymd') . '.csv';
        $headers  = [
            'Content-Type'        => 'text/csv; charset=UTF-8',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];
        $callback = function() use ($records) {
            $out = fopen('php://output', 'w');
            fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($out, ['CATEGORIA','CALLSIGN_ANT','NOME_ANT','FINAL_SCORE_ANT'], ';');
            foreach ($records as $r) {
                fputcsv($out, [
                    $r->category,
                    $r->callsign_ant    ?? '',
                    $r->name_ant        ?? '',
                    $r->final_score_ant ?? 0,
                ], ';');
            }
            fclose($out);
        };
        return response()->stream($callback, 200, $headers);
    }
 
    public function edit(int $id)
    {
        $record = DB::table('records')->where('id', $id)->first();
        abort_if(!$record, 404);
        return view('tabelas.records-edit', compact('record'));
    }
 
    public function update(Request $request, int $id)
    {
        $dados = $request->validate([
            'callsign_ant'    => 'nullable|string|max:32',
            'name_ant'        => 'nullable|string|max:30',
            'final_score_ant' => 'nullable|integer|min:0',
        ]);
 
        $dados['callsign_ant']    = strtoupper(trim($dados['callsign_ant'] ?? ''));
        $dados['name_ant']        = strtoupper(trim($dados['name_ant']     ?? ''));
        $dados['final_score_ant'] = (int)($dados['final_score_ant']        ?? 0);
 
        DB::table('records')->where('id', $id)->update($dados);
 
        activity()->causedBy(auth()->user())
            ->log("Record #{$id} atualizado: {$dados['callsign_ant']} score={$dados['final_score_ant']}");
 
        return redirect()->route('tabelas.records.index')
            ->with('sucesso', 'Record atualizado com sucesso.');
    }
 
    /** Importar CSV: CATEGORIA;CALLSIGN;NOME;SCORE */
    public function importar(Request $request)
    {
        $request->validate(['csv' => 'required|file|mimes:csv,txt|max:512']);
 
        $fp    = fopen($request->file('csv')->getRealPath(), 'r');
        $ok    = 0;
        $erros = [];
        $linha = 0;
 
        while (($row = fgetcsv($fp, 0, ';')) !== false) {
            $linha++;
            if ($linha === 1 && stripos($row[0] ?? '', 'categ') !== false) {
                continue; // pular cabeçalho
            }
            if (count($row) < 4) {
                $erros[] = "Linha {$linha}: colunas insuficientes.";
                continue;
            }
 
            $cat   = strtoupper(trim($row[0]));
            $call  = strtoupper(trim($row[1]));
            $nome  = strtoupper(trim($row[2]));
            $score = (int)trim($row[3]);
 
            $record = DB::table('records')->where('category', $cat)->first();
            if (!$record) {
                DB::table('records')->insert([
                    'category'        => $cat,
                    'callsign_ant'    => $call,
                    'name_ant'        => $nome,
                    'final_score_ant' => $score,
                    'callsign_atu'    => '',
                    'name_atu'        => '',
                    'final_score_atu' => 0,
                ]);
            } else {
                DB::table('records')->where('category', $cat)->update([
                    'callsign_ant'    => $call,
                    'name_ant'        => $nome,
                    'final_score_ant' => $score,
                ]);
            }
            $ok++;
        }
        fclose($fp);
 
        activity()->causedBy(auth()->user())
            ->log("Records importados: {$ok} linhas, " . count($erros) . " erros.");
 
        $msg = "{$ok} registro(s) importado(s).";
        if ($erros) {
            $msg .= ' Erros: ' . implode('; ', array_slice($erros, 0, 5));
        }
 
        return back()->with('sucesso', $msg);
    }
 
    /** Limpar campos _ant de todos os records */
    public function limparAnt(Request $request)
    {
        $request->validate(
            ['confirmacao' => 'required|in:LIMPAR'],
            ['confirmacao.in' => 'Digite exatamente LIMPAR (maiúsculas) para confirmar.']
        );
 
        DB::table('records')->update([
            'callsign_ant'    => '',
            'name_ant'        => '',
            'final_score_ant' => 0,
        ]);
 
        activity()->causedBy(auth()->user())->log('Records: campos _ant limpos.');
 
        return back()->with('sucesso', 'Campos de record anterior limpos com sucesso.');
    }
}