@extends('layouts.app')
@section('title','Gestão de Contests')
@section('content')

@php use App\Models\ContestDate; @endphp

{{-- Mensagens --}}
@if(session('sucesso'))
    <div class="alert alert-success" style="margin-bottom:1rem">✅ {{ session('sucesso') }}</div>
@endif
@if(session('erro'))
    <div class="alert alert-danger" style="margin-bottom:1rem">❌ {{ session('erro') }}</div>
@endif

<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.75rem;margin-bottom:1.5rem">
    <h2 style="margin:0">🗂️ Gestão de Contests</h2>
    <div style="display:flex;gap:.5rem">
        <a href="{{ route('gestao.contests.criar') }}" class="btn btn-primary">+ Criar Próximo</a>
        <a href="{{ route('dashboard') }}" class="btn btn-secondary">← Dashboard</a>
    </div>
</div>

{{-- Toggle Ativação Automática --}}
<div style="background:#fff;border-radius:var(--radius);padding:1rem 1.25rem;
            box-shadow:0 2px 8px rgba(0,0,0,.06);margin-bottom:1.75rem;
            display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:.75rem">
    <div>
        <strong>⚙️ Ativação Automática por Data</strong>
        <p style="margin:.25rem 0 0;font-size:.83rem;color:var(--muted);max-width:520px">
            Quando <strong>ligada</strong>, o sistema ativa automaticamente o contest Futuro
            quando o dia de <code>inicio_log</code> chegar (via cron diário às 00:05).
            Requer <strong>Task Scheduler do Windows</strong> configurado.
        </p>
        @if($autoAtivar)
        <div style="margin-top:.5rem;background:#e8f5e9;border-radius:4px;padding:.4rem .7rem;font-size:.78rem;color:#2E7D32">
            Comando para o Task Scheduler (rodar a cada 1 minuto):<br>
            <code>php C:\laragon\www\projetos\labre-contest\artisan schedule:run</code>
        </div>
        @endif
    </div>
    <form method="POST" action="{{ route('gestao.contests.toggle-auto') }}" style="flex-shrink:0">
        @csrf
        <button type="submit"
            class="btn {{ $autoAtivar ? 'btn-primary' : 'btn-secondary' }}"
            style="{{ $autoAtivar ? 'background:#2E7D32;border-color:#2E7D32' : '' }}">
            {{ $autoAtivar ? '✅ Automático — LIGADO' : '⛔ Automático — DESLIGADO' }}
        </button>
    </form>
</div>

{{-- Legenda de flags --}}
<div style="display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:1.25rem;font-size:.8rem">
    @foreach(ContestDate::FLAG_LABELS as $f => $info)
    <span style="background:{{ $info['bg'] }};color:{{ $info['cor'] }};border:1px solid {{ $info['cor'] }};
                 border-radius:20px;padding:.2rem .75rem;font-weight:bold">
        {{ $f }} — {{ $info['label'] }}
    </span>
    @endforeach
</div>

{{-- Lista de contests --}}
@forelse($contests as $c)
@php
    $fi        = ContestDate::FLAG_LABELS[$c->flag] ?? ['label'=>'?','cor'=>'#333','bg'=>'#f5f5f5'];
    $ep        = $etapasPorContest[$c->id] ?? null;
    $progresso = $ep ? (int)(($ep->concluidas / max($ep->total, 1)) * 100) : 0;
    $ano       = $c->start_date->format('Y');
