<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

// Vale Admin — super-admin (cross-tenant). Auth lives in the `admins` table,
// separate from `users`, so tenant scoping is never contaminated.
// The ONLY place cross-tenant queries are allowed is here.

require_once dirname(__DIR__) . '/services/slug.php';

$db = DB::connect();
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];

// --- Public: login ---
if ($uri === '/admin/login') {
    if (isset($_SESSION['admin_id'])) {
        header('Location: /admin/dashboard');
        exit;
    }
    $error = '';
    if ($method === 'POST') {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $stmt = $db->prepare("SELECT * FROM admins WHERE email = :email LIMIT 1");
        $stmt->execute([':email' => $email]);
        $admin = $stmt->fetch();
        if ($admin && password_verify($password, $admin['password_hash'])) {
            session_regenerate_id(true);
            $_SESSION = []; // drop any owner session — never mix planes
            $_SESSION['admin_id']    = $admin['id'];
            $_SESSION['admin_name']  = $admin['name'];
            $_SESSION['admin_email'] = $admin['email'];
            header('Location: /admin/dashboard');
            exit;
        }
        $error = 'Credenciales inválidas.';
    }
    require dirname(__DIR__) . '/views/admin/login.php';
    exit;
}

// --- Logout ---
if ($uri === '/admin/logout') {
    $_SESSION = [];
    session_destroy();
    header('Location: /admin/login');
    exit;
}

// --- Everything below requires an admin session ---
if (!isset($_SESSION['admin_id'])) {
    header('Location: /admin/login');
    exit;
}

