<x-admin-layout title="Propostas Comerciais — OPCON">

<div x-data="propostasApp()" x-init="init()">

    {{-- Header --}}
    <div style="display:flex; align-items:flex-start; justify-content:space-between; gap:1rem; margin-bottom:1.5rem; flex-wrap:wrap;">
        <div>
            <h1 style="font-size:1.375rem; font-weight:700; color:#1e3a5f; margin:0;">Propostas Comerciais</h1>
            <p style="font-size:0.8125rem; color:#64748b; margin:0.25rem 0 0;">Gere, envie e acompanhe propostas com link de aceite digital</p>
        </div>
        <button @click="openCreate()"
                style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1.125rem; background:#1e3a5f; color:#fff; border:none; border-radius:9px; font-size:0.875rem; font-weight:600; cursor:pointer; font-family:inherit; transition:background 0.15s;"
                onmouseover="this.style.background='#162d4a'" onmouseout="this.style.background='#1e3a5f'">
            <svg style="width:15px;height:15px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
            Nova proposta
        </button>
    </div>

    {{-- Table --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; overflow:hidden;">
        <div style="overflow-x:auto;">
        <table style="width:100%; border-collapse:collapse; min-width:640px;">
            <thead>
                <tr style="background:#f8fafc; border-bottom:1px solid #e2e8f0;">
                    <th style="padding:0.75rem 1rem; text-align:left; font-size:0.7rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Cliente</th>
                    <th style="padding:0.75rem 1rem; text-align:left; font-size:0.7rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Regime</th>
                    <th style="padding:0.75rem 1rem; text-align:left; font-size:0.7rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Honorário</th>
                    <th style="padding:0.75rem 1rem; text-align:left; font-size:0.7rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Validade</th>
                    <th style="padding:0.75rem 1rem; text-align:left; font-size:0.7rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Status</th>
                    <th style="padding:0.75rem 1rem; text-align:right; font-size:0.7rem; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Ações</th>
                </tr>
            </thead>
            <tbody>
                @forelse($propostas as $p)
                <tr style="border-bottom:1px solid #f1f5f9;" onmouseover="this.style.background='#fafafa'" onmouseout="this.style.background=''">
                    <td style="padding:0.875rem 1rem;">
                        <p style="font-size:0.875rem; font-weight:700; color:#1e3a5f; margin:0;">{{ $p->razao_social }}</p>
                        <p style="font-size:0.7rem; color:#94a3b8; margin:0;">{{ $p->email }}</p>
                        @if($p->lead)
                            <span style="font-size:0.6875rem; font-weight:600; padding:0.125rem 0.5rem; border-radius:100px; background:#eff6ff; color:#2563eb; margin-top:0.25rem; display:inline-block;">
                                Lead: {{ $p->lead->name }}
                            </span>
                        @endif
                        @if($p->contrato)
                            <span style="font-size:0.6875rem; font-weight:600; padding:0.125rem 0.5rem; border-radius:100px; background:#f0fdf4; color:#16a34a; margin-top:0.25rem; display:inline-block;">
                                Contrato #{{ $p->contrato->id }}
                            </span>
                        @endif
                    </td>
                    <td style="padding:0.875rem 1rem; font-size:0.8125rem; color:#374151;">{{ Str::limit($p->regime_tributario, 28) }}</td>
                    <td style="padding:0.875rem 1rem; font-size:0.9375rem; font-weight:800; color:#1e3a5f;">R$ {{ number_format($p->honorario_final, 2, ',', '.') }}</td>
                    <td style="padding:0.875rem 1rem; font-size:0.8125rem; color:{{ $p->validade->isPast() ? '#dc2626' : '#374151' }};">{{ $p->validade->format('d/m/Y') }}</td>
                    <td style="padding:0.875rem 1rem;">
                        <span style="font-size:0.7rem; font-weight:700; padding:0.2rem 0.625rem; border-radius:20px; background:{{ $p->status_bg }}; color:{{ $p->status_color }}; text-transform:capitalize;">{{ $p->status }}</span>
                        @if($p->aceita_em)
                            <p style="font-size:0.7rem; color:#25b87e; margin:0.2rem 0 0;">{{ $p->aceita_em->format('d/m/Y H:i') }}</p>
                        @endif
                    </td>
                    <td style="padding:0.875rem 1rem; text-align:right;">
                        <div style="display:inline-flex; gap:0.375rem; align-items:center;">
                            <a href="{{ route('admin.propostas.pdf', $p) }}"
                               style="display:inline-flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:7px; background:#eff6ff; color:#2563eb; text-decoration:none; transition:background 0.15s;"
                               title="Baixar PDF" onmouseover="this.style.background='#dbeafe'" onmouseout="this.style.background='#eff6ff'">
                                <svg style="width:13px;height:13px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                            </a>
                            @if($p->status === 'rascunho')
                            <button @click="enviar({{ $p->id }})"
                                    style="display:inline-flex; align-items:center; gap:0.25rem; padding:0.275rem 0.625rem; border-radius:7px; background:#f0fdf4; color:#25b87e; border:none; cursor:pointer; font-size:0.75rem; font-weight:600; font-family:inherit;">
                                <svg style="width:12px;height:12px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                                Enviar
                            </button>
                            @endif
                            @if($p->status === 'aceita' && !$p->contrato)
                            <button @click="converterContrato({{ $p->id }})"
                                    style="display:inline-flex; align-items:center; gap:0.25rem; padding:0.275rem 0.625rem; border-radius:7px; background:#eff6ff; color:#1e3a5f; border:none; cursor:pointer; font-size:0.75rem; font-weight:600; font-family:inherit;"
                                    title="Converter em contrato">
                                <svg style="width:12px;height:12px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                                Contrato
                            </button>
                            @endif
                            <button @click="deletar({{ $p->id }})"
                                    style="display:inline-flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:7px; background:#fef2f2; color:#dc2626; border:none; cursor:pointer;"
                                    onmouseover="this.style.background='#fee2e2'" onmouseout="this.style.background='#fef2f2'">
                                <svg style="width:13px;height:13px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                            </button>
                        </div>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="6" style="padding:3rem; text-align:center; color:#94a3b8;">
                        <svg style="width:40px;height:40px;margin:0 auto 0.75rem;display:block;color:#cbd5e1;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                        Nenhuma proposta ainda
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>
        </div>
    </div>
    @if($propostas->hasPages())
    <div style="margin-top:1rem;">{{ $propostas->links() }}</div>
    @endif

    {{-- Modal Nova Proposta --}}
    <div x-show="showCreate" x-transition.opacity
         style="position:fixed; inset:0; z-index:200; background:rgba(15,23,42,0.55); backdrop-filter:blur(3px);"
         @keydown.escape.window="showCreate=false" x-cloak>
        <div style="display:flex; align-items:center; justify-content:center; min-height:100%; width:100%; padding:1rem;">
        <div @click.stop x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
             style="background:#fff; border-radius:18px; width:100%; max-width:580px; box-shadow:0 25px 50px rgba(0,0,0,0.18); overflow:hidden; max-height:90vh; overflow-y:auto;">
            <div style="background:#1e3a5f; padding:1.25rem 1.5rem; display:flex; align-items:center; justify-content:space-between; position:sticky; top:0; z-index:10;">
                <div>
                    <h2 style="font-size:1rem; font-weight:700; color:#fff; margin:0;">Nova proposta comercial</h2>
                    <p style="font-size:0.75rem; color:rgba(255,255,255,0.65); margin:0.2rem 0 0;">Preencha os dados e gere o PDF ou envie por e-mail</p>
                </div>
                <button @click="showCreate=false" style="width:32px;height:32px;border-radius:8px;background:rgba(255,255,255,0.12);border:none;color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;">
                    <svg style="width:16px;height:16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                </button>
            </div>
            <form @submit.prevent="saveProposta()" style="padding:1.5rem; display:flex; flex-direction:column; gap:1rem;">
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem;">
                    <div style="grid-column:span 2;">
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">Razão Social / Nome <span style="color:#ef4444;">*</span></label>
                        <input type="text" x-model="form.razao_social" required placeholder="Empresa ou nome do cliente"
                               style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">E-mail <span style="color:#ef4444;">*</span></label>
                        <input type="email" x-model="form.email" required style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">Telefone</label>
                        <input type="text" x-model="form.telefone" style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">CNPJ / CPF</label>
                        <input type="text" x-model="form.cnpj" style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">Regime tributário <span style="color:#ef4444;">*</span></label>
                        <input type="text" x-model="form.regime_tributario" required placeholder="Simples Nacional, Lucro Presumido…" style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem;">
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">Honorário calculado (R$)</label>
                        <input type="number" x-model="form.honorario_calculado" min="0" step="0.01" style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">Honorário final (R$) <span style="color:#ef4444;">*</span></label>
                        <input type="number" x-model="form.honorario_final" required min="0" step="0.01" style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                    <div style="grid-column:span 2;">
                        <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">Válida até <span style="color:#ef4444;">*</span></label>
                        <input type="date" x-model="form.validade" required style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"/>
                    </div>
                </div>
                <div>
                    <label style="display:block; font-size:0.75rem; font-weight:700; color:#1e3a5f; margin-bottom:0.4rem; text-transform:uppercase; letter-spacing:0.04em;">Observações</label>
                    <textarea x-model="form.observacoes" rows="3" placeholder="Condições especiais, escopo dos serviços…"
                              style="width:100%; padding:0.625rem 0.875rem; border:1.5px solid #e2e8f0; border-radius:10px; font-size:0.875rem; color:#1e3a5f; font-family:inherit; box-sizing:border-box; resize:vertical;" onfocus="this.style.borderColor='#1e3a5f'" onblur="this.style.borderColor='#e2e8f0'"></textarea>
                </div>
                <div x-show="formError" style="background:#fef2f2; border:1px solid #fecaca; border-radius:8px; padding:0.625rem 0.875rem;">
                    <p style="font-size:0.8125rem; color:#dc2626; margin:0;" x-text="formError"></p>
                </div>
                <div style="display:flex; justify-content:flex-end; gap:0.625rem; padding-top:0.25rem; border-top:1px solid #f1f5f9;">
                    <button type="button" @click="showCreate=false" style="padding:0.5625rem 1rem; background:#f1f5f9; color:#64748b; border:none; border-radius:9px; font-size:0.875rem; font-weight:600; cursor:pointer; font-family:inherit;">Cancelar</button>
                    <button type="submit" :disabled="saving" style="padding:0.5625rem 1.25rem; background:#1e3a5f; color:#fff; border:none; border-radius:9px; font-size:0.875rem; font-weight:600; cursor:pointer; font-family:inherit;" :style="saving?'opacity:0.6':''" x-text="saving?'Salvando…':'Criar proposta'"></button>
                </div>
            </form>
        </div>
        </div>
    </div>

</div>

<script>
function propostasApp() {
    return {
        showCreate: false,
        saving: false,
        formError: '',
        form: { razao_social:'', cnpj:'', email:'', telefone:'', regime_tributario:'', honorario_calculado:0, honorario_final:0, observacoes:'', validade:'' },

        init() {
            const d = new Date(); d.setDate(d.getDate() + 30);
            this.form.validade = d.toISOString().slice(0,10);
        },

        openCreate() {
            this.formError = '';
            this.init();
            this.showCreate = true;
        },

        async saveProposta() {
            this.saving = true; this.formError = '';
            try {
                const r = await fetch('{{ route('admin.propostas.store') }}', {
                    method:'POST',
                    headers:{ 'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}','Accept':'application/json' },
                    body: JSON.stringify(this.form),
                });
                const data = await r.json();
                if (data.ok) {
                    this.showCreate = false; window.location.reload();
                } else if (data.errors) {
                    this.formError = Object.values(data.errors).flat().join(' ');
                } else {
                    this.formError = data.message || 'Erro ao criar proposta.';
                }
            } catch(e) { this.formError = 'Erro de conexão.'; }
            finally { this.saving = false; }
        },

        async enviar(id) {
            if (!confirm('Enviar proposta por e-mail para o cliente?')) return;
            const r = await fetch(`/admin/propostas/${id}/enviar`, {
                method:'POST', headers:{ 'X-CSRF-TOKEN':'{{ csrf_token() }}','Accept':'application/json' }
            });
            const data = await r.json();
            if (data.ok) { alert('Proposta enviada com sucesso!'); window.location.reload(); }
        },

        async converterContrato(id) {
            if (!confirm('Criar contrato a partir desta proposta?\n\nO contrato será criado em status "Rascunho" para que você preencha os demais dados.')) return;
            const r = await fetch(`/admin/propostas/${id}/contrato`, {
                method:'POST', headers:{ 'X-CSRF-TOKEN':'{{ csrf_token() }}','Accept':'application/json','Content-Type':'application/json' },
                body:'{}'
            });
            const data = await r.json();
            if (data.ok) {
                alert('Contrato criado com sucesso!');
                window.location.href = '{{ route('contratos.index') }}';
            } else {
                alert(data.message || 'Erro ao criar contrato.');
            }
        },

        async deletar(id) {
            if (!confirm('Excluir esta proposta?')) return;
            const r = await fetch(`/admin/propostas/${id}`, {
                method:'DELETE', headers:{ 'X-CSRF-TOKEN':'{{ csrf_token() }}','Accept':'application/json' }
            });
            const data = await r.json();
            if (data.ok) window.location.reload();
        },
    };
}
</script>

</x-admin-layout>
