<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }
$page_title = 'Vale Admin — WhatsApp';
ob_start();
?>
<div class="dashboard-container">
    <?php $adminNav = 'whatsapp'; require __DIR__ . '/sidebar.php'; ?>

    <main class="main-content">
        <header class="header-bar">
            <h2>WhatsApp Business</h2>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 2rem;max-width:860px;">

            <?php if ($waNotice): ?>
            <div style="background:rgba(30,122,77,.08);border:1px solid rgba(30,122,77,.25);border-radius:8px;padding:.85rem 1.1rem;margin-bottom:1.25rem;font-size:.88rem;color:#1E7A4D;font-weight:600;">
                <?= htmlspecialchars($waNotice) ?>
            </div>
            <?php endif; ?>

            <?php if ($waError): ?>
            <div style="background:rgba(168,51,26,.07);border:1px solid rgba(168,51,26,.25);border-radius:8px;padding:.85rem 1.1rem;margin-bottom:1.25rem;font-size:.88rem;color:#A8331A;">
                <strong><?= htmlspecialchars($waError) ?></strong>
                <?php if (stripos($waError, 'auth') !== false || stripos($waError, 'token') !== false || stripos($waError, '190') !== false): ?>
                <br><span style="font-weight:400;font-size:.82rem;">El token de acceso venció o es inválido. Generá uno nuevo en Meta Business Manager y actualizalo en el formulario <strong>"Agregar / actualizar credencial"</strong> de abajo.</span>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- ── Webhook info ──────────────────────────────────────────────── -->
            <section style="background:#fff;border:1px solid #E6DDCE;border-radius:12px;padding:1.4rem 1.5rem;margin-bottom:1.25rem;">
                <h3 style="font-size:.92rem;font-weight:700;margin-bottom:1rem;padding-bottom:.75rem;border-bottom:1px solid #E6DDCE;">Configuración de Webhook</h3>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                    <div>
                        <p style="font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">URL del Webhook (Meta panel)</p>
                        <code style="display:block;background:#F6F0E6;padding:.6rem .8rem;border-radius:6px;font-size:.8rem;word-break:break-all;"><?= htmlspecialchars($webhookUrl) ?></code>
                    </div>
                    <div>
                        <p style="font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Verify Token</p>
                        <code style="display:block;background:#F6F0E6;padding:.6rem .8rem;border-radius:6px;font-size:.8rem;"><?= htmlspecialchars($verifyToken) ?></code>
                    </div>
                </div>
                <p style="font-size:.78rem;color:#8C8275;margin-top:.85rem;">
                    En el panel de Meta: <strong>WhatsApp → Configuración → Webhooks</strong> · Suscribí al evento <code>messages</code>.
                </p>
            </section>

            <!-- ── Números configurados ──────────────────────────────────────── -->
            <section style="background:#fff;border:1px solid #E6DDCE;border-radius:12px;padding:1.4rem 1.5rem;margin-bottom:1.25rem;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;padding-bottom:.75rem;border-bottom:1px solid #E6DDCE;">
                    <h3 style="font-size:.92rem;font-weight:700;">Números configurados</h3>
                    <span style="font-size:.78rem;color:#8C8275;"><?= count($waTenants) ?> número<?= count($waTenants) != 1 ? 's' : '' ?></span>
                </div>

                <?php if (empty($waTenants)): ?>
                <div style="padding:1.5rem 0;text-align:center;color:#8C8275;font-size:.88rem;">
                    Sin números configurados aún. Usá el formulario de abajo para agregar uno.
                </div>
                <?php else: ?>
                <table style="width:100%;border-collapse:collapse;font-size:.84rem;">
                    <thead>
                        <tr style="border-bottom:1px solid #E6DDCE;">
                            <th style="text-align:left;padding:.4rem .5rem;font-size:.72rem;color:#8C8275;font-weight:600;">Negocio</th>
                            <th style="text-align:left;padding:.4rem .5rem;font-size:.72rem;color:#8C8275;font-weight:600;">Phone Number ID</th>
                            <th style="text-align:left;padding:.4rem .5rem;font-size:.72rem;color:#8C8275;font-weight:600;">WABA ID</th>
                            <th style="text-align:center;padding:.4rem .5rem;font-size:.72rem;color:#8C8275;font-weight:600;">Estado</th>
                            <th style="text-align:right;padding:.4rem .5rem;font-size:.72rem;color:#8C8275;font-weight:600;">Acción</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($waTenants as $tw): ?>
                    <tr style="border-bottom:1px solid #F6F0E6;">
                        <td style="padding:.55rem .5rem;font-weight:600;">
                            <a href="/admin/tenant?id=<?= $tw['tenant_id'] ?>" style="color:#211C16;text-decoration:none;"><?= htmlspecialchars($tw['tenant_name']) ?></a>
                        </td>
                        <td style="padding:.55rem .5rem;font-family:monospace;font-size:.78rem;color:#5a3a2e;"><?= htmlspecialchars($tw['phone_number_id']) ?></td>
                        <td style="padding:.55rem .5rem;font-family:monospace;font-size:.78rem;color:#8C8275;"><?= htmlspecialchars($tw['waba_id'] ?? '—') ?></td>
                        <td style="padding:.55rem .5rem;text-align:center;">
                            <?php if ($tw['status'] === 'active'): ?>
                            <span style="background:rgba(30,122,77,.1);color:#1E7A4D;border-radius:99px;padding:2px 10px;font-size:.72rem;font-weight:700;">Activo</span>
                            <?php else: ?>
                            <span style="background:#F0EAE2;color:#8C8275;border-radius:99px;padding:2px 10px;font-size:.72rem;font-weight:700;">Inactivo</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding:.55rem .5rem;text-align:right;">
                            <?php if ($tw['status'] === 'active'): ?>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('¿Desactivar este número?')">
                                <input type="hidden" name="action" value="disable_wa">
                                <input type="hidden" name="tw_id" value="<?= $tw['id'] ?>">
                                <button type="submit" style="background:none;border:1px solid #E6DDCE;border-radius:6px;padding:3px 10px;font-size:.72rem;color:#8C8275;cursor:pointer;">Desactivar</button>
                            </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </section>

            <!-- ── Enviar mensaje de prueba ──────────────────────────────────── -->
            <section style="background:#fff;border:1px solid #E6DDCE;border-radius:12px;padding:1.4rem 1.5rem;margin-bottom:1.25rem;">
                <h3 style="font-size:.92rem;font-weight:700;margin-bottom:1rem;padding-bottom:.75rem;border-bottom:1px solid #E6DDCE;">Enviar mensaje de prueba</h3>

                <?php if (empty($waTenants)): ?>
                <p style="color:#8C8275;font-size:.85rem;">Primero configurá al menos un número usando el formulario de abajo.</p>
                <?php else: ?>
                <form method="POST" action="/admin/whatsapp" style="display:flex;flex-wrap:wrap;gap:.85rem;align-items:flex-end;">
                    <input type="hidden" name="action" value="test_wa">

                    <div style="flex:1.5;min-width:180px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Número origen (tenant)</label>
                        <select name="tw_id" style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;background:#fff;">
                            <?php foreach ($waTenants as $tw): if ($tw['status'] !== 'active') continue; ?>
                            <option value="<?= $tw['id'] ?>"><?= htmlspecialchars($tw['tenant_name']) ?> · <?= htmlspecialchars($tw['phone_number_id']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="flex:1;min-width:160px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Destino (sin + ni espacios)</label>
                        <input type="text" name="destino" inputmode="numeric" placeholder="50587654321"
                            style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;box-sizing:border-box;">
                    </div>

                    <div style="min-width:130px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Plantilla</label>
                        <input type="text" name="template" value="hello_world"
                            style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;box-sizing:border-box;">
                    </div>

                    <div style="min-width:130px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Idioma</label>
                        <select name="lang" style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;background:#fff;">
                            <option value="en_US">English (US)</option>
                            <option value="es_MX">Español (MX)</option>
                            <option value="es">Español</option>
                        </select>
                    </div>

                    <div>
                        <button type="submit" style="padding:9px 20px;background:#A8331A;color:#fff;border:none;border-radius:8px;font-size:.84rem;font-weight:700;cursor:pointer;white-space:nowrap;">
                            Enviar plantilla
                        </button>
                    </div>
                </form>
                <?php endif; ?>
            </section>

            <!-- ── Agregar / actualizar credencial ───────────────────────────── -->
            <section style="background:#fff;border:1px solid #E6DDCE;border-radius:12px;padding:1.4rem 1.5rem;margin-bottom:2rem;">
                <h3 style="font-size:.92rem;font-weight:700;margin-bottom:.4rem;">Agregar / actualizar credencial</h3>
                <p style="font-size:.8rem;color:#8C8275;margin-bottom:1rem;">Pegá el token de acceso de Meta directamente aquí. Se encripta antes de guardarse (AES-256-GCM).</p>

                <form method="POST" action="/admin/whatsapp" style="display:flex;flex-wrap:wrap;gap:.85rem;align-items:flex-end;">
                    <input type="hidden" name="action" value="save_wa_credential">

                    <div style="flex:1.5;min-width:180px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Negocio (tenant)</label>
                        <select name="tenant_id" style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;background:#fff;">
                            <option value="">— Seleccioná —</option>
                            <?php foreach ($allTenants as $t): ?>
                            <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="flex:1;min-width:160px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Phone Number ID</label>
                        <input type="text" name="phone_number_id" placeholder="1215781871610651"
                            style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;box-sizing:border-box;">
                    </div>

                    <div style="flex:1;min-width:160px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">WABA ID</label>
                        <input type="text" name="waba_id" placeholder="21312348881066413"
                            style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;box-sizing:border-box;">
                    </div>

                    <div style="flex:2;min-width:220px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:#8C8275;margin-bottom:.3rem;">Access Token de Meta</label>
                        <input type="password" name="access_token" placeholder="EAAx..."
                            style="width:100%;padding:8px 10px;border:1px solid #E6DDCE;border-radius:8px;font-size:.84rem;box-sizing:border-box;font-family:monospace;">
                    </div>

                    <div>
                        <button type="submit" style="padding:9px 20px;background:#3A332E;color:#fff;border:none;border-radius:8px;font-size:.84rem;font-weight:700;cursor:pointer;white-space:nowrap;">
                            Guardar credencial
                        </button>
                    </div>
                </form>
            </section>

        </div>
    </main>
</div>
<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/layout.php';