switch ($uri) {
    case '/admin':
        header('Location: /admin/dashboard');
        exit;

    // ── Dashboard global ──────────────────────────────────────────────────────
    case '/admin/dashboard':
        // POST: test de WhatsApp desde el dashboard
        if ($method === 'POST' && ($_POST['action'] ?? '') === 'dash_test_whatsapp') {
            require_once dirname(__DIR__) . '/services/meta_whatsapp.php';
            require_once dirname(__DIR__) . '/services/token_crypto.php';
            $twId    = (int)($_POST['tw_id']    ?? 0);
            $destino = preg_replace('/\D/', '', $_POST['destino'] ?? '');
            $tplName = trim($_POST['template']  ?? 'hello_world');
            $tplLang = trim($_POST['lang']      ?? 'en_US');
            if ($twId && $destino !== '') {
                try {
                    $stmtTw = $db->prepare("SELECT * FROM tenant_whatsapp WHERE id = :id LIMIT 1");
                    $stmtTw->execute([':id' => $twId]);
                    $tw = $stmtTw->fetch();
                    if ($tw) {
                        $token  = TokenCrypto::decrypt((string)$tw['access_token']);
                        $result = MetaWhatsApp::sendTemplate($tw['phone_number_id'], $destino, $tplName, $tplLang, $token);
                        $_SESSION['dash_wa_result'] = $result;
                        $_SESSION['dash_wa_input']  = compact('destino', 'tplName', 'tplLang', 'twId');
                    } else {
                        $_SESSION['dash_wa_result'] = ['ok' => false, 'error' => 'Credencial no encontrada.'];
                    }
                } catch (Throwable $_we) {
                    $_SESSION['dash_wa_result'] = ['ok' => false, 'error' => $_we->getMessage()];
                }
            } else {
                $_SESSION['dash_wa_result'] = ['ok' => false, 'error' => 'Seleccioná un número y completá el destino.'];
            }
            header('Location: /admin/dashboard#wa-test');
            exit;
        }

        // KPIs plataforma
        $kpi = $db->query(
            "SELECT
                COUNT(*)                                                              AS total,
                SUM(onboarding_status='live')                                         AS live_count,
                SUM(billing_status='active')                                          AS activos,
                SUM(billing_status='trial')                                           AS trial,
                SUM(billing_status IN ('free',''))                                    AS free_count,
                SUM(billing_status='past_due')                                        AS past_due,
                COALESCE(SUM(mrr),0)                                                  AS mrr,
                SUM(YEAR(created_at)=YEAR(NOW()) AND MONTH(created_at)=MONTH(NOW())) AS nuevos_mes,
                SUM(rubro IS NULL OR rubro='')                                        AS sin_rubro
             FROM tenants WHERE deleted_at IS NULL"
        )->fetch();

        $convosRow = $db->query(
            "SELECT COUNT(*) AS cnt, COALESCE(SUM(tokens),0) AS tokens
             FROM agent_logs
             WHERE YEAR(created_at)=YEAR(NOW()) AND MONTH(created_at)=MONTH(NOW())"
        )->fetch();
        $kpi['convos_mes'] = (int)($convosRow['cnt'] ?? 0);
        $kpi['tokens_mes'] = (int)($convosRow['tokens'] ?? 0);

        // Distribución por plan
        $byPlan = $db->query(
            "SELECT plan, COUNT(*) AS cnt, COALESCE(SUM(mrr),0) AS mrr
             FROM tenants WHERE deleted_at IS NULL GROUP BY plan ORDER BY mrr DESC"
        )->fetchAll();

        // Distribución por rubro
        $byRubro = $db->query(
            "SELECT COALESCE(rubro,'sin rubro') AS rubro, COUNT(*) AS cnt
             FROM tenants WHERE deleted_at IS NULL GROUP BY rubro ORDER BY cnt DESC"
        )->fetchAll();

        // Últimos 5 negocios
        $recentTenants = $db->query(
            "SELECT id, name, rubro, plan, billing_status, onboarding_status, created_at
             FROM tenants WHERE deleted_at IS NULL ORDER BY id DESC LIMIT 5"
        )->fetchAll();

        // Top 5 vendedores
        $topSellers = $db->query(
            "SELECT s.nombre,
                SUM(t.billing_status='active')                                           AS activos,
                COALESCE(SUM(CASE WHEN t.billing_status='active' THEN t.mrr ELSE 0 END),0) AS mrr
             FROM sellers s LEFT JOIN tenants t ON t.seller_id=s.id AND t.deleted_at IS NULL
             GROUP BY s.id ORDER BY mrr DESC LIMIT 5"
        )->fetchAll();

        // Errores recientes (logs con type que contiene 'error' o payload con error)
        $recentErrors = $db->query(
            "SELECT l.id, l.type, l.payload, l.created_at, t.name AS tenant_name
             FROM agent_logs l LEFT JOIN tenants t ON l.tenant_id=t.id
             WHERE l.type LIKE '%error%' OR l.type LIKE '%fail%'
             ORDER BY l.id DESC LIMIT 10"
        )->fetchAll();

        // WhatsApp test panel
        $dashWaTenants = [];
        try {
            $stmtWa = $db->prepare(
                "SELECT tw.id, tw.phone_number_id, tw.status, t.name AS tenant_name
                 FROM tenant_whatsapp tw JOIN tenants t ON t.id = tw.tenant_id AND t.deleted_at IS NULL
                 ORDER BY t.name"
            );
            $stmtWa->execute();
            $dashWaTenants = $stmtWa->fetchAll();
        } catch (Throwable $_we) {}
        $dashWaResult = $_SESSION['dash_wa_result'] ?? null;
        $dashWaInput  = $_SESSION['dash_wa_input']  ?? [];
        unset($_SESSION['dash_wa_result'], $_SESSION['dash_wa_input']);

        require dirname(__DIR__) . '/views/admin/dashboard.php';
        exit;

    // ── Contextos de Vale ─────────────────────────────────────────────────────
    case '/admin/contextos':
        $ctxNotice = '';
        $ctxError  = '';

        if ($method === 'POST' && ($_POST['action'] ?? '') === 'save_constitution') {
            $fields = ['identidad','guardrails','reglas_citas','reglas_escalado','reglas_idioma','tono_default'];
            $data   = [];
            foreach ($fields as $f) {
                $data[$f] = trim($_POST[$f] ?? '');
            }
            if ($data['identidad'] === '' || $data['guardrails'] === '') {
                $ctxError = 'Identidad y guardrails son obligatorios.';
            } else {
                try {
                    // Desactivar todas las versiones anteriores
                    $db->exec("UPDATE vale_constitution_versions SET activa = 0");
                    // Nueva versión activa
                    $prevVersion = trim($_POST['version_anterior'] ?? '1.0');
                    $parts = explode('.', $prevVersion);
                    $newVersion = ($parts[0] ?? 1) . '.' . ((int)($parts[1] ?? 0) + 1);
                    $db->prepare(
                        "INSERT INTO vale_constitution_versions
                         (version, identidad, guardrails, reglas_citas, reglas_escalado, reglas_idioma, tono_default, activa)
                         VALUES (:v,:id,:gu,:rc,:re,:ri,:to,1)"
                    )->execute([
                        ':v'  => $newVersion,
                        ':id' => $data['identidad'],
                        ':gu' => $data['guardrails'],
                        ':rc' => $data['reglas_citas'],
                        ':re' => $data['reglas_escalado'],
                        ':ri' => $data['reglas_idioma'],
                        ':to' => $data['tono_default'] ?: 'calido',
                    ]);
                    $ctxNotice = "Constitución guardada como versión $newVersion y activada.";
                } catch (Throwable $e) {
                    $ctxError = 'Error al guardar constitución: ' . $e->getMessage();
                }
            }
        }

        // Cargar constitución activa
        require_once dirname(__DIR__) . '/services/vale_memory_service.php';
        $constitution = ValeMemoryService::getConstitution($db);
        $constitutionFromDb = false;
        try {
            $row = $db->query("SELECT version FROM vale_constitution_versions WHERE activa=1 LIMIT 1")->fetch();
            $constitutionFromDb = (bool)$row;
        } catch (Throwable $_e) {}

        // Plan limits desde archivo
        $planLimits = require dirname(__DIR__, 2) . '/config/plan_limits.php';

        // Rubros
        $rubros = require dirname(__DIR__, 2) . '/config/rubros.php';

        require dirname(__DIR__) . '/views/admin/contextos.php';
        exit;

    // ── Directorio (admin) ────────────────────────────────────────────────────
    case '/admin/directorio':
        $dirNotice = $_SESSION['dir_flash'] ?? '';
        unset($_SESSION['dir_flash']);
        $filterRubro  = trim($_GET['rubro']       ?? '');
        $filterCiudad = trim($_GET['ciudad']      ?? '');
        $filterDesc   = trim($_GET['desc_filter'] ?? '');

        // Stats globales
        $dirStats = $db->query(
            "SELECT
                COUNT(*)                                    AS total,
                SUM(descripcion_dir IS NOT NULL AND descripcion_dir != '') AS con_desc_es,
                SUM(descripcion_dir_en IS NOT NULL AND descripcion_dir_en != '') AS con_desc_en,
                SUM(descripcion_dir IS NULL OR descripcion_dir = '')       AS sin_desc,
                COUNT(DISTINCT ciudad)                      AS ciudades
             FROM tenants WHERE deleted_at IS NULL AND public_slug IS NOT NULL AND public_slug != ''"
        )->fetch();

        // Ciudades para filtro
        $ciudades = $db->query(
            "SELECT DISTINCT ciudad FROM tenants WHERE deleted_at IS NULL AND ciudad IS NOT NULL AND ciudad != '' AND public_slug IS NOT NULL ORDER BY ciudad"
        )->fetchAll(PDO::FETCH_COLUMN);

        // Listings
        $sql = "SELECT id, name, rubro, ciudad, public_slug, descripcion_dir, descripcion_dir_en, dir_keywords
                FROM tenants WHERE deleted_at IS NULL AND public_slug IS NOT NULL AND public_slug != ''";
        $params = [];
        if ($filterRubro !== '')  { $sql .= " AND rubro = :rubro";      $params[':rubro']  = $filterRubro; }
        if ($filterCiudad !== '') { $sql .= " AND ciudad = :ciudad";     $params[':ciudad'] = $filterCiudad; }
        if ($filterDesc === 'sin') {
            $sql .= " AND (descripcion_dir IS NULL OR descripcion_dir = '')";
        } elseif ($filterDesc === 'con') {
            $sql .= " AND descripcion_dir IS NOT NULL AND descripcion_dir != ''";
        }
        $sql .= " ORDER BY name ASC";
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $listings = $stmt->fetchAll();

        // Negocios sin slug
        $sinSlug = $db->query(
            "SELECT id, name FROM tenants WHERE deleted_at IS NULL AND (public_slug IS NULL OR public_slug = '') ORDER BY name ASC"
        )->fetchAll();

        require dirname(__DIR__) . '/views/admin/directorio_admin.php';
        exit;

    case '/admin/directorio/regenerar':
        if ($method === 'POST') {
            $tid = (int)($_POST['tenant_id'] ?? 0);
            if ($tid > 0) {
                try {
                    require_once dirname(__DIR__) . '/services/directorio_service.php';
                    $ok = DirectorioService::generarDescripcion($db, $tid);
                    $_SESSION['dir_flash'] = $ok ? 'Descripción regenerada correctamente.' : 'No se pudo regenerar (revisar logs).';
                } catch (Throwable $e) {
                    error_log('[admin/directorio/regenerar] ' . $e->getMessage());
                    $_SESSION['dir_flash'] = 'Error: ' . $e->getMessage();
                }
            }
        }
        header('Location: /admin/directorio');
        exit;

    // ── Gestión de emails ─────────────────────────────────────────────────────
    case '/admin/emails':
        $emailNotice = '';
        $emailError  = '';
        $testResult  = null;
        $filterType   = trim($_GET['filter_type']   ?? '');
        $filterStatus = trim($_GET['filter_status'] ?? '');

        if ($method === 'POST' && ($_POST['action'] ?? '') === 'test_send') {
            $testTo = trim($_POST['test_to'] ?? '');
            if ($testTo !== '') {
                require_once dirname(__DIR__) . '/services/mailer.php';
                $testResult = Mailer::sendTest($db, $testTo);
                if ($testResult['ok']) {
                    $emailNotice = "Email de prueba enviado a $testTo.";
                } else {
                    $emailError = 'No se pudo enviar: ' . ($testResult['error'] ?? 'Error desconocido');
                }
            } else {
                $emailError = 'Ingresá un email de destino.';
            }
        }

        // Stats
        $stats = [
            'sent_mes'                  => 0,
            'failed_mes'                => 0,
            'total'                     => 0,
            'welcome_owner'             => 0,
            'welcome_seller'            => 0,
            'client_welcome'            => 0,
            'appointment_confirmation'  => 0,
            'new_client_alert'          => 0,
        ];
        try {
            $statsRow = $db->query(
                "SELECT
                    SUM(status='sent'   AND MONTH(created_at)=MONTH(NOW()) AND YEAR(created_at)=YEAR(NOW())) AS sent_mes,
                    SUM(status='failed' AND MONTH(created_at)=MONTH(NOW()) AND YEAR(created_at)=YEAR(NOW())) AS failed_mes,
                    COUNT(*)                                                  AS total,
                    SUM(type='welcome_owner')                                 AS welcome_owner,
                    SUM(type='welcome_seller')                                AS welcome_seller,
                    SUM(type='client_welcome')                                AS client_welcome,
                    SUM(type='appointment_confirmation')                      AS appointment_confirmation,
                    SUM(type='new_client_alert')                              AS new_client_alert
                 FROM email_logs"
            )->fetch();
            if ($statsRow) {
                $stats = array_map('intval', $statsRow);
            }
        } catch (Throwable $_e) {}

        // Logs con filtros
        $logSql = "SELECT id, tenant_id, to_email, subject, type, status, resend_id, error, created_at
                   FROM email_logs WHERE 1=1";
        $logParams = [];
        if ($filterType   !== '') { $logSql .= " AND type = :type";     $logParams[':type']   = $filterType; }
        if ($filterStatus !== '') { $logSql .= " AND status = :status"; $logParams[':status'] = $filterStatus; }
        $logSql .= " ORDER BY id DESC LIMIT 150";
        try {
            $logStmt = $db->prepare($logSql);
            $logStmt->execute($logParams);
            $emailLogs = $logStmt->fetchAll();
        } catch (Throwable $_e) {
            $emailLogs = [];
            $emailError = $emailError ?: 'La tabla email_logs no existe todavía. Ejecutá la migración 020_email_logs.sql.';
        }

        require dirname(__DIR__) . '/views/admin/emails.php';
        exit;

    case '/admin/tenants':
        $notice = '';
        $error = '';
        if ($method === 'POST' && ($_POST['action'] ?? '') === 'update_tenant') {
            // Editar un negocio existente (número, nombre, timezone, idioma).
            $tid = (int) ($_POST['tenant_id'] ?? 0);
            $name = trim($_POST['name'] ?? '');
            $wa = trim($_POST['whatsapp_number'] ?? '');
            $tz = trim($_POST['timezone'] ?? '') ?: 'America/New_York';
            $loc = ($_POST['locale'] ?? 'es') === 'en' ? 'en' : 'es';
            if ($tid > 0 && $name !== '') {
                try {
                    $stmt = $db->prepare(
                        "UPDATE tenants SET name = :n, whatsapp_number = :wa, timezone = :tz, locale = :loc WHERE id = :id"
                    );
                    $stmt->execute([
                        ':n' => $name,
                        ':wa' => $wa !== '' ? $wa : null,
                        ':tz' => $tz,
                        ':loc' => $loc,
                        ':id' => $tid,
                    ]);
                    // El slug público sigue al nombre.
                    $slug = Slug::uniqueFor($db, $name, $tid);
                    $db->prepare("UPDATE tenants SET public_slug = :s WHERE id = :id")->execute([':s' => $slug, ':id' => $tid]);
                    $notice = 'Negocio actualizado. Página pública: /n/' . $slug;
                    // Re-generar descripción del directorio si el negocio está live
                    try {
                        require_once dirname(__DIR__) . '/services/directorio_service.php';
                        DirectorioService::generarDescripcion($db, $tid);
                    } catch (Throwable $_e) { /* silencioso */ }
                } catch (Throwable $e) {
                    $error = 'No se pudo actualizar (¿el número de WhatsApp ya lo usa otro negocio?).';
                    error_log('Admin update tenant failed: ' . $e->getMessage());
                }
            } else {
                $error = 'El nombre es obligatorio.';
            }
        } elseif ($method === 'POST') {
            $name = trim($_POST['name'] ?? '');
            $whatsapp = trim($_POST['whatsapp_number'] ?? '');
            $ownerEmail = trim($_POST['owner_email'] ?? '');
            $ownerPass = $_POST['owner_password'] ?? '';
            if ($name === '' || $ownerEmail === '' || $ownerPass === '') {
                $error = 'Nombre, email y contraseña del dueño son obligatorios.';
            } else {
                try {
                    $db->beginTransaction();
                    $publicKey = bin2hex(random_bytes(16));
                    $stmt = $db->prepare(
                        "INSERT INTO tenants (name, whatsapp_number, web_public_key)
                         VALUES (:name, :wa, :key)"
                    );
                    $stmt->execute([
                        ':name' => $name,
                        ':wa' => $whatsapp !== '' ? $whatsapp : null,
                        ':key' => $publicKey,
                    ]);
                    $tenantId = (int) $db->lastInsertId();

                    $stmt = $db->prepare(
                        "INSERT INTO vale_config (tenant_id, greeting)
                         VALUES (:tid, :greeting)"
                    );
                    $stmt->execute([
                        ':tid' => $tenantId,
                        ':greeting' => '¡Hola! Soy Vale, la asistente virtual de ' . $name . '. ¿En qué te puedo ayudar?',
                    ]);

                    $stmt = $db->prepare(
                        "INSERT INTO users (tenant_id, email, password_hash, name, role)
                         VALUES (:tid, :email, :hash, :name, 'owner')"
                    );
                    $stmt->execute([
                        ':tid' => $tenantId,
                        ':email' => $ownerEmail,
                        ':hash' => password_hash($ownerPass, PASSWORD_DEFAULT),
                        ':name' => $name . ' (Dueño)',
                    ]);

                    $db->commit();
                    $notice = 'Negocio creado. Clave de embed web: ' . $publicKey;
                } catch (Throwable $e) {
                    if ($db->inTransaction()) {
                        $db->rollBack();
                    }
                    $error = 'No se pudo crear el negocio (¿email ya usado?).';
                    error_log('Admin create tenant failed: ' . $e->getMessage());
                }
            }
        }

        // Negocio a editar (si vino ?edit=ID).
        $editTenant = null;
        $editId = filter_input(INPUT_GET, 'edit', FILTER_VALIDATE_INT);
        if ($editId) {
            $stmt = $db->prepare("SELECT * FROM tenants WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $editId]);
            $editTenant = $stmt->fetch() ?: null;
        }

        $tenants = $db->query(
            "SELECT t.id, t.name, t.whatsapp_number, t.web_public_key, t.public_slug, t.onboarding_status, t.created_at,
                    (SELECT COUNT(*) FROM appointments a WHERE a.tenant_id = t.id) AS citas,
                    (SELECT COUNT(*) FROM leads l WHERE l.tenant_id = t.id) AS leads,
                    (SELECT COUNT(*) FROM messages m WHERE m.tenant_id = t.id) AS messages,
                    (SELECT MAX(created_at) FROM agent_logs g WHERE g.tenant_id = t.id) AS last_activity,
                    (SELECT COUNT(*) FROM agent_logs g WHERE g.tenant_id = t.id AND g.type LIKE '%error%' AND g.created_at > (NOW() - INTERVAL 1 DAY)) AS recent_errors,
                    (SELECT email FROM users u WHERE u.tenant_id = t.id AND u.role = 'owner' ORDER BY u.id LIMIT 1) AS owner_email
             FROM tenants t WHERE t.deleted_at IS NULL ORDER BY t.id DESC"
        )->fetchAll();
        $summary = $db->query(
            "SELECT COUNT(*) AS total,
                    SUM(onboarding_status = 'live') AS live,
                    (SELECT COUNT(*) FROM appointments) AS citas,
                    (SELECT COUNT(*) FROM leads) AS leads
             FROM tenants WHERE deleted_at IS NULL"
        )->fetch();
        require dirname(__DIR__) . '/views/admin/tenants.php';
        exit;

    // ── Soft-delete de tenant (NUNCA hard DELETE) ─────────────────────────────
    case '/admin/tenant/delete':
        if ($method !== 'POST') { header('Location: /admin/tenants'); exit; }
        $delId = filter_input(INPUT_POST, 'tenant_id', FILTER_VALIDATE_INT);
        if ($delId) {
            $db->prepare(
                "UPDATE tenants SET deleted_at = NOW() WHERE id = :id AND deleted_at IS NULL"
            )->execute([':id' => $delId]);
        }
        $_SESSION['flash'] = $delId ? "Tenant #$delId marcado como eliminado." : 'ID inválido.';
        header('Location: /admin/tenants');
        exit;

    // ── Restaurar tenant soft-deleted ────────────────────────────────────────
    case '/admin/tenant/restore':
        if ($method !== 'POST') { header('Location: /admin/tenants'); exit; }
        $restId = filter_input(INPUT_POST, 'tenant_id', FILTER_VALIDATE_INT);
        if ($restId) {
            $db->prepare(
                "UPDATE tenants SET deleted_at = NULL WHERE id = :id"
            )->execute([':id' => $restId]);
        }
        $_SESSION['flash'] = $restId ? "Tenant #$restId restaurado." : 'ID inválido.';
        header('Location: /admin/tenants');
        exit;

    case '/admin/tenant':
        // Perfil de un negocio (cliente de Vale).
        $pid = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if (!$pid) {
            header('Location: /admin/tenants');
            exit;
        }
        $stmt = $db->prepare("SELECT * FROM tenants WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $pid]);
        $profile = $stmt->fetch();
        if (!$profile) {
            header('Location: /admin/tenants');
            exit;
        }
        $stmt = $db->prepare("SELECT name, email, phone, role, auth_provider, created_at FROM users WHERE tenant_id = :t ORDER BY id");
        $stmt->execute([':t' => $pid]);
        $profileUsers = $stmt->fetchAll();
        $stmt = $db->prepare("SELECT greeting, tone, default_locale, hours_json FROM vale_config WHERE tenant_id = :t LIMIT 1");
        $stmt->execute([':t' => $pid]);
        $profileConfig = $stmt->fetch() ?: [];
        $stmt = $db->prepare("SELECT name, duration_min, price_min, price_max, active FROM services WHERE tenant_id = :t ORDER BY id");
        $stmt->execute([':t' => $pid]);
        $profileServices = $stmt->fetchAll();
        $stmt = $db->prepare(
            "SELECT
                (SELECT COUNT(*) FROM appointments WHERE tenant_id = :t1) AS citas,
                (SELECT COUNT(*) FROM leads WHERE tenant_id = :t2) AS leads,
                (SELECT COUNT(*) FROM conversations WHERE tenant_id = :t3) AS convs,
                (SELECT COUNT(*) FROM messages WHERE tenant_id = :t4) AS msgs,
                (SELECT COUNT(*) FROM contacts WHERE tenant_id = :t5) AS contactos"
        );
        $stmt->execute([':t1' => $pid, ':t2' => $pid, ':t3' => $pid, ':t4' => $pid, ':t5' => $pid]);
        $profileMetrics = $stmt->fetch();
        $stmt = $db->prepare("SELECT type, gemini_call, tokens, created_at FROM agent_logs WHERE tenant_id = :t ORDER BY id DESC LIMIT 12");
        $stmt->execute([':t' => $pid]);
        $profileLogs = $stmt->fetchAll();
        require dirname(__DIR__) . '/views/admin/tenant_profile.php';
        exit;

    case '/admin/logs':
        // Evidence viewer — the contest's proof of the agent running.
        $filterType = trim($_GET['type'] ?? '');
        $filterTenant = filter_input(INPUT_GET, 'tenant_id', FILTER_VALIDATE_INT) ?: null;

        $sql = "SELECT l.id, l.tenant_id, t.name AS tenant_name, l.type, l.gemini_call,
                       l.tokens, l.payload, l.created_at
                FROM agent_logs l LEFT JOIN tenants t ON l.tenant_id = t.id WHERE 1=1";
        $params = [];
        if ($filterType !== '') {
            $sql .= " AND l.type = :type";
            $params[':type'] = $filterType;
        }
        if ($filterTenant !== null) {
            $sql .= " AND l.tenant_id = :tid";
            $params[':tid'] = $filterTenant;
        }
        $sql .= " ORDER BY l.id DESC LIMIT 100";
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $logs = $stmt->fetchAll();

        $types = $db->query("SELECT DISTINCT type FROM agent_logs ORDER BY type")->fetchAll(PDO::FETCH_COLUMN);
        require dirname(__DIR__) . '/views/admin/logs.php';
        exit;

    case '/admin/impersonate':
        $tid = filter_input(INPUT_GET, 'tenant_id', FILTER_VALIDATE_INT);
        if ($tid) {
            $stmt = $db->prepare(
                "SELECT u.*, t.name AS tenant_name FROM users u
                 JOIN tenants t ON u.tenant_id = t.id AND t.deleted_at IS NULL
                 WHERE u.tenant_id = :tid AND u.role = 'owner' ORDER BY u.id ASC LIMIT 1"
            );
            $stmt->execute([':tid' => $tid]);
            $owner = $stmt->fetch();
            if ($owner) {
                $adminId = $_SESSION['admin_id'];
                $adminName = $_SESSION['admin_name'] ?? '';
                session_regenerate_id(true);
                $_SESSION['admin_id'] = $adminId;
                $_SESSION['admin_name'] = $adminName;
                $_SESSION['impersonated_by_admin'] = $adminId;
                $_SESSION['user_id'] = $owner['id'];
                $_SESSION['tenant_id'] = $owner['tenant_id'];
                $_SESSION['tenant_name'] = $owner['tenant_name'];
                $_SESSION['user_name'] = $owner['name'];
                $_SESSION['user_role'] = $owner['role'];
                header('Location: /inicio');
                exit;
            }
        }
        header('Location: /admin/tenants');
        exit;

    case '/admin/stop-impersonate':
        // Drop the owner session, keep the admin session.
        unset($_SESSION['user_id'], $_SESSION['tenant_id'], $_SESSION['tenant_name'],
              $_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['impersonated_by_admin']);
        header('Location: /admin/tenants');
        exit;

    // ── Usuarios & Roles ──────────────────────────────────────────────────────
    case '/admin/users':
        $usersNotice = '';
        $usersError  = '';

        if ($method === 'POST') {
            $action = $_POST['action'] ?? '';

            if ($action === 'create_admin') {
                $name  = trim($_POST['name']     ?? '');
                $email = trim($_POST['email']    ?? '');
                $pass  = $_POST['password']      ?? '';
                if (!$name || !$email || strlen($pass) < 10) {
                    $usersError = 'Nombre, email y contraseña (mínimo 10 caracteres) son obligatorios.';
                } else {
                    try {
                        $db->prepare(
                            "INSERT INTO admins (name, email, password_hash) VALUES (:n, :e, :h)"
                        )->execute([
                            ':n' => $name,
                            ':e' => $email,
                            ':h' => password_hash($pass, PASSWORD_DEFAULT),
                        ]);
                        $usersNotice = "Admin $name creado correctamente.";
                    } catch (Throwable $e) {
                        $usersError = '¿El email ya existe? ' . $e->getMessage();
                    }
                }
            }

            if ($action === 'delete_admin') {
                $aid = (int)($_POST['admin_id'] ?? 0);
                if ($aid && $aid !== (int)($_SESSION['admin_id'] ?? 0)) {
                    $db->prepare("DELETE FROM admins WHERE id = :id")->execute([':id' => $aid]);
                    $usersNotice = 'Admin eliminado.';
                } else {
                    $usersError = 'No podés eliminarte a vos mismo.';
                }
            }

            if ($action === 'change_role') {
                $uid  = (int)($_POST['user_id'] ?? 0);
                $role = $_POST['role'] ?? '';
                $allowed = ['owner', 'staff', 'seller', 'support'];
                if ($uid && in_array($role, $allowed, true)) {
                    $db->prepare("UPDATE users SET role = :r WHERE id = :id")
                       ->execute([':r' => $role, ':id' => $uid]);
                    $usersNotice = 'Rol actualizado.';
                } else {
                    $usersError = 'Rol inválido.';
                }
            }
        }

        // Super-admins
        $admins = $db->query("SELECT id, name, email, created_at FROM admins ORDER BY id ASC")->fetchAll();

        // Usuarios de tenants
        $tenantUsers = $db->query(
            "SELECT u.id, u.name, u.email, u.role, u.created_at, u.tenant_id, t.name AS tenant_name
             FROM users u
             LEFT JOIN tenants t ON t.id = u.tenant_id
             ORDER BY t.name ASC, u.role ASC, u.id ASC"
        )->fetchAll();

        require dirname(__DIR__) . '/views/admin/users.php';
        exit;

    case '/admin/config':
        require_once dirname(__DIR__) . '/services/twilio.php';
        $cfgNotice = '';
        $cfgError = '';
        $testResult = null;
        if ($method === 'POST') {
            $action = $_POST['action'] ?? '';
            if ($action === 'save_number') {
                PlatformSettings::set('supraide_whatsapp', preg_replace('/\D+/', '', $_POST['supraide_whatsapp'] ?? ''));
                $cfgNotice = 'Número de Supraide guardado.';
            } elseif ($action === 'test_send') {
                $to = trim($_POST['test_to'] ?? '');
                $channel = ($_POST['test_channel'] ?? 'whatsapp') === 'sms' ? 'sms' : 'whatsapp';
                if ($to !== '') {
                    $testResult = TwilioService::sendMessage($to, 'Hola 👋 Soy Vale. Prueba de conexión de Supraide. ✅', $channel);
                } else {
                    $cfgError = 'Poné un número de destino para la prueba.';
                }
            }
        }
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $status = [
            'twilio_sid' => (bool) getenv('TWILIO_ACCOUNT_SID'),
            'twilio_token' => (bool) getenv('TWILIO_AUTH_TOKEN'),
            'twilio_validation' => filter_var(getenv('TWILIO_VALIDATION_ENABLED') ?: 'true', FILTER_VALIDATE_BOOLEAN),
            'supraide_number' => PlatformSettings::supraideNumber(),
            'gemini_key' => (bool) getenv('GEMINI_API_KEY'),
            'gemini_model' => getenv('GEMINI_MODEL') ?: 'gemini-3.5-flash',
            'google_oauth' => (bool) getenv('GOOGLE_CLIENT_ID'),
            'webhook_url' => $scheme . '://' . $host . '/agent/whatsapp',
        ];
        require dirname(__DIR__) . '/views/admin/config.php';
        exit;

    // ── Ventas & Finanzas ─────────────────────────────────────────────────────
    case '/admin/sales':
        // KPIs globales
        $kpi = $db->query(
            "SELECT
                COALESCE(SUM(mrr),0)                             AS mrr_total,
                SUM(billing_status='active')                     AS activos,
                SUM(billing_status='trial')                      AS trial,
                SUM(billing_status='past_due')                   AS past_due,
                (SELECT COALESCE(SUM(monto),0) FROM commissions WHERE pagada=0) AS comm_pend,
                (SELECT COALESCE(SUM(monto),0) FROM commissions WHERE pagada=1) AS comm_paid
             FROM tenants WHERE deleted_at IS NULL"
        )->fetch();

        $mrrByPlan = $db->query(
            "SELECT plan, COUNT(*) AS cnt, COALESCE(SUM(mrr),0) AS total_mrr
             FROM tenants WHERE billing_status='active' AND deleted_at IS NULL GROUP BY plan ORDER BY total_mrr DESC"
        )->fetchAll();

        $mrrByMethod = $db->query(
            "SELECT billing_method, COUNT(*) AS cnt, COALESCE(SUM(mrr),0) AS total_mrr
             FROM tenants WHERE billing_status='active' AND deleted_at IS NULL GROUP BY billing_method ORDER BY total_mrr DESC"
        )->fetchAll();

        // Rendimiento por vendedor
        $sellers = $db->query(
            "SELECT s.*,
                COUNT(DISTINCT t.id)                                              AS total_tenants,
                SUM(t.billing_status='active')                                    AS activos,
                COALESCE(SUM(CASE WHEN t.billing_status='active' THEN t.mrr ELSE 0 END),0) AS mrr,
                COALESCE((SELECT SUM(c.monto) FROM commissions c WHERE c.seller_id=s.id AND c.pagada=0),0) AS comm_pend,
                COALESCE((SELECT SUM(c.monto) FROM commissions c WHERE c.seller_id=s.id AND c.pagada=1),0) AS comm_paid
             FROM sellers s
             LEFT JOIN tenants t ON t.seller_id = s.id AND t.deleted_at IS NULL
             GROUP BY s.id ORDER BY mrr DESC"
        )->fetchAll();

        // Movimientos (commissions) con filtros
        $filterPagada = $_GET['filter_pagada'] ?? '';
        $filterTipo   = $_GET['filter_tipo']   ?? '';
        $commSql = "SELECT c.*, s.nombre AS seller_nombre, t.name AS tenant_name
                    FROM commissions c
                    LEFT JOIN sellers s ON s.id = c.seller_id
                    LEFT JOIN tenants t ON t.id = c.tenant_id
                    WHERE 1=1";
        $commParams = [];
        if ($filterPagada !== '') { $commSql .= " AND c.pagada = :pagada"; $commParams[':pagada'] = (int)$filterPagada; }
        if ($filterTipo   !== '') { $commSql .= " AND c.tipo = :tipo";   $commParams[':tipo']   = $filterTipo; }
        $commSql .= " ORDER BY c.created_at DESC LIMIT 200";
        $stmt = $db->prepare($commSql);
        $stmt->execute($commParams);
        $commissions = $stmt->fetchAll();

        require dirname(__DIR__) . '/views/admin/sales.php';
        exit;

    // ── WhatsApp Business ─────────────────────────────────────────────────────
    case '/admin/whatsapp':
        require_once dirname(__DIR__) . '/services/meta_whatsapp.php';
        require_once dirname(__DIR__) . '/services/token_crypto.php';

        $waNotice = '';
        $waError  = '';
        $waTestResult = null;

        if ($method === 'POST') {
            $waAction = $_POST['action'] ?? '';

            // ── Enviar mensaje de prueba ───────────────────────────────────────
            if ($waAction === 'test_wa') {
                $twId    = (int)($_POST['tw_id']    ?? 0);
                $destino = preg_replace('/\D/', '', $_POST['destino'] ?? '');
                $tplName = trim($_POST['template']  ?? 'hello_world');
                $tplLang = trim($_POST['lang']       ?? 'en_US');

                if (!$twId || $destino === '') {
                    $waError = 'Seleccioná un número y completá el destino.';
                } else {
                    try {
                        $stmt = $db->prepare("SELECT * FROM tenant_whatsapp WHERE id = :id LIMIT 1");
                        $stmt->execute([':id' => $twId]);
                        $tw = $stmt->fetch();
                        if ($tw) {
                            $token = TokenCrypto::decrypt((string)$tw['access_token']);
                            $waTestResult = MetaWhatsApp::sendTemplate(
                                $tw['phone_number_id'], $destino, $tplName, $tplLang, $token
                            );
                            if (!empty($waTestResult['ok'])) {
                                $waNotice = 'Mensaje enviado. ID: ' . ($waTestResult['message_id'] ?? '–');
                            } else {
                                $waError = $waTestResult['error'] ?? 'Error desconocido de Meta.';
                            }
                        } else {
                            $waError = 'Credencial no encontrada.';
                        }
                    } catch (Throwable $_we) {
                        $waError = $_we->getMessage();
                    }
                }
            }

            // ── Agregar / actualizar credencial ────────────────────────────────
            if ($waAction === 'save_wa_credential') {
                $tenantId     = (int)($_POST['tenant_id'] ?? 0);
                $phoneNumId   = trim($_POST['phone_number_id'] ?? '');
                $wabaId       = trim($_POST['waba_id']         ?? '');
                $accessToken  = trim($_POST['access_token']    ?? '');

                if (!$tenantId || !$phoneNumId || !$wabaId || !$accessToken) {
                    $waError = 'Todos los campos son obligatorios.';
                } else {
                    try {
                        $encrypted = TokenCrypto::encrypt($accessToken);
                        $db->prepare(
                            "INSERT INTO tenant_whatsapp (tenant_id, phone_number_id, waba_id, access_token, status)
                             VALUES (:tid, :pid, :wid, :tok, 'active')
                             ON DUPLICATE KEY UPDATE
                                phone_number_id = VALUES(phone_number_id),
                                waba_id         = VALUES(waba_id),
                                access_token    = VALUES(access_token),
                                status          = 'active'"
                        )->execute([
                            ':tid' => $tenantId,
                            ':pid' => $phoneNumId,
                            ':wid' => $wabaId,
                            ':tok' => $encrypted,
                        ]);
                        $waNotice = 'Credencial guardada correctamente.';

                        // Capa A: notificar al dueño que su WhatsApp quedó conectado
                        try {
                            require_once dirname(__DIR__) . '/services/platform_whatsapp.php';
                            $negRow = $db->prepare("SELECT name FROM tenants WHERE id = :t LIMIT 1");
                            $negRow->execute([':t' => $tenantId]);
                            $negNombre = (string)($negRow->fetchColumn() ?: 'tu negocio');
                            PlatformWhatsApp::sendWaConectado($db, $tenantId, $negNombre);
                        } catch (Throwable $_e) {}

                    } catch (Throwable $_we) {
                        $waError = 'Error al guardar: ' . $_we->getMessage();
                    }
                }
            }

            // ── Desactivar número ──────────────────────────────────────────────
            if ($waAction === 'disable_wa') {
                $twId = (int)($_POST['tw_id'] ?? 0);
                if ($twId) {
                    $db->prepare("UPDATE tenant_whatsapp SET status = 'inactive' WHERE id = :id")
                       ->execute([':id' => $twId]);
                    $waNotice = 'Número desactivado.';
                }
            }
        }

        // Cargar todos los números configurados
        $waTenants = [];
        try {
            $stmt = $db->prepare(
                "SELECT tw.id, tw.phone_number_id, tw.waba_id, tw.status, tw.created_at,
                        t.id AS tenant_id, t.name AS tenant_name
                 FROM tenant_whatsapp tw
                 JOIN tenants t ON t.id = tw.tenant_id AND t.deleted_at IS NULL
                 ORDER BY tw.status DESC, t.name ASC"
            );
            $stmt->execute();
            $waTenants = $stmt->fetchAll();
        } catch (Throwable $_we) {}

        // Todos los tenants para el form de agregar
        $allTenants = $db->query("SELECT id, name FROM tenants WHERE deleted_at IS NULL ORDER BY name ASC")->fetchAll();

        // Info de webhook
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                  || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') ? 'https' : 'http';
        $webhookUrl   = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'valeai.app') . '/webhook/meta';
        $verifyToken  = getenv('META_WEBHOOK_VERIFY_TOKEN') ?: '(no configurado)';

        require dirname(__DIR__) . '/views/admin/whatsapp.php';
        exit;

    // ── Gestión de vendedores ─────────────────────────────────────────────────
    case '/admin/sellers':
        $notice = '';
        $error  = '';
        $openForm = false;

        if ($method === 'POST') {
            $action = $_POST['action'] ?? '';

            if ($action === 'create_seller') {
                $nombre  = trim($_POST['nombre'] ?? '');
                $email   = trim($_POST['email']  ?? '');
                $tel     = trim($_POST['telefono'] ?? '') ?: null;
                $setPct  = (float)($_POST['comision_setup_pct'] ?? 35);
                $mrrPct  = (float)($_POST['comision_mrr_pct']  ?? 15);
                $meses   = (int)($_POST['comision_meses'] ?? 12);
                $pass    = $_POST['password'] ?? '';

                if (!$nombre || !$email || !$pass) {
                    $error = 'Nombre, email y contraseña son obligatorios.';
                    $openForm = true;
                } else {
                    try {
                        $db->beginTransaction();
                        // Insertar en sellers
                        $db->prepare(
                            "INSERT INTO sellers (nombre,telefono,email,comision_setup_pct,comision_mrr_pct,comision_meses)
                             VALUES (:n,:tel,:e,:sp,:mp,:mes)"
                        )->execute([':n'=>$nombre,':tel'=>$tel,':e'=>$email,':sp'=>$setPct,':mp'=>$mrrPct,':mes'=>$meses]);
                        $sellerId = (int)$db->lastInsertId();

                        // Crear usuario con role=seller para login (tenant_id NULL — ver migración 021)
                        $db->prepare(
                            "INSERT INTO users (tenant_id, email, password_hash, name, role, seller_profile_id)
                             VALUES (NULL, :e, :h, :n, 'seller', :sid)"
                        )->execute([':e'=>$email,':h'=>password_hash($pass,PASSWORD_DEFAULT),':n'=>$nombre,':sid'=>$sellerId]);

                        $db->commit();
                        $notice = "Vendedor '$nombre' creado correctamente.";

                        // Email de bienvenida con credenciales (fuera de la transacción)
                        try {
                            require_once dirname(__DIR__) . '/services/mailer.php';
                            Mailer::sendSellerWelcome($db, $email, $nombre, $pass);
                        } catch (Throwable $mailEx) {
                            error_log('Seller welcome email failed: ' . $mailEx->getMessage());
                            $notice .= ' (Email de bienvenida no pudo enviarse — revisá los logs.)';
                        }
                    } catch (Throwable $ex) {
                        if ($db->inTransaction()) $db->rollBack();
                        $error = 'Error al crear vendedor: ' . $ex->getMessage();
                        $openForm = true;
                    }
                }
            } elseif ($action === 'toggle_seller') {
                $sid = (int)($_POST['seller_id'] ?? 0);
                $db->prepare("UPDATE sellers SET activo = NOT activo WHERE id = :id")->execute([':id'=>$sid]);
                $notice = 'Estado del vendedor actualizado.';
            }
        }

        $sellers = $db->query(
            "SELECT s.*,
                COUNT(DISTINCT t.id) AS total_tenants,
                COALESCE(SUM(CASE WHEN t.billing_status='active' THEN t.mrr ELSE 0 END),0) AS mrr
             FROM sellers s
             LEFT JOIN tenants t ON t.seller_id = s.id AND t.deleted_at IS NULL
             GROUP BY s.id ORDER BY s.created_at DESC"
        )->fetchAll();

        require dirname(__DIR__) . '/views/admin/sellers.php';
        exit;

    // ── Perfil de vendedor (pipeline detallado) ───────────────────────────────
    case '/admin/seller':
        $sid = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if (!$sid) { header('Location: /admin/sellers'); exit; }
        $seller = $db->prepare("SELECT * FROM sellers WHERE id = :id LIMIT 1");
        $seller->execute([':id' => $sid]);
        $sellerProfile = $seller->fetch();
        if (!$sellerProfile) { header('Location: /admin/sellers'); exit; }

        $tenants = $db->prepare(
            "SELECT t.*, u.email AS owner_email, u.name AS owner_name
             FROM tenants t LEFT JOIN users u ON u.tenant_id=t.id AND u.role='owner'
             WHERE t.seller_id = :sid AND t.deleted_at IS NULL ORDER BY t.created_at DESC"
        );
        $tenants->execute([':sid' => $sid]);
        $tenants = $tenants->fetchAll();

        $totalMrr  = array_sum(array_column($tenants, 'mrr'));
        $activos   = count(array_filter($tenants, fn($t) => $t['billing_status'] === 'active'));
        $pendComm  = $db->prepare("SELECT COALESCE(SUM(monto),0) FROM commissions WHERE seller_id=:s AND pagada=0");
        $pendComm->execute([':s' => $sid]);
        $pendComm = (float)$pendComm->fetchColumn();

        // Re-usar la view de seller/tenants con contexto del admin
        $ctx       = ['role' => 'super_admin', 'display_name' => $_SESSION['admin_name'] ?? 'Admin'];
        $page_title = 'Pipeline de ' . htmlspecialchars($sellerProfile['nombre']);
        ob_start();
        require dirname(__DIR__) . '/views/seller/tenants.php';
        exit;

    // ── Test WhatsApp — enviar plantilla de prueba ────────────────────────────
    case '/admin/test-whatsapp':
        require_once dirname(__DIR__) . '/services/meta_whatsapp.php';
        require_once dirname(__DIR__) . '/services/token_crypto.php';

        $waResult  = null;
        $waError   = null;
        $waTenants = [];

        // Cargar todos los tenants con WhatsApp configurado
        try {
            $stmt = $db->prepare(
                "SELECT tw.id, tw.phone_number_id, tw.waba_id, tw.access_token, tw.status,
                        t.name AS tenant_name, t.id AS tenant_id
                 FROM tenant_whatsapp tw
                 JOIN tenants t ON t.id = tw.tenant_id AND t.deleted_at IS NULL
                 ORDER BY t.name"
            );
            $stmt->execute();
            $waTenants = $stmt->fetchAll();
        } catch (Throwable $_e) {}

        if ($method === 'POST') {
            $twId    = (int)($_POST['tw_id']    ?? 0);
            $destino = preg_replace('/\D/', '', $_POST['destino'] ?? '');
            $tplName = trim($_POST['template']  ?? 'hello_world');
            $tplLang = trim($_POST['lang']       ?? 'en_US');

            if ($twId && $destino !== '') {
                $stmt = $db->prepare("SELECT * FROM tenant_whatsapp WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $twId]);
                $tw = $stmt->fetch();

                if ($tw) {
                    try {
                        $token  = TokenCrypto::decrypt((string)$tw['access_token']);
                        $result = MetaWhatsApp::sendTemplate(
                            $tw['phone_number_id'],
                            $destino,
                            $tplName,
                            $tplLang,
                            $token
                        );
                        $waResult = $result;
                    } catch (Throwable $_e) {
                        $waError = $_e->getMessage();
                    }
                } else {
                    $waError = 'Credencial no encontrada.';
                }
            } else {
                $waError = 'Seleccioná un número y completá el destino.';
            }
        }

        // ── Vista inline ──────────────────────────────────────────────────────
        ?><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Test WhatsApp — Admin</title>
<style>
  body{font-family:system-ui,sans-serif;max-width:600px;margin:40px auto;padding:0 20px;color:#222}
  h1{font-size:22px;margin-bottom:4px}
  .sub{color:#666;font-size:13px;margin-bottom:28px}
  label{display:block;font-weight:600;font-size:13px;margin-bottom:4px;margin-top:16px}
  input,select{width:100%;padding:9px 12px;border:1px solid #ddd;border-radius:8px;font-size:14px;box-sizing:border-box}
  button{margin-top:20px;background:#A8331A;color:#fff;border:none;padding:11px 24px;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer}
  .ok{background:#e8f5e9;border:1px solid #81c784;padding:14px 16px;border-radius:8px;margin-top:20px;font-size:14px}
  .err{background:#fdecea;border:1px solid #e57373;padding:14px 16px;border-radius:8px;margin-top:20px;font-size:14px}
  pre{margin:6px 0 0;font-size:12px;white-space:pre-wrap;word-break:break-all}
  a{color:#A8331A;font-size:13px}
</style>
</head>
<body>
<p><a href="/admin">← Admin</a></p>
<h1>Test — Envío WhatsApp</h1>
<p class="sub">Envía una plantilla aprobada a un número para verificar que las credenciales funcionan.</p>

<?php if ($waResult !== null): ?>
  <?php if ($waResult['ok']): ?>
    <div class="ok">
      <strong>Mensaje enviado.</strong><br>
      Message ID: <code><?= htmlspecialchars($waResult['message_id'] ?? '—') ?></code>
    </div>
  <?php else: ?>
    <div class="err">
      <strong>Error de Meta:</strong> <?= htmlspecialchars($waResult['error'] ?? 'desconocido') ?>
    </div>
  <?php endif; ?>
<?php elseif ($waError): ?>
  <div class="err"><strong>Error:</strong> <?= htmlspecialchars($waError) ?></div>
<?php endif; ?>

<?php if (empty($waTenants)): ?>
  <div class="err">No hay números de WhatsApp configurados en la DB. Corrí el seed primero.</div>
<?php else: ?>
<form method="POST">
  <label>Número de WhatsApp (tenant)</label>
  <select name="tw_id">
    <?php foreach ($waTenants as $tw): ?>
      <option value="<?= $tw['id'] ?>" <?= (($_POST['tw_id'] ?? '') == $tw['id']) ? 'selected' : '' ?>>
        <?= htmlspecialchars($tw['tenant_name']) ?> — <?= htmlspecialchars($tw['phone_number_id']) ?> (<?= $tw['status'] ?>)
      </option>
    <?php endforeach; ?>
  </select>

  <label>Destino (número con código país, sin +)</label>
  <input type="text" name="destino" placeholder="15055551234" value="<?= htmlspecialchars($_POST['destino'] ?? '') ?>">

  <label>Plantilla</label>
  <input type="text" name="template" value="<?= htmlspecialchars($_POST['template'] ?? 'hello_world') ?>">

  <label>Idioma</label>
  <input type="text" name="lang" value="<?= htmlspecialchars($_POST['lang'] ?? 'en_US') ?>">

  <button type="submit">Enviar plantilla</button>
</form>
<?php endif; ?>
</body>
</html>
<?php
        exit;

    // ── Marcar comisión como pagada ───────────────────────────────────────────
    case '/admin/commissions/pay':
        if ($method === 'POST') {
            $cid = (int)($_POST['id'] ?? 0);
            if ($cid) {
                $db->prepare("UPDATE commissions SET pagada=1 WHERE id=:id")->execute([':id'=>$cid]);
            }
        }
        header('Location: /admin/sales');
        exit;

    default:
        http_response_code(404);
        echo '404 Not Found';
        exit;
}