@endphp
<div style="background:#fff;border-radius:var(--radius);box-shadow:0 2px 8px rgba(0,0,0,.06);
            margin-bottom:1rem;border-left:5px solid {{ $fi['cor'] }}">

    {{-- Cabeçalho --}}
    <div style="padding:.85rem 1.25rem;display:flex;align-items:center;
                justify-content:space-between;flex-wrap:wrap;gap:.5rem">
        <div style="display:flex;align-items:center;gap:.75rem">
            <span style="background:{{ $fi['bg'] }};color:{{ $fi['cor'] }};
                         border:1px solid {{ $fi['cor'] }};border-radius:20px;
                         padding:.2rem .75rem;font-size:.8rem;font-weight:bold;white-space:nowrap">
                {{ $fi['label'] }}
            </span>
            <div>
                <strong style="font-size:1rem">{{ $c->name }} {{ $ano }}</strong>
                <span style="color:var(--muted);font-size:.8rem;margin-left:.4rem">#{{ $c->id }}</span>
            </div>
        </div>
        <div style="font-size:.82rem;color:var(--muted);text-align:right;line-height:1.5">
            📅 Contest: {{ $c->start_date->format('d/m/Y H:i') }} – {{ $c->end_date->format('d/m/Y H:i') }} UTC<br>
            📤 Envio: {{ \Carbon\Carbon::parse($c->inicio_log)->format('d/m/Y') }}
               até {{ \Carbon\Carbon::parse($c->limit_log)->format('d/m/Y') }}
        </div>
    </div>

    {{-- Barra de progresso etapas --}}
    @if($ep && $ep->total > 0)
    <div style="padding:0 1.25rem .6rem">
        <div style="display:flex;justify-content:space-between;font-size:.75rem;color:var(--muted);margin-bottom:.25rem">
            <span>Etapas concluídas: {{ $ep->concluidas }}/{{ $ep->total }}</span>
            <span>{{ $progresso }}%</span>
        </div>
        <div style="background:#e9ecef;border-radius:50px;height:8px">
            <div style="width:{{ $progresso }}%;height:100%;border-radius:50px;
                        background:{{ $progresso == 100 ? '#2E7D32' : 'var(--blue)' }}"></div>
        </div>
    </div>
    @endif

    {{-- Ações --}}
    <div style="background:#f8f9fa;border-top:1px solid #eee;padding:.65rem 1.25rem;
                display:flex;gap:.5rem;flex-wrap:wrap;align-items:center">

        {{-- ATIVAR --}}
        @if(in_array($c->flag, [ContestDate::FLAG_FUTURO, ContestDate::FLAG_ENCERRADO]))
        <form method="POST" action="{{ route('gestao.contests.ativar', $c->id) }}"
              onsubmit="return confirm('Ativar o contest #{{ $c->id }} — {{ $c->name }} {{ $ano }}?\n\nO contest ativo atual será suspenso.')">
            @csrf
            <button type="submit" class="btn btn-primary" style="padding:.35rem .85rem;font-size:.82rem">
                ▶ Ativar
            </button>
        </form>
        @elseif($c->flag === ContestDate::FLAG_ATIVO)
        <span class="btn btn-primary" style="padding:.35rem .85rem;font-size:.82rem;opacity:.65;cursor:default">
            ✅ Ativo
        </span>
        @endif

        {{-- REPROCESSAR --}}
        @if($c->flag === ContestDate::FLAG_ENCERRADO)
        <button type="button" class="btn btn-secondary"
                style="padding:.35rem .85rem;font-size:.82rem"
                onclick="toggleForm('reprocess-{{ $c->id }}')">
            🔄 Reprocessar
        </button>
        <form id="reprocess-{{ $c->id }}" method="POST"
              action="{{ route('gestao.contests.reprocessar', $c->id) }}"
              style="display:none;gap:.35rem;align-items:center">
            @csrf
            <input type="text" name="confirmacao" placeholder="Digite REPROCESSAR"
                   style="padding:.35rem .6rem;border:1px solid #ccc;border-radius:4px;font-size:.82rem;width:180px">
            <button type="submit" class="btn btn-secondary"
                    style="padding:.35rem .75rem;font-size:.82rem">Confirmar</button>
            <button type="button" onclick="toggleForm('reprocess-{{ $c->id }}')"
                    style="background:none;border:none;cursor:pointer;color:#aaa;font-size:.85rem">✕</button>
        </form>
        @endif

        {{-- ARQUIVAR --}}
        @if($c->flag === ContestDate::FLAG_ENCERRADO)
        <button type="button"
                style="padding:.35rem .85rem;font-size:.82rem;background:#C62828;color:#fff;
                       border:1px solid #C62828;border-radius:var(--radius);cursor:pointer"
                onclick="toggleForm('arquivar-{{ $c->id }}')">
            📦 Arquivar
        </button>
        <form id="arquivar-{{ $c->id }}" method="POST"
              action="{{ route('gestao.contests.arquivar', $c->id) }}"
              style="display:none;gap:.35rem;align-items:center">
            @csrf
            <span style="font-size:.78rem;color:#C62828;font-weight:bold">⚠️ Remove dados do banco!</span>
            <input type="text" name="confirmacao" placeholder="Digite ARQUIVAR"
                   style="padding:.35rem .6rem;border:1px solid #C62828;border-radius:4px;font-size:.82rem;width:160px">
            <button type="submit"
                    style="padding:.35rem .75rem;font-size:.82rem;background:#C62828;color:#fff;
                           border:1px solid #C62828;border-radius:var(--radius);cursor:pointer">
                Confirmar
            </button>
            <button type="button" onclick="toggleForm('arquivar-{{ $c->id }}')"
                    style="background:none;border:none;cursor:pointer;color:#aaa;font-size:.85rem">✕</button>
        </form>
        @endif

        @if($c->flag === ContestDate::FLAG_ARQUIVADO)
        <span style="font-size:.8rem;color:#aaa">📁 Dados em backup — storage/app/backup/</span>
        @endif
    </div>
</div>
@empty
<p style="color:var(--muted);text-align:center;padding:2rem">
    Nenhum contest cadastrado. <a href="{{ route('gestao.contests.criar') }}">Criar o primeiro</a>.
</p>
@endforelse

<script>
function toggleForm(id) {
    const el = document.getElementById(id);
    const visible = el.style.display !== 'none';
    el.style.display = visible ? 'none' : 'flex';
    if (!visible) el.querySelector('input')?.focus();
}
</script>
@endsection
