<?php
// caliente.php - PHP 5.6
// Panel "Calientes" con:
// - Pregrabados: click => envía automáticamente
// - IA: genera borrador seguro (no auto-send)
// - Multimedia en iframe: imágenes/audio/video/doc con detección por extensión
// - Botón "No quitar de caliente": si está activado, NO elimina la tarjeta al enviar
// - Grid: 3 columnas en desktop
// - Fecha: si es de HOY, muestra "hace X min / hace X hora(s) y media"

// =========================
// Bootstrap básico
// =========================
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!ob_get_level()) { ob_start(); }
@date_default_timezone_set('America/Argentina/Buenos_Aires');

require_once __DIR__ . '/config.php';
$pdo = db();

error_reporting(0);
ini_set('display_errors', '0');

$POR_PAGINA = 30;
$MIN_HORAS  = 2;

// URL BASE PARA CONSTRUIR RUTAS COMPLETAS DE MEDIA
define('MEDIA_BASE_URL', 'https://nodo11.radiosnet.com.ar/whatsapp_ofi/');

/* =========================
   OPENAI CONFIG
========================= */
if (!defined('OPENAI_API_KEY')) { define('OPENAI_API_KEY', 'PEGAR_EN_config.php'); }
define('OPENAI_MODEL', 'gpt-3.5-turbo');
define('OPENAI_API_URL', 'https://api.openai.com/v1/chat/completions');
define('OPENAI_TIMEOUT', 30);
define('WHISPER_API_URL', 'https://api.openai.com/v1/audio/transcriptions');

define('AI_MAX_MSGS', 120);
define('AI_MAX_CHARS_PER_MSG', 1200);
define('AI_MAX_OUTPUT_TOKENS', 450);

/* =========================
   Helpers
========================= */
function normalizar_mensaje($txt) {
    return trim(str_replace(array("\r\n","\r"), "\n", (string)$txt));
}
function recortar_texto($s, $max) {
    $s = (string)$s;
    if ($max <= 0) return '';
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        if (mb_strlen($s, 'UTF-8') > $max) return mb_substr($s, 0, $max, 'UTF-8') . '...';
        return $s;
    }
    if (strlen($s) > $max) return substr($s, 0, $max) . '...';
    return $s;
}
function normalizar_telefono_ultra($telefono) {
    $to = trim((string)$telefono);
    $to = str_replace('@c.us', '', $to);
    if ($to !== '' && isset($to[0]) && $to[0] !== '+') {
        $digits = ltrim(preg_replace('/\D+/', '', $to), '0');
        if ($digits === '') return '';
        if (strpos($digits, '549') === 0) $to = '+' . $digits;
        elseif (strpos($digits, '54') === 0) $to = '+' . $digits;
        elseif (strpos($digits, '341') === 0) $to = '+549' . $digits;
        else $to = '+' . $digits;
    }
    return $to;
}
function enviar_whatsapp_texto($telefono, $mensaje) {
    $to = normalizar_telefono_ultra($telefono);
    if ($to === '') return array('success'=>false,'error'=>'Teléfono vacío','response'=>'','data'=>null);

    $params = array('token' => ULTRA_TOKEN, 'to' => $to, 'body' => $mensaje, 'priority' => 10);

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ultramsg.com/" . ULTRA_INSTANCE_ID . "/messages/chat",
        CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_HTTPHEADER => array("content-type: application/x-www-form-urlencoded"),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) return array('success'=>false,'error'=>$err,'response'=>$response,'data'=>null);

    $data = json_decode($response, true);
    $success = is_array($data) && isset($data['sent']) && ($data['sent'] === 'true' || $data['sent'] === true || $data['sent'] === 1 || $data['sent'] === '1');

    $msg = 'Error';
    if (is_array($data) && isset($data['message'])) $msg = $data['message'];

    return array('success' => $success, 'error' => $success ? null : $msg, 'response' => $response, 'data' => $data);
}
function enviar_whatsapp_audio($telefono, $audio_url) {
    $to = normalizar_telefono_ultra($telefono);
    if ($to === '') return array('success'=>false,'error'=>'Teléfono vacío','response'=>'','data'=>null);

    $params = array('token' => ULTRA_TOKEN, 'to' => $to, 'audio' => $audio_url);

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ultramsg.com/" . ULTRA_INSTANCE_ID . "/messages/audio",
        CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_HTTPHEADER => array("content-type: application/x-www-form-urlencoded"),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) return array('success'=>false,'error'=>$err,'response'=>$response,'data'=>null);

    $data = json_decode($response, true);
    $success = is_array($data) && isset($data['sent']) && ($data['sent'] === 'true' || $data['sent'] === true || $data['sent'] === 1 || $data['sent'] === '1');

    $msg = 'Error';
    if (is_array($data) && isset($data['message'])) $msg = $data['message'];

    return array('success' => $success, 'error' => $success ? null : $msg, 'response' => $response, 'data' => $data);
}
function es_post_repetido($key, $ttlSeg) {
    $ttlSeg = (int)$ttlSeg;
    $now = time();
    if (!isset($_SESSION['cal_last_posts']) || !is_array($_SESSION['cal_last_posts'])) $_SESSION['cal_last_posts'] = array();

    foreach ($_SESSION['cal_last_posts'] as $k => $info) {
        if (!is_array($info) || !isset($info['t'])) { unset($_SESSION['cal_last_posts'][$k]); continue; }
        if ($now - (int)$info['t'] > $ttlSeg) unset($_SESSION['cal_last_posts'][$k]);
    }

    if (isset($_SESSION['cal_last_posts'][$key])) return true;
    $_SESSION['cal_last_posts'][$key] = array('t' => $now);
    return false;
}
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/* FECHA: hoy => "hace X" */
function fmt_fecha($dt) {
    if (!$dt) return '';
    $ts = strtotime($dt);
    return $ts ? date('d/m/Y H:i', $ts) : '';
}
function fmt_hace_si_hoy($dt) {
    if (!$dt) return '';
    $ts = strtotime($dt);
    if (!$ts) return '';

    $hoy = date('Y-m-d');
    if (date('Y-m-d', $ts) !== $hoy) {
        return date('d/m/Y H:i', $ts);
    }

    $diff = time() - $ts;
    if ($diff < 0) $diff = 0;

    $mins = (int)floor($diff / 60);
    if ($mins < 1) $mins = 1;

    if ($mins < 60) {
        return 'hace ' . $mins . ' min';
    }

    // redondeo a 30 min para poder decir "y media"
    $minsRounded = (int)(round($mins / 30) * 30);
    if ($minsRounded < 60) $minsRounded = 60;

    $hours = (int)floor($minsRounded / 60);
    $rem   = (int)($minsRounded % 60);

    $hsTxt = ($hours === 1) ? 'hora' : 'horas';

    if ($rem === 0) {
        return 'hace ' . $hours . ' ' . $hsTxt;
    }
    if ($rem === 30) {
        return 'hace ' . $hours . ' ' . $hsTxt . ' y media';
    }

    // fallback poco probable
    return 'hace ' . $hours . ' ' . $hsTxt . ' y ' . $rem . ' min';
}

/* =========================
   BUSINESS CONTEXT (REAL)
========================= */
function get_business_context() {
    return array(
        'brand' => 'NetFan',
        'jingles' => array(
            'precio_ars' => 32000,
            'pago_transferencia' => array('alias'=>'netfan2','titular'=>'Laura Pizzorno'),
            'descuento_volumen' => 'Si compra varios jingles: referencia autorizada 50% en la segunda canción.',
            'datos_para_letra' => array(
                'nombre_del_negocio','rubro','productos_o_servicios','localidad_ciudad_provincia_pais',
                'frase_o_slogan','telefono_o_redes_si_quiere_incluir','estilo_musical_preferido',
            ),
            'reglas_letra' => array(
                'Sin encabezados tipo "Estribillo/Verso".',
                'Letra limpia lista para usar.',
                'Objetivo 25-35 segundos aprox.',
                'Mencionar el nombre del negocio 2-3 veces.',
            ),
        ),
        'sistemastock' => array(
            'demo_10_dias_url' => 'https://nodo40.sistemastock.com/misistema/',
            'precio_mensual_ars' => 24000,
            'precio_anual_ars' => 240000,
            'pago_transferencia' => array('alias'=>'netfan2','titular'=>'Laura Pizzorno','enviar_comprobante_por'=>'WhatsApp'),
            'condiciones' => array(
                'sin_cobro_de_alta' => true,
                'sin_costo_de_baja' => true,
                'minimo_contratacion' => '1 mes',
                'formas_pago' => array('mes','trimestre','anio'),
                'descuento_pago_meses' => '10% si abona varios meses juntos',
            ),
            'faq' => array(
                'es' => 'Sistema para control diario del negocio: cuentas, stock, precios y herramientas para facilitar tareas.',
                'comercios' => array('kioscos','almacenes','ferreterias','panaderias','dietéticas','bares_y_restaurantes','carnicerias',
                    'venta_de_ropa','repuestos_autos_motos','decoracion_y_arte','jugueterias','librerias','articulos_escolares',
                    'regaleria','bijouterie_y_mercerias'),
                'funcionamiento' => array(
                    'Lectora de codigos opcional: escanea, suma, calcula vuelto, guarda en caja del dia.',
                    'Sin lectora: carga por teclado/busqueda.',
                    'Tickets: con impresora termica comun; no fiscales y fiscales. Puede incluir nombre del comercio, logo y redes.',
                    'Ingreso: llega por mail al registrarse (enlace al sistema).',
                    'Empleados: admin cambia precios y administra productos; empleado solo vende.',
                    'Vencimientos por lote: alerta 5 dias antes y el dia del vencimiento.',
                    'Caja del dia: guardado digital o impreso.',
                    'Productos: se pueden cargar nuevos; trae 95.000 productos de Argentina con codigo y nombre.',
                    'Promociones: se pueden crear; avisa si el cliente eligio promo.',
                    'Stock: cada venta descuenta stock.',
                    'Costo y venta: permite ambos; muestra caja menos costos para estimar ganancia neta aproximada.',
                    'Aumentos masivos: por porcentaje, por proveedor o categoria.',
                    'Alerta de poco stock: configurable por producto.',
                    'Venta por peso: kilos/gramos.',
                    'Facturacion: se conecta con servicios externos segun el pais.',
                    'Privilegios: admin puede limitar lo que ve el empleado.',
                    'Primer paso: cargar precios; luego listo para usar.',
                    'Codigos propios: permite imprimir codigos propios.',
                    'Hardware: lectora e impresora no incluidas; se compran por fuera.',
                ),
            ),
        ),
        'radiosnet' => array(
            'demo_15_dias' => true,
            'formularios' => array('campos' => array('nombre','email','sitio_web','telefono','servicio_a_probar')),
            'servicios' => array('portal_web_autoadministrable','panel_de_administracion','asesoramiento_google','streaming_audio','streaming_video','apps_moviles','soporte_24_7','planes_reseller'),
            'planes' => array(
                'solo_audio_web_simple_no_portal' => array('precio_ars_mes'=>27225,'incluye'=>array('sitio_web_simple','streaming_audio_ssl_https','chat_integrado','hosting'),'nota'=>'Sitio web simple (no permite cargar noticias).'),
                'combo_1' => array('precio_ars_mes'=>30000,'incluye'=>array('portal_web_autoadministrable','streaming_audio_standard','disenio_de_portal','registro_de_dominio')),
                'combo_2' => array('precio_ars_mes'=>36000,'precio_usd_mes_exterior_ref'=>24,'incluye'=>array('portal_web_autoadministrable','streaming_audio_https','disenio_de_portal','registro_de_dominio','hosting','app_movil_segun_bloque')),
                'combo_3_full_audio_video' => array('precio_ars_mes'=>59400,'precio_usd_mes_exterior_ref'=>42,'incluye'=>array('portal_web_autoadministrable','streaming_video_standard','streaming_audio_https','disenio_de_portal','hosting','app_movil_segun_bloque')),
                'portal_web_solo' => array('precio_ars_mes_desde'=>28000,'precio_usd_mes_exterior_ref'=>21,'incluye'=>array('portal_web_autoadministrable'),'nota'=>'Si contrata portal + streaming audio, segun nota debe sumar 10000 al precio del portal solo.','suma_audio_ars'=>10000),
            ),
            'descuentos' => array('sin_costo_alta'=>true,'sin_costo_baja'=>true,'sin_minimo_contratacion'=>true,'pago_trimestral_descuento'=>'10%','pago_anual_descuento'=>'15%'),
            'contacto' => array('email'=>'hola@radiosnet.org','telefonos'=>array('+54 9 341 6495220', '+54 9 341 5643881')),
            'nota_url_existente' => 'Si la radio ya tiene sitio web, puede seguir usando la misma URL: envian el logo y se encargan del resto.',
        ),
    );
}

/* =========================
   IA: PROMPT + LLAMADA API
========================= */
function get_ai_system_prompt() {
    $promptFile = __DIR__ . '/prompt_ai.php';
    if (is_file($promptFile)) {
        $c = @include $promptFile;
        if (is_string($c) && trim($c) !== '') return $c;
    }
    return 'Eres "Asistente Comercial NetFan". No inventes. Responde corto y seguro. Devuelve solo JSON con reply_to_send.';
}
function openai_chat_completion($messages, $temperature, $max_tokens) {
    if (!defined('OPENAI_API_KEY') || trim(OPENAI_API_KEY) === '' || OPENAI_API_KEY === 'PEGAR_TU_API_KEY_AQUI') {
        return array('ok'=>0, 'error'=>'Falta OPENAI_API_KEY');
    }

    $payload = array(
        'model' => OPENAI_MODEL,
        'messages' => $messages,
        'temperature' => $temperature,
        'max_tokens' => (int)$max_tokens,
    );

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => OPENAI_API_URL,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => OPENAI_TIMEOUT,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "Authorization: Bearer " . OPENAI_API_KEY
        ),
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
    ));

    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($err) return array('ok'=>0, 'error'=>$err, 'http'=>$code, 'raw'=>$resp);

    $data = json_decode($resp, true);
    if (!is_array($data)) return array('ok'=>0, 'error'=>'Respuesta OpenAI inválida', 'http'=>$code, 'raw'=>$resp);

    if ($code < 200 || $code >= 300) {
        $msg = 'Error OpenAI';
        if (isset($data['error']) && isset($data['error']['message'])) $msg = $data['error']['message'];
        return array('ok'=>0, 'error'=>$msg, 'http'=>$code, 'raw'=>$resp);
    }

    $content = '';
    if (isset($data['choices'][0]['message']['content'])) $content = (string)$data['choices'][0]['message']['content'];

    return array('ok'=>1, 'content'=>$content, 'raw'=>$resp, 'http'=>$code);
}

/* =========================
   WHISPER AUDIO TRANSCRIPTION
========================= */
function transcribir_audio_whisper($audio_url) {
    if (!defined('OPENAI_API_KEY') || trim(OPENAI_API_KEY) === '') {
        return array('ok'=>0, 'error'=>'Falta OPENAI_API_KEY');
    }

    $temp_file = tempnam(sys_get_temp_dir(), 'audio_') . '.mp3';
    $fp = fopen($temp_file, 'w+');

    $ch = curl_init($audio_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $success = curl_exec($ch);
    curl_close($ch);
    fclose($fp);

    if (!$success || @filesize($temp_file) < 100) {
        @unlink($temp_file);
        return array('ok'=>0, 'error'=>'No se pudo descargar el audio');
    }

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => WHISPER_API_URL,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => array(
            'file' => new CURLFile($temp_file, 'audio/mpeg', 'audio.mp3'),
            'model' => 'whisper-1',
            'response_format' => 'json',
            'language' => 'es'
        ),
        CURLOPT_HTTPHEADER => array(
            "Authorization: Bearer " . OPENAI_API_KEY
        ),
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
    ));

    $resp = curl_exec($ch);
    $err = curl_error($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    @unlink($temp_file);

    if ($err) return array('ok'=>0, 'error'=>$err, 'http'=>$code, 'raw'=>$resp);

    $data = json_decode($resp, true);
    if (!is_array($data)) return array('ok'=>0, 'error'=>'Respuesta Whisper inválida', 'http'=>$code, 'raw'=>$resp);

    if ($code < 200 || $code >= 300) {
        $msg = 'Error Whisper';
        if (isset($data['error']) && isset($data['error']['message'])) $msg = $data['error']['message'];
        return array('ok'=>0, 'error'=>$msg, 'http'=>$code, 'raw'=>$resp);
    }

    $texto = '';
    if (isset($data['text'])) $texto = trim($data['text']);
    if ($texto === '') return array('ok'=>0, 'error'=>'Transcripción vacía', 'http'=>$code, 'raw'=>$resp);

    return array('ok'=>1, 'texto'=>$texto, 'raw'=>$resp, 'http'=>$code);
}

function get_conversation_for_ai($pdo, $cid, $limit) {
    $cid = (int)$cid;
    $limit = max(10, (int)$limit);

    $stmt = $pdo->prepare("SELECT direccion, tipo, mensaje, fecha, media_path FROM charlas WHERE contacto_id = ? ORDER BY fecha DESC, id DESC LIMIT ".$limit);
    $stmt->execute(array($cid));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $rows = array_reverse($rows);

    $conv = array();
    foreach ($rows as $m) {
        $dir = (string)$m['direccion'];
        $from = ($dir === 'enviado') ? 'agente' : 'cliente';

        $texto = isset($m['mensaje']) ? trim((string)$m['mensaje']) : '';
        $tipo  = isset($m['tipo']) ? strtolower(trim((string)$m['tipo'])) : 'texto';
        $mediaPath = isset($m['media_path']) ? trim((string)$m['media_path']) : '';

        if ($mediaPath && $mediaPath !== 'NULL') {
            if ($texto === '') $texto = '[MEDIA]';
        }

        $texto = recortar_texto($texto, AI_MAX_CHARS_PER_MSG);

        $ts = '';
        if (!empty($m['fecha'])) {
            $t = strtotime($m['fecha']);
            if ($t) $ts = date('c', $t);
        }

        if ($texto === '' && !$mediaPath) continue;

        $conv[] = array(
            'from' => $from,
            'direction' => $dir,
            'text' => $texto,
            'ts' => $ts,
            'tipo' => $tipo
        );
    }
    return $conv;
}

function ai_safe_fallback($reason) {
    return array(
        'service_detected' => 'NO_CLARO',
        'confidence' => 0.0,
        'lead_stage' => 'sin_respuesta',
        'customer_intent' => 'otro',
        'missing_data' => array(),
        'reply_to_send' => 'Dale, lo reviso y te confirmo en breve. Gracias por la paciencia.',
        'notes_for_system' => 'Fallback seguro: ' . $reason,
        'send_policy' => array('safe_to_send' => false, 'reason_if_false' => $reason),
        'action' => 'HUMAN_TAKEOVER'
    );
}
function ai_parse_and_sanitize($content) {
    $content = trim((string)$content);
    $parsed = json_decode($content, true);
    if (!is_array($parsed) || !isset($parsed['reply_to_send'])) return null;

    $parsed['reply_to_send'] = normalizar_mensaje((string)$parsed['reply_to_send']);
    $parsed['reply_to_send'] = preg_replace('/[\x{1F300}-\x{1FAFF}\x{2600}-\x{26FF}\x{2700}-\x{27BF}]/u', '', $parsed['reply_to_send']);

    if (!isset($parsed['send_policy']) || !is_array($parsed['send_policy'])) $parsed['send_policy'] = array('safe_to_send'=>false,'reason_if_false'=>'Sin send_policy');
    if (!array_key_exists('safe_to_send', $parsed['send_policy'])) $parsed['send_policy']['safe_to_send'] = false;
    if (!isset($parsed['action'])) $parsed['action'] = ($parsed['send_policy']['safe_to_send'] ? 'DRAFT' : 'HUMAN_TAKEOVER');

    return $parsed;
}

/* =========================
   AJAX: TRANSCRIBIR AUDIO
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_transcribir_audio']) && $_POST['ajax_transcribir_audio'] == '1') {
    if (ob_get_level()) @ob_clean();
    header('Content-Type: application/json; charset=utf-8');

    $audio_url = isset($_POST['audio_url']) ? trim($_POST['audio_url']) : '';
    if ($audio_url === '') { echo json_encode(array('ok'=>0, 'message'=>'Falta URL de audio')); exit; }

    $hashKey = md5("transcribe:$audio_url");
    if (es_post_repetido($hashKey, 10)) { echo json_encode(array('ok'=>0, 'message'=>'Transcripción en proceso')); exit; }

    $resultado = transcribir_audio_whisper($audio_url);

    $log = "==== ".date('Y-m-d H:i:s')." ====\nWHISPER_TRANSCRIBE\nAUDIO_URL: {$audio_url}\nOK: ".(int)$resultado['ok']."\nERR: ".(isset($resultado['error'])?$resultado['error']:'')."\nTEXTO: ".(isset($resultado['texto'])?$resultado['texto']:'')."\n\n";
    @file_put_contents(__DIR__ . '/debug_caliente_whisper.log', $log, FILE_APPEND);

    if (empty($resultado['ok'])) { echo json_encode(array('ok'=>0, 'message'=> isset($resultado['error']) ? $resultado['error'] : 'Error en transcripción')); exit; }
    echo json_encode(array('ok'=>1, 'texto'=> $resultado['texto'])); exit;
}

/* =========================
   AJAX: PREGUNTAS
========================= */
if (isset($_GET['ajax_preguntas']) && $_GET['ajax_preguntas'] == '1') {
    if (ob_get_level()) @ob_clean();
    header('Content-Type: application/json; charset=utf-8');
    $stmt = $pdo->query("SELECT id, categoria, titulo, texto FROM preguntas WHERE activo=1 ORDER BY categoria ASC, titulo ASC");
    echo json_encode(array('ok'=>1, 'preguntas'=>$stmt->fetchAll(PDO::FETCH_ASSOC)));
    exit;
}

/* =========================
   IFRAME (últimos 15)
========================= */
if (isset($_GET['iframe']) && $_GET['iframe'] == '1') {
    if (ob_get_level()) @ob_clean();
    $cid = isset($_GET['contacto_id']) ? (int)$_GET['contacto_id'] : 0;
    header('Content-Type: text/html; charset=utf-8');
    if ($cid <= 0) { echo "<!doctype html><html><body>Sin contacto</body></html>"; exit; }

    $stmt = $pdo->prepare("SELECT direccion, tipo, mensaje, fecha, media_path FROM charlas WHERE contacto_id = ? ORDER BY fecha DESC, id DESC LIMIT 15");
    $stmt->execute(array($cid));
    $msgs = array_reverse($stmt->fetchAll(PDO::FETCH_ASSOC));
    ?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html,body{height:100%;margin:0}
body{padding:10px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;background:#e5ddd5 url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAGklEQVQYlWNgYGD4T0VgYGBgYGBgYKAqmBYAAHoYBAKCqz9gAAAAAElFTkSuQmCC');overflow-y:auto;overflow-x:hidden}
.wrap{display:flex;flex-direction:column;gap:8px;padding-bottom:10px}
.msg{max-width:75%;padding:7px 9px;border-radius:8px;font-size:14px;line-height:1.4;word-wrap:break-word;box-shadow:0 1px 0.5px rgba(0,0,0,0.13)}
.enviado{margin-left:auto;background:#d9fdd3;border-radius:8px 0 8px 8px}
.recibido{margin-right:auto;background:#fff;border-radius:0 8px 8px 8px}
.msgContent{margin-bottom:2px}
.meta{font-size:11px;color:rgba(0,0,0,0.45);margin-top:4px;text-align:right;user-select:none}
.msgMedia{margin:4px 0;border-radius:8px;overflow:hidden;max-width:100%}
.msgMedia img{display:block;max-width:100%;height:auto;max-height:280px;cursor:pointer;transition:opacity 0.2s}
.msgMedia img:hover{opacity:0.92}
.msgAudio{background:rgba(0,0,0,0.05);border-radius:18px;padding:8px 12px;display:flex;align-items:center;gap:10px;margin:4px 0;min-width:200px}
.audioIcon{width:32px;height:32px;border-radius:50%;background:#00a884;display:flex;align-items:center;justify-content:center;font-size:16px}
.audioWave{flex:1;height:20px;display:flex;align-items:center;gap:2px}
.audioBar{width:3px;background:rgba(0,0,0,0.2);border-radius:2px;animation:wave 1.2s ease-in-out infinite}
.audioBar:nth-child(1){animation-delay:0s;height:30%}
.audioBar:nth-child(2){animation-delay:0.1s;height:50%}
.audioBar:nth-child(3){animation-delay:0.2s;height:70%}
.audioBar:nth-child(4){animation-delay:0.3s;height:85%}
.audioBar:nth-child(5){animation-delay:0.4s;height:60%}
.audioBar:nth-child(6){animation-delay:0.5s;height:75%}
@keyframes wave{0%,100%{transform:scaleY(0.5)}50%{transform:scaleY(1)}}
.msgVideo{border-radius:8px;overflow:hidden;margin:4px 0;background:#000;max-width:100%}
.msgVideo video{display:block;max-width:100%;height:auto;max-height:280px}
.msgDoc{background:rgba(0,0,0,0.05);border-radius:8px;padding:10px 12px;display:flex;align-items:center;gap:12px;margin:4px 0;cursor:pointer}
.msgDoc:hover{background:rgba(0,0,0,0.08)}
.docIcon{width:36px;height:36px;background:#00a884;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:18px}
.docName{font-size:13px;font-weight:500;color:#111}
.mediaLink{background:rgba(0,0,0,0.05);border-radius:8px;padding:12px;text-align:center;margin:4px 0}
.mediaLink a{color:#00a884;text-decoration:none;font-size:13px;font-weight:700}
.lightbox{display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.95);z-index:9999;align-items:center;justify-content:center;cursor:zoom-out}
.lightbox.show{display:flex}
.lightbox img{max-width:95%;max-height:95%;object-fit:contain}
.lightboxClose{position:absolute;top:20px;right:20px;width:40px;height:40px;background:rgba(255,255,255,0.2);border:none;border-radius:50%;color:#fff;font-size:24px;cursor:pointer}
.lightboxClose:hover{background:rgba(255,255,255,0.3)}
.empty{text-align:center;padding:40px 20px;color:rgba(0,0,0,0.4);font-size:14px}
.transcribeBtn{display:inline-block;background:#007bff;color:white;border:none;border-radius:4px;padding:4px 8px;font-size:11px;cursor:pointer;margin-top:5px;text-decoration:none}
.transcribeBtn:hover{background:#0056b3}
.transcribeBtn:disabled{background:#ccc;cursor:not-allowed}
.transcriptionResult{margin-top:8px;padding:8px;background:#f8f9fa;border-radius:6px;border-left:3px solid #007bff;font-size:13px;line-height:1.4}
</style>
</head>
<body>
<div class="wrap" id="wrap">
<?php if (!$msgs): ?>
    <div class="empty">No hay mensajes aún</div>
<?php else: foreach ($msgs as $m):
    $cl = ($m['direccion'] === 'enviado') ? 'enviado' : 'recibido';
    $tipo = isset($m['tipo']) ? strtolower(trim((string)$m['tipo'])) : 'texto';
    $texto = isset($m['mensaje']) ? trim((string)$m['mensaje']) : '';
    $mediaPath = isset($m['media_path']) ? trim((string)$m['media_path']) : '';

    $mediaUrl = '';
    if ($mediaPath && $mediaPath !== 'NULL') {
        $mediaUrl = (strpos($mediaPath, 'http') === 0) ? $mediaPath : MEDIA_BASE_URL . $mediaPath;
    }

    $tipoReal = 'texto';
    if ($mediaUrl) {
        $ext = strtolower(pathinfo($mediaPath, PATHINFO_EXTENSION));
        if ($ext && in_array($ext, array('jpg','jpeg','png','gif','webp','bmp','svg'))) $tipoReal = 'imagen';
        elseif ($ext && in_array($ext, array('mp3','ogg','wav','opus','m4a','aac','oga'))) $tipoReal = 'audio';
        elseif ($ext && in_array($ext, array('mp4','webm','mov','avi','mkv'))) $tipoReal = 'video';
        elseif ($ext && in_array($ext, array('pdf','doc','docx','xls','xlsx','zip','rar','txt'))) $tipoReal = 'documento';
        else {
            if (in_array($tipo, array('imagen','image'))) $tipoReal = 'imagen';
            elseif (in_array($tipo, array('audio','voice','ptt'))) $tipoReal = 'audio';
            elseif ($tipo === 'video') $tipoReal = 'video';
            elseif (in_array($tipo, array('documento','document'))) $tipoReal = 'documento';
            else $tipoReal = 'imagen';
        }
    }

    $hora = '';
    if (!empty($m['fecha'])) {
        $ts = strtotime($m['fecha']);
        if ($ts) $hora = date('H:i', $ts);
    }

    $audioId = uniqid('audio_');
    $ocrId = uniqid('ocr_');
?>
    <div class="msg <?php echo $cl; ?>">

        <?php if ($mediaUrl && $tipoReal === 'imagen'): ?>
            <div class="msgMedia">
                <img src="<?php echo h($mediaUrl); ?>" alt="Imagen" loading="lazy"
                     onclick="openLightbox('<?php echo h($mediaUrl); ?>')"
                     onerror="this.parentElement.innerHTML='<div class=\'mediaLink\'><a href=\'<?php echo h($mediaUrl); ?>\' target=\'_blank\'>Ver imagen</a></div>';"/>
            </div>

            <div style="margin-top:6px;">
                <a href="javascript:void(0)"
                   class="transcribeBtn"
                   onclick="ocrFlyer(this, <?php echo (int)$cid; ?>, '<?php echo h($mediaUrl); ?>', '<?php echo $ocrId; ?>')">OCR flyer</a>
                <div id="ocr-<?php echo $ocrId; ?>" class="transcriptionResult" style="display:none;"></div>
            </div>

            <?php if ($texto && !preg_match('/^\[.*\]/', $texto)): ?>
                <div class="msgContent"><?php echo nl2br(h($texto)); ?></div>
            <?php endif; ?>

        <?php elseif ($mediaUrl && in_array($tipoReal, array('audio','voice','ptt'))): ?>
            <div class="msgAudio">
                <div class="audioIcon">♪</div>
                <div class="audioWave">
                    <?php for($i=0;$i<6;$i++): ?><div class="audioBar"></div><?php endfor; ?>
                </div>
            </div>
            <audio controls style="width:100%;margin-top:4px;">
                <source src="<?php echo h($mediaUrl); ?>" type="audio/mpeg">
            </audio>

            <div>
                <button class="transcribeBtn" onclick="transcribirAudio(this, '<?php echo h($mediaUrl); ?>', '<?php echo $audioId; ?>')">
                    Transcribir audio
                </button>
                <div id="transcription-<?php echo $audioId; ?>" class="transcriptionResult" style="display:none;"></div>
            </div>

            <?php if ($texto && !preg_match('/^\[.*\]/', $texto)): ?>
                <div class="msgContent" style="margin-top:4px;"><?php echo nl2br(h($texto)); ?></div>
            <?php endif; ?>

        <?php elseif ($mediaUrl && $tipoReal === 'video'): ?>
            <div class="msgVideo">
                <video controls><source src="<?php echo h($mediaUrl); ?>" type="video/mp4"></video>
            </div>
            <?php if ($texto && !preg_match('/^\[.*\]/', $texto)): ?>
                <div class="msgContent"><?php echo nl2br(h($texto)); ?></div>
            <?php endif; ?>

        <?php elseif ($mediaUrl && $tipoReal === 'documento'): ?>
            <div class="msgDoc" onclick="window.open('<?php echo h($mediaUrl); ?>','_blank')">
                <div class="docIcon">DOC</div>
                <div><div class="docName"><?php echo h($texto ? $texto : 'Documento'); ?></div></div>
            </div>

        <?php else: ?>
            <?php
                $mostrar = $texto;
                if (!$mediaUrl && $tipo !== 'texto' && $tipo !== '') {
                    $pref = '[' . strtoupper($tipo) . '] ';
                    if (strpos($mostrar, $pref) !== 0) $mostrar = $pref . $mostrar;
                    if ($mostrar === $pref) $mostrar = $pref . '(sin texto)';
                }
            ?>
            <div class="msgContent"><?php echo nl2br(h($mostrar)); ?></div>
        <?php endif; ?>

        <?php if ($hora): ?><div class="meta"><?php echo h($hora); ?></div><?php endif; ?>
    </div>
<?php endforeach; endif; ?>
<div id="bottom"></div>
</div>

<div class="lightbox" id="lightbox" onclick="closeLightbox()">
    <button class="lightboxClose" onclick="closeLightbox();event.stopPropagation();">×</button>
    <img id="lightboxImg" src="" alt="">
</div>

<script>
(function(){
    function scrollBottom(){var b=document.getElementById('bottom');if(b)b.scrollIntoView({block:'end',behavior:'auto'});}
    if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',function(){setTimeout(scrollBottom,20);setTimeout(scrollBottom,150);setTimeout(scrollBottom,400);});}
    else{setTimeout(scrollBottom,20);setTimeout(scrollBottom,150);setTimeout(scrollBottom,400);}
    window.addEventListener('load',function(){setTimeout(scrollBottom,50);setTimeout(scrollBottom,200);});
})();
function openLightbox(src){document.getElementById('lightboxImg').src=src;document.getElementById('lightbox').classList.add('show');}
function closeLightbox(){document.getElementById('lightbox').classList.remove('show');}
document.addEventListener('keydown',function(e){if(e.key==='Escape')closeLightbox();});

async function transcribirAudio(btn, audioUrl, audioId) {
    var resultDiv = document.getElementById('transcription-' + audioId);
    if (!btn || !resultDiv) return;

    btn.disabled = true;
    btn.textContent = 'Transcribiendo...';
    resultDiv.style.display = 'none';

    var fd = new FormData();
    fd.append('ajax_transcribir_audio', '1');
    fd.append('audio_url', audioUrl);

    try {
        var r = await fetch('caliente.php', {method: 'POST', body: fd, cache: 'no-store'});
        var data = await r.json();

        if (data.ok === 1 && data.texto) {
            resultDiv.innerHTML = '<strong>Transcripción:</strong><br>' + String(data.texto).replace(/\n/g, '<br>');
            resultDiv.style.display = 'block';
            btn.textContent = 'Transcribir audio';
        } else {
            resultDiv.innerHTML = '<strong>Error:</strong> ' + (data.message || 'No se pudo transcribir');
            resultDiv.style.display = 'block';
            btn.textContent = 'Transcribir audio';
        }
    } catch(e) {
        console.error(e);
        resultDiv.innerHTML = '<strong>Error de red:</strong> No se pudo conectar';
        resultDiv.style.display = 'block';
        btn.textContent = 'Transcribir audio';
    } finally {
        btn.disabled = false;
    }
}

async function ocrFlyer(btn, cid, imageUrl, ocrId) {
    var box = document.getElementById('ocr-' + ocrId);
    if (!btn || !box) return;

    btn.style.pointerEvents = 'none';
    var old = btn.textContent;
    btn.textContent = 'Leyendo...';
    box.style.display = 'none';
    box.innerHTML = '';

    var fd = new FormData();
    fd.append('contacto_id', String(cid));
    fd.append('image_url', imageUrl);

    try {
        var r = await fetch('reconocer_ocr.php', {method: 'POST', body: fd, cache: 'no-store'});
        var data = await r.json();

        if (data && data.ok === 1 && data.texto) {
            box.innerHTML = '<strong>Texto detectado:</strong><br>' + String(data.texto).replace(/\n/g, '<br>');
            box.style.display = 'block';
            btn.textContent = 'OCR listo';
        } else {
            box.innerHTML = '<strong>Error:</strong> ' + (data && data.error ? data.error : 'No se pudo leer');
            box.style.display = 'block';
            btn.textContent = old;
            btn.style.pointerEvents = 'auto';
        }
    } catch (e) {
        console.error(e);
        box.innerHTML = '<strong>Error de red:</strong> No se pudo conectar';
        box.style.display = 'block';
        btn.textContent = old;
        btn.style.pointerEvents = 'auto';
    }
}
</script>
</body>
</html>
<?php
    exit;
}

/* =========================
   AJAX: SEND TEXTO
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_send']) && $_POST['ajax_send'] == '1') {
    if (ob_get_level()) @ob_clean();
    header('Content-Type: application/json; charset=utf-8');

    $cid = isset($_POST['contacto_id']) ? (int)$_POST['contacto_id'] : 0;
    $msg = isset($_POST['mensaje']) ? normalizar_mensaje($_POST['mensaje']) : '';

    if ($cid <= 0 || $msg === '') { echo json_encode(array('ok'=>0, 'message'=>'Falta contacto o mensaje')); exit; }

    $hashKey = md5("cid:$cid|msg:$msg");
    if (es_post_repetido($hashKey, 20)) { echo json_encode(array('ok'=>1, 'blocked'=>1, 'message'=>'Repetido')); exit; }

    $stmt = $pdo->prepare("SELECT telefono FROM contactos WHERE id = ? LIMIT 1");
    $stmt->execute(array($cid));
    $tel = $stmt->fetchColumn();
    if (!$tel) { echo json_encode(array('ok'=>0, 'message'=>'No se encontró teléfono')); exit; }

    $resultado = enviar_whatsapp_texto($tel, $msg);

    $log = "==== ".date('Y-m-d H:i:s')." ====\nCID: {$cid}\nTEL: {$tel}\nMSG: {$msg}\nRES: ".json_encode($resultado)."\n\n";
    @file_put_contents(__DIR__ . '/debug_caliente_send.log', $log, FILE_APPEND);

    if (empty($resultado['success'])) {
        $err = isset($resultado['error']) ? $resultado['error'] : 'Error';
        echo json_encode(array('ok'=>0, 'message'=>$err));
        exit;
    }
    echo json_encode(array('ok'=>1, 'message'=>'Enviado'));
    exit;
}

/* =========================
   AJAX: SEND AUDIO
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_send_audio']) && $_POST['ajax_send_audio'] == '1') {
    if (ob_get_level()) @ob_clean();
    header('Content-Type: application/json; charset=utf-8');

    $cid = isset($_POST['contacto_id']) ? (int)$_POST['contacto_id'] : 0;
    $audio_url = isset($_POST['audio_url']) ? trim($_POST['audio_url']) : '';

    if ($cid <= 0 || $audio_url === '') { echo json_encode(array('ok'=>0, 'message'=>'Falta contacto o URL de audio')); exit; }

    $hashKey = md5("cid:$cid|audio:$audio_url");
    if (es_post_repetido($hashKey, 20)) { echo json_encode(array('ok'=>1, 'blocked'=>1, 'message'=>'Repetido')); exit; }

    $stmt = $pdo->prepare("SELECT telefono FROM contactos WHERE id = ? LIMIT 1");
    $stmt->execute(array($cid));
    $tel = $stmt->fetchColumn();
    if (!$tel) { echo json_encode(array('ok'=>0, 'message'=>'No se encontró teléfono')); exit; }

    $resultado = enviar_whatsapp_audio($tel, $audio_url);

    $log = "==== ".date('Y-m-d H:i:s')." ====\nCID: {$cid}\nTEL: {$tel}\nAUDIO_URL: {$audio_url}\nRES: ".json_encode($resultado)."\n\n";
    @file_put_contents(__DIR__ . '/debug_caliente_audio.log', $log, FILE_APPEND);

    if (empty($resultado['success'])) {
        $err = isset($resultado['error']) ? $resultado['error'] : 'Error';
        echo json_encode(array('ok'=>0, 'message'=>$err));
        exit;
    }
    echo json_encode(array('ok'=>1, 'message'=>'Audio enviado'));
    exit;
}

/* =========================
   AJAX: IA (BORRADOR)
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_ai']) && $_POST['ajax_ai'] == '1') {
    if (ob_get_level()) @ob_clean();
    header('Content-Type: application/json; charset=utf-8');

    $cid = isset($_POST['contacto_id']) ? (int)$_POST['contacto_id'] : 0;
    if ($cid <= 0) { echo json_encode(array('ok'=>0, 'message'=>'Falta contacto')); exit; }

    $hashKey = md5("ai:cid:$cid");
    if (es_post_repetido($hashKey, 8)) {
        echo json_encode(array('ok'=>1, 'message'=>'Repetido', 'data'=>ai_safe_fallback('Click repetido')));
        exit;
    }

    $stmt = $pdo->prepare("SELECT nombre, telefono FROM contactos WHERE id = ? LIMIT 1");
    $stmt->execute(array($cid));
    $contact = $stmt->fetch(PDO::FETCH_ASSOC);
    $nombre = (is_array($contact) && isset($contact['nombre'])) ? (string)$contact['nombre'] : '';
    $tel    = (is_array($contact) && isset($contact['telefono'])) ? (string)$contact['telefono'] : '';

    $conversation = get_conversation_for_ai($pdo, $cid, AI_MAX_MSGS);
    if (!$conversation || count($conversation) < 1) {
        $fallback = ai_safe_fallback('No hay conversación para analizar');
        echo json_encode(array('ok'=>1, 'data'=>$fallback, 'reply'=>$fallback['reply_to_send']));
        exit;
    }

    $business_context = get_business_context();
    $customer_profile = array('nombre'=>$nombre,'telefono'=>$tel);

    $input = array(
        'conversation' => $conversation,
        'customer_profile' => $customer_profile,
        'business_context' => $business_context
    );

    $messages = array(
        array('role' => 'system', 'content' => get_ai_system_prompt()),
        array('role' => 'user', 'content' => "INPUT JSON:\n" . json_encode($input, JSON_UNESCAPED_UNICODE))
    );

    $resp = openai_chat_completion($messages, 0.2, AI_MAX_OUTPUT_TOKENS);

    $log = "==== ".date('Y-m-d H:i:s')." ====\nCID: {$cid}\nOPENAI_OK: ".(int)$resp['ok']."\nHTTP: ".(isset($resp['http'])?$resp['http']:'')."\nERR: ".(isset($resp['error'])?$resp['error']:'')."\nCONTENT:\n".(isset($resp['content'])?$resp['content']:'')."\n\n";
    @file_put_contents(__DIR__ . '/debug_caliente_ai.log', $log, FILE_APPEND);

    if (empty($resp['ok'])) {
        $fallback = ai_safe_fallback(isset($resp['error']) ? $resp['error'] : 'Error OpenAI');
        echo json_encode(array('ok'=>1, 'data'=>$fallback, 'reply'=>$fallback['reply_to_send']));
        exit;
    }

    $parsed = ai_parse_and_sanitize($resp['content']);
    if (!is_array($parsed) || !isset($parsed['reply_to_send'])) {
        $fallback = ai_safe_fallback('La IA no devolvió JSON válido');
        echo json_encode(array('ok'=>1, 'data'=>$fallback, 'reply'=>$fallback['reply_to_send']));
        exit;
    }

    $safe = (isset($parsed['send_policy']) && isset($parsed['send_policy']['safe_to_send'])) ? (bool)$parsed['send_policy']['safe_to_send'] : false;
    $action = isset($parsed['action']) ? (string)$parsed['action'] : ($safe ? 'DRAFT' : 'HUMAN_TAKEOVER');

    if (!$safe || $action === 'HUMAN_TAKEOVER') {
        $parsed['reply_to_send'] = 'Dale, lo reviso y te confirmo en breve. Gracias por la paciencia.';
        $parsed['send_policy']['safe_to_send'] = false;
        $parsed['action'] = 'HUMAN_TAKEOVER';
    } else {
        $parsed['action'] = ($action === 'SEND') ? 'DRAFT' : $action;
    }

    echo json_encode(array('ok'=>1, 'data'=>$parsed, 'reply'=>$parsed['reply_to_send']), JSON_UNESCAPED_UNICODE);
    exit;
}

/* =========================
   LISTADO / FILTRO OPCIONAL
   - por defecto: muestra más recientes
   - opcional: solo >= MIN_HORAS (minh=1)
========================= */
$filtrarHoras = (isset($_GET['minh']) && $_GET['minh'] == '1') ? true : false;

$pag = max(1, isset($_GET['p']) ? (int)$_GET['p'] : 1);
$offset = ($pag - 1) * $POR_PAGINA;

$whereAge = '';
if ($filtrarHoras) {
    $whereAge = " AND lastm.fecha <= DATE_SUB(NOW(), INTERVAL ".(int)$MIN_HORAS." HOUR) ";
}

$SQL_BASE = "
    FROM contactos c
    JOIN (
        SELECT ch.contacto_id, MAX(ch.id) AS last_id FROM charlas ch
        JOIN (SELECT contacto_id, MAX(fecha) AS max_fecha FROM charlas GROUP BY contacto_id) mx
        ON mx.contacto_id = ch.contacto_id AND ch.fecha = mx.max_fecha
        GROUP BY ch.contacto_id
    ) lastx ON lastx.contacto_id = c.id
    JOIN charlas lastm ON lastm.id = lastx.last_id
    JOIN (SELECT contacto_id, COUNT(*) AS total_msgs FROM charlas GROUP BY contacto_id) stats ON stats.contacto_id = c.id
    WHERE lastm.direccion = 'recibido'
    {$whereAge}
";

$total = (int)$pdo->query("SELECT COUNT(*) FROM (SELECT c.id $SQL_BASE) t")->fetchColumn();
$totalPaginas = max(1, (int)ceil($total / $POR_PAGINA));
if ($pag > $totalPaginas) { $pag = $totalPaginas; $offset = ($pag - 1) * $POR_PAGINA; }

$stmtL = $pdo->prepare("SELECT c.id, c.nombre, c.telefono, lastm.mensaje AS ultimo_mensaje, lastm.fecha AS ultima_fecha, stats.total_msgs $SQL_BASE ORDER BY lastm.fecha DESC, c.id DESC LIMIT :off, :lim");
$stmtL->bindValue(':off', (int)$offset, PDO::PARAM_INT);
$stmtL->bindValue(':lim', (int)$POR_PAGINA, PDO::PARAM_INT);
$stmtL->execute();
$rows = $stmtL->fetchAll(PDO::FETCH_ASSOC);

if (ob_get_level()) @ob_clean();

// qs para paginación manteniendo filtro
$qsMinh = $filtrarHoras ? '&minh=1' : '';
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Calientes</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{box-sizing:border-box}
body{margin:0;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;background:#f0f2f5;color:#111b21}
#loadingOverlay{position:fixed;top:0;left:0;right:0;bottom:0;background:linear-gradient(135deg,rgba(0,0,0,0.95),rgba(20,20,20,0.92));z-index:99999;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:28px;backdrop-filter:blur(10px)}
.loadingEmoji{font-size:64px;animation:pulse 1.8s ease-in-out infinite;filter:drop-shadow(0 0 20px rgba(255,100,50,0.5))}
@keyframes pulse{0%,100%{transform:scale(1);opacity:1}50%{transform:scale(1.15);opacity:0.85}}
.spinner{width:70px;height:70px;border:5px solid rgba(255,255,255,0.1);border-top-color:#00a884;border-bottom-color:#00a884;border-radius:50%;animation:spin 1s ease-in-out infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.loadingText{color:#fff;font-size:18px;font-weight:800;text-align:center;line-height:1.7;letter-spacing:0.3px;text-shadow:0 2px 8px rgba(0,0,0,0.3)}
.topbar{position:sticky;top:0;z-index:10;background:#fff;border-bottom:1px solid #d1d7db;padding:14px 16px;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;box-shadow:0 1px 2px rgba(0,0,0,0.05)}
.titleRow{display:flex;align-items:center;gap:10px}
.titleEmoji{font-size:24px;animation:flame 2s ease-in-out infinite}
@keyframes flame{0%,100%{transform:translateY(0) scale(1)}50%{transform:translateY(-3px) scale(1.05)}}
.title{font-weight:900;font-size:20px;background:linear-gradient(135deg,#ff6b35,#f7931e);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.sub{color:#667781;font-size:12px;font-weight:700;margin-top:5px}
.topLinks{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.topLinks a{text-decoration:none;color:#008069;background:#eef2f3;border:1px solid rgba(0,0,0,0.06);padding:9px 15px;border-radius:10px;font-weight:800;font-size:13px;transition:all 0.25s cubic-bezier(0.4,0,0.2,1)}
.topLinks a:hover{background:#d9fdd3;transform:translateY(-2px);box-shadow:0 4px 8px rgba(0,128,105,0.15)}
.pager{display:flex;gap:10px;align-items:center;font-weight:800}
.pager a{text-decoration:none;color:#008069;background:#eef2f3;border:1px solid rgba(0,0,0,0.06);padding:9px 14px;border-radius:10px;transition:all 0.25s;font-size:13px}
.pager a:hover{background:#d9fdd3;transform:translateY(-2px)}
.pager span{color:#667781;font-size:14px}
.wrap{padding:16px}

/* 3 columnas (desktop), 2 (med), 1 (mobile) */
.grid{display:grid;grid-template-columns:repeat(3, minmax(320px, 1fr));gap:16px}
@media(max-width:1200px){.grid{grid-template-columns:repeat(2, minmax(320px, 1fr));}}
@media(max-width:768px){.grid{grid-template-columns:1fr}}

.card{background:#fff;border:1px solid #d1d7db;border-radius:16px;box-shadow:0 2px 4px rgba(0,0,0,0.06);overflow:hidden;transition:all 0.4s cubic-bezier(0.4,0,0.2,1)}
.card:hover{box-shadow:0 8px 16px rgba(0,0,0,0.1);transform:translateY(-4px)}
.card.success-fade{animation:successFade 0.75s cubic-bezier(0.4,0,0.2,1) forwards}
@keyframes successFade{0%{background:#d9fdd3;transform:scale(1);box-shadow:0 0 0 0 rgba(0,168,132,0.4)}40%{background:#a8f5d1;transform:scale(1.03);box-shadow:0 0 0 10px rgba(0,168,132,0)}100%{opacity:0;transform:scale(0.92) translateY(-30px)}}
.cardHead{padding:15px 15px 13px;border-bottom:1px solid rgba(0,0,0,0.06);display:flex;justify-content:space-between;gap:12px;background:linear-gradient(135deg,#fff,#f9fafb)}
.who{min-width:0;flex:1}
.name{font-weight:900;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#111b21}
.phone{color:#667781;font-size:12px;font-weight:700;margin-top:4px}
.right{text-align:right;flex-shrink:0}
.dt{color:#667781;font-size:12px;font-weight:800;white-space:nowrap}
.badges{margin-top:8px;display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap}
.badge{font-size:10px;font-weight:900;padding:5px 10px;border-radius:12px;border:1px solid rgba(0,0,0,0.08);background:#eef2f3;color:#111b21;letter-spacing:0.4px}
.badge-green{background:rgba(0,168,132,0.12);border-color:rgba(0,168,132,0.3);color:#008069}
.badge-gray{background:rgba(0,0,0,0.06);border-color:rgba(0,0,0,0.12);color:#445}
.badge-purple{background:rgba(155,89,182,0.12);border-color:rgba(155,89,182,0.3);color:#6d2f85}
.body{padding:15px;display:flex;flex-direction:column;gap:12px}
.iframeBox{border:1px solid rgba(0,0,0,0.08);border-radius:14px;overflow:hidden;background:#e5ddd5;box-shadow:inset 0 2px 4px rgba(0,0,0,0.06)}
iframe{width:100%;height:300px;border:0;display:block}
textarea{width:100%;min-height:95px;resize:vertical;border:1px solid rgba(0,0,0,0.12);border-radius:14px;padding:12px 14px;font-size:14px;outline:none;background:#f7f8fa;font-family:inherit;line-height:1.5;transition:all 0.25s}
textarea:focus{background:#fff;border-color:rgba(0,168,132,0.5);box-shadow:0 0 0 4px rgba(0,168,132,0.08)}
textarea::placeholder{color:#9ca3af}
.btnRow{display:flex;gap:10px;flex-wrap:wrap}
.btn{flex:1;min-width:110px;padding:12px 16px;border-radius:12px;border:1px solid rgba(0,0,0,0.12);background:#fff;cursor:pointer;font-weight:900;font-size:13px;transition:all 0.25s cubic-bezier(0.4,0,0.2,1);display:flex;align-items:center;justify-content:center;gap:7px}
.btn:hover:not(:disabled){background:#f5f6f6;transform:translateY(-2px);box-shadow:0 4px 8px rgba(0,0,0,0.1)}
.btn:active:not(:disabled){transform:translateY(0)}
.btnSend{background:linear-gradient(135deg,#00a884,#008069);border-color:#00a884;color:#fff}
.btnSend:hover:not(:disabled){background:linear-gradient(135deg,#008069,#006d57);border-color:#008069;box-shadow:0 4px 12px rgba(0,168,132,0.3)}
.btnSend:disabled{opacity:.5;cursor:not-allowed;transform:none}
.btnPreguntas{background:linear-gradient(135deg,#9b59b6,#8e44ad);border-color:#9b59b6;color:#fff}
.btnPreguntas:hover{background:linear-gradient(135deg,#8e44ad,#7d3c98);border-color:#8e44ad;box-shadow:0 4px 12px rgba(155,89,182,0.3)}
.btnAI{background:linear-gradient(135deg,#1f6feb,#0ea5e9);border-color:#1f6feb;color:#fff}
.btnAI:hover:not(:disabled){background:linear-gradient(135deg,#0b5bd3,#0284c7);border-color:#0b5bd3;box-shadow:0 4px 12px rgba(14,165,233,0.25)}
.btnAudio{background:linear-gradient(135deg,#8a2387,#f27121);border-color:#8a2387;color:#fff}
.btnAudio:hover:not(:disabled){background:linear-gradient(135deg,#7d1b7a,#e65c19);border-color:#7d1b7a;box-shadow:0 4px 12px rgba(138,35,135,0.3)}
.btnKeep{background:linear-gradient(135deg,#4b5563,#111827);border-color:#374151;color:#fff}
.btnKeep:hover:not(:disabled){background:linear-gradient(135deg,#374151,#0b1220);border-color:#374151;box-shadow:0 4px 12px rgba(0,0,0,0.25)}
.btnKeep.active{outline:3px solid rgba(17,24,39,0.15);box-shadow:0 0 0 4px rgba(17,24,39,0.08)}
.toast{position:fixed;right:20px;bottom:20px;background:#fff;border:1px solid #d1d7db;border-radius:16px;box-shadow:0 12px 40px rgba(0,0,0,0.2),0 0 0 1px rgba(0,0,0,0.05);padding:16px 20px;min-width:280px;max-width:400px;display:none;z-index:10001;animation:slideInUp 0.4s cubic-bezier(0.4,0,0.2,1)}
@keyframes slideInUp{from{transform:translateY(100px);opacity:0}to{transform:translateY(0);opacity:1}}
.toastT{font-weight:900;margin-bottom:5px;font-size:16px}
.toastS{color:#667781;font-size:13px;font-weight:600;line-height:1.5}
.empty{padding:60px 24px;background:#fff;border:1px solid #d1d7db;border-radius:16px;text-align:center;color:#667781;font-weight:800;font-size:16px;line-height:1.8}
.modalOverlay{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);z-index:10000;display:none;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(6px);animation:fadeIn 0.25s ease}
.modalOverlay.show{display:flex}
@keyframes fadeIn{from{opacity:0}to{opacity:1}}
.modalBox{background:#fff;border-radius:20px;max-width:750px;width:100%;max-height:85vh;overflow:hidden;box-shadow:0 25px 70px rgba(0,0,0,0.4);display:flex;flex-direction:column;animation:slideUp 0.35s cubic-bezier(0.4,0,0.2,1)}
@keyframes slideUp{from{transform:translateY(60px) scale(0.95);opacity:0}to{transform:translateY(0) scale(1);opacity:1}}
.modalHeader{padding:20px 24px;border-bottom:1px solid #e5e7eb;display:flex;justify-content:space-between;align-items:center;background:linear-gradient(135deg,#f9fafb,#fff)}
.modalTitle{font-weight:900;font-size:20px;color:#111b21;display:flex;align-items:center;gap:10px}
.modalClose{background:rgba(0,0,0,0.05);border:none;font-size:28px;cursor:pointer;color:#667781;line-height:1;padding:0;width:40px;height:40px;border-radius:50%;display:flex;align-items:center;justify-content:center;transition:all 0.25s}
.modalClose:hover{background:rgba(0,0,0,0.1);color:#111b21;transform:rotate(90deg) scale(1.1)}
.modalBody{padding:24px;overflow-y:auto;flex:1}
.categoriaGroup{margin-bottom:30px}
.categoriaTitle{font-weight:900;font-size:16px;color:#00a884;margin-bottom:14px;padding-bottom:10px;border-bottom:3px solid rgba(0,168,132,0.2);display:flex;align-items:center;gap:10px}
.preguntaItem{background:#f7f8fa;border:1px solid rgba(0,0,0,0.08);border-radius:14px;padding:16px 18px;margin-bottom:12px;cursor:pointer;transition:all 0.25s cubic-bezier(0.4,0,0.2,1)}
.preguntaItem:hover{background:#d9fdd3;border-color:#00a884;transform:translateX(8px);box-shadow:0 4px 12px rgba(0,168,132,0.15)}
.preguntaItemTitle{font-weight:800;font-size:14px;margin-bottom:7px;color:#111b21}
.preguntaItemTexto{font-size:13px;color:#667781;line-height:1.6}
.modalEmpty{text-align:center;color:#667781;padding:80px 20px;font-weight:700;font-size:16px;line-height:1.8}
</style>
</head>
<body>

<div id="loadingOverlay">
<div class="loadingEmoji">🔥</div>
<div class="spinner"></div>
<div class="loadingText">Cargando chats calientes...<br><span style="font-size:14px;font-weight:600;opacity:0.8;">Preparando interfaz profesional</span></div>
</div>

<div class="topbar">
<div>
  <div class="titleRow"><span class="titleEmoji">🔥</span><span class="title">Calientes</span></div>
  <div class="sub">
    No respondidos<?php echo $filtrarHoras ? ' ≥ '.(int)$MIN_HORAS.'h' : ''; ?> · Total: <strong><?php echo (int)$total; ?></strong> · Página <strong><?php echo (int)$pag; ?>/<?php echo (int)$totalPaginas; ?></strong>
  </div>
</div>
<div class="topLinks">
  <a href="preguntas.php" target="_blank">⚙️ Gestionar Preguntas</a>
  <?php if ($filtrarHoras): ?>
    <a href="caliente.php?p=<?php echo (int)$pag; ?>">Mostrar todos</a>
  <?php else: ?>
    <a href="caliente.php?p=<?php echo (int)$pag; ?>&minh=1">Solo ≥ <?php echo (int)$MIN_HORAS; ?>h</a>
  <?php endif; ?>
  <div class="pager">
    <?php if ($pag > 1): ?><a href="caliente.php?p=<?php echo (int)($pag - 1); ?><?php echo $qsMinh; ?>">‹ Anterior</a><?php endif; ?>
    <span><?php echo (int)$pag; ?> / <?php echo (int)$totalPaginas; ?></span>
    <?php if ($pag < $totalPaginas): ?><a href="caliente.php?p=<?php echo (int)($pag + 1); ?><?php echo $qsMinh; ?>">Siguiente ›</a><?php endif; ?>
  </div>
</div>
</div>

<div class="wrap">
<?php if (!$rows): ?>
<div class="empty">No hay chats que cumplan el filtro</div>
<?php else: ?>
<div class="grid">
<?php foreach ($rows as $r):
    $cid = (int)$r['id'];
    $name = $r['nombre'] ? $r['nombre'] : $r['telefono'];
    $tel = $r['telefono'];
    $dt = fmt_hace_si_hoy($r['ultima_fecha']); // CAMBIO: "hace X" si es hoy
    $totalMsgs = (int)$r['total_msgs'];
?>
<div class="card" id="card-<?php echo $cid; ?>" data-cid="<?php echo $cid; ?>">
  <div class="cardHead">
    <div class="who">
      <div class="name"><?php echo h($name); ?></div>
      <div class="phone"><?php echo h($tel); ?></div>
    </div>
    <div class="right">
      <div class="dt"><?php echo h($dt); ?></div>
      <div class="badges">
        <span class="badge badge-green" id="badge-<?php echo $cid; ?>">NO RESPONDIDO</span>
        <?php if ($totalMsgs === 1): ?><span class="badge badge-purple">1 MENSAJE</span><?php endif; ?>
        <span class="badge"><?php echo $totalMsgs; ?> MSG</span>
      </div>
    </div>
  </div>

  <div class="body">
    <div class="iframeBox">
      <iframe src="caliente.php?iframe=1&contacto_id=<?php echo $cid; ?>" loading="lazy" class="chat-iframe"></iframe>
    </div>

    <textarea id="ta-<?php echo $cid; ?>" placeholder="Escribir respuesta... (Enter para enviar, Shift+Enter para nueva línea)" data-cid="<?php echo $cid; ?>"></textarea>

    <div class="btnRow">
      <button class="btn btnPreguntas" onclick="abrirPreguntas(<?php echo $cid; ?>)">📝 Pregrabados</button>
      <button class="btn btnAI" id="btnai-<?php echo $cid; ?>" onclick="generarRespuestaIA(<?php echo $cid; ?>)">Responder IA</button>
      <button class="btn" onclick="window.open('whatsapp.php?contacto_id=<?php echo $cid; ?>','_blank')">💬 Abrir</button>
      <button class="btn btnAudio" onclick="enviarAudio(<?php echo $cid; ?>)">🎵 Audio</button>

      <!-- Botón nuevo: No quitar de caliente -->
      <button class="btn btnKeep" id="btnkeep-<?php echo $cid; ?>" onclick="toggleNoQuitar(<?php echo $cid; ?>)">No quitar de caliente</button>

      <button class="btn btnSend" id="btn-<?php echo $cid; ?>" onclick="enviarRespuesta(<?php echo $cid; ?>)">✓ Enviar</button>
    </div>
  </div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>

<div class="modalOverlay" id="modalPreguntas" onclick="if(event.target===this) cerrarPreguntas()">
  <div class="modalBox">
    <div class="modalHeader">
      <div class="modalTitle"><span>📝</span><span>Preguntas Pregrabadas</span></div>
      <button class="modalClose" onclick="cerrarPreguntas()">&times;</button>
    </div>
    <div class="modalBody" id="modalPreguntasBody">
      <div class="modalEmpty">Cargando preguntas...</div>
    </div>
  </div>
</div>

<div class="toast" id="toast">
  <div class="toastT" id="toastT">Info</div>
  <div class="toastS" id="toastS"></div>
</div>

<script>
var currentCidForPreguntas=null, preguntasData=[], iframesLoaded=0;
var totalIframes=<?php echo count($rows); ?>;

function checkAllIframesLoaded(){
  iframesLoaded++;
  if(iframesLoaded>=totalIframes){
    setTimeout(function(){
      var o=document.getElementById('loadingOverlay');
      if(o){
        o.style.opacity='0';
        o.style.transition='opacity 0.6s ease';
        setTimeout(function(){o.style.display='none';},600);
      }
    },400);
  }
}

document.addEventListener('DOMContentLoaded',function(){
  // restaurar estado "no quitar"
  var cards=document.querySelectorAll('.card[data-cid]');
  for(var i=0;i<cards.length;i++){
    var cid=cards[i].getAttribute('data-cid');
    if(isNoQuitar(cid)){
      var b=document.getElementById('btnkeep-'+cid);
      if(b){ b.classList.add('active'); }
      cards[i].setAttribute('data-keep','1');
    }
  }

  var ixs=document.querySelectorAll('.chat-iframe');
  if(ixs.length===0){
    var o=document.getElementById('loadingOverlay');
    if(o){
      setTimeout(function(){
        o.style.opacity='0';
        o.style.transition='opacity 0.6s ease';
        setTimeout(function(){o.style.display='none';},600);
      },600);
    }
  }else{
    for(var j=0;j<ixs.length;j++){ ixs[j].addEventListener('load',checkAllIframesLoaded); }
    setTimeout(function(){
      if(iframesLoaded<totalIframes){
        var o2=document.getElementById('loadingOverlay');
        if(o2){
          o2.style.opacity='0';
          o2.style.transition='opacity 0.6s ease';
          setTimeout(function(){o2.style.display='none';},600);
        }
      }
    },8000);
  }
});

function toast(t,s){
  var b=document.getElementById('toast');
  document.getElementById('toastT').textContent=t||'Info';
  document.getElementById('toastS').textContent=s||'';
  b.style.display='block';
  clearTimeout(window.__tto);
  window.__tto=setTimeout(function(){
    b.style.opacity='0';
    b.style.transition='opacity 0.4s ease';
    setTimeout(function(){b.style.display='none';b.style.opacity='1';},400);
  },3200);
}

/* =========================
   NO QUITAR (localStorage)
========================= */
function keyNoQuitar(cid){ return 'cal_noquitar_'+String(cid); }
function isNoQuitar(cid){
  try{ return localStorage.getItem(keyNoQuitar(cid)) === '1'; }catch(e){ return false; }
}
function setNoQuitar(cid, v){
  try{ localStorage.setItem(keyNoQuitar(cid), v ? '1':'0'); }catch(e){}
}
function toggleNoQuitar(cid){
  var c=String(cid);
  var on = !isNoQuitar(c);
  setNoQuitar(c, on);

  var btn=document.getElementById('btnkeep-'+c);
  var card=document.getElementById('card-'+c);
  if(btn){
    if(on) btn.classList.add('active'); else btn.classList.remove('active');
  }
  if(card){
    if(on) card.setAttribute('data-keep','1'); else card.removeAttribute('data-keep');
  }
  toast('Estado', on ? 'Se mantiene en calientes' : 'Se quita al enviar');
}

function marcarRespondidoSiSeMantiene(cid){
  var badge=document.getElementById('badge-'+cid);
  if(badge){
    badge.textContent='RESPONDIDO';
    badge.classList.remove('badge-green');
    badge.classList.add('badge-gray');
  }
}

/* =========================
   ENVIAR TEXTO
========================= */
async function enviarRespuesta(cid){
  var ta=document.getElementById('ta-'+cid), btn=document.getElementById('btn-'+cid);
  if(!ta||!btn)return;
  var msg=(ta.value||'').trim();
  if(!msg){toast('Atención','Escribí un mensaje primero');ta.focus();return;}
  if(btn.dataset.locked==='1')return;

  btn.dataset.locked='1';btn.disabled=true;btn.innerHTML='Enviando...';

  var fd=new FormData();
  fd.append('ajax_send','1');
  fd.append('contacto_id',String(cid));
  fd.append('mensaje',msg);

  try{
    var r=await fetch('caliente.php',{method:'POST',body:fd,cache:'no-store'});
    var txt=await r.text();
    var data=null;
    try{data=JSON.parse(txt);}catch(e){console.error('Respuesta no-JSON:',txt);throw new Error('Respuesta inválida');}

    if(!data||data.ok!==1){
      toast('Error',(data&&data.message)?data.message:'No se pudo enviar');
      btn.innerHTML='✓ Enviar';
    }else{
      ta.value='';
      if(isNoQuitar(cid)){
        toast('Enviado','Mensaje enviado (se mantiene en calientes)');
        marcarRespondidoSiSeMantiene(cid);
      }else{
        toast('Enviado','Mensaje enviado correctamente');
        var card=document.getElementById('card-'+cid);
        if(card){card.classList.add('success-fade');setTimeout(function(){card.remove();},750);}
      }
    }
  }catch(e){
    console.error(e);
    toast('Error de red','No se pudo conectar');
    btn.innerHTML='✓ Enviar';
  }finally{
    setTimeout(function(){ if(btn){btn.disabled=false;btn.dataset.locked='0';btn.innerHTML='✓ Enviar';}},900);
  }
}

/* =========================
   ENVIAR AUDIO
========================= */
async function enviarAudio(cid){
  var audioUrl=prompt('Ingresa la URL del archivo MP3:');
  if(!audioUrl)return;
  if(!audioUrl.match(/\.(mp3|m4a|ogg|wav)$/i)){
    if(!confirm('La URL no parece ser un archivo de audio. ¿Continuar igual?'))return;
  }
  var btn=document.getElementById('btn-'+cid);
  if(btn && btn.dataset.locked==='1')return;

  if(btn){btn.dataset.locked='1';btn.disabled=true;btn.innerHTML='Enviando audio...';}

  var fd=new FormData();
  fd.append('ajax_send_audio','1');
  fd.append('contacto_id',String(cid));
  fd.append('audio_url',audioUrl);

  try{
    var r=await fetch('caliente.php',{method:'POST',body:fd,cache:'no-store'});
    var txt=await r.text();
    var data=null;
    try{data=JSON.parse(txt);}catch(e){console.error('Respuesta no-JSON:',txt);throw new Error('Respuesta inválida');}

    if(!data||data.ok!==1){
      toast('Error',(data&&data.message)?data.message:'No se pudo enviar audio');
    }else{
      if(isNoQuitar(cid)){
        toast('Audio enviado','Se mantiene en calientes');
        marcarRespondidoSiSeMantiene(cid);
      }else{
        toast('Audio enviado','Audio enviado correctamente');
        var card=document.getElementById('card-'+cid);
        if(card){card.classList.add('success-fade');setTimeout(function(){card.remove();},750);}
      }
    }
  }catch(e){
    console.error(e);
    toast('Error de red','No se pudo conectar');
  }finally{
    if(btn){setTimeout(function(){btn.disabled=false;btn.dataset.locked='0';btn.innerHTML='✓ Enviar';},900);}
  }
}

/* =========================
   IA
========================= */
async function generarRespuestaIA(cid){
  var ta=document.getElementById('ta-'+cid);
  var btn=document.getElementById('btnai-'+cid);
  if(!ta||!btn)return;

  if(btn.dataset.locked==='1') return;
  btn.dataset.locked='1';
  btn.disabled=true;

  var old = btn.textContent;
  btn.textContent = 'Pensando...';

  var fd=new FormData();
  fd.append('ajax_ai','1');
  fd.append('contacto_id',String(cid));

  try{
    var r=await fetch('caliente.php',{method:'POST',body:fd,cache:'no-store'});
    var txt=await r.text();
    var data=null;
    try{data=JSON.parse(txt);}catch(e){console.error('Respuesta IA no-JSON:',txt);throw new Error('Respuesta IA inválida');}

    if(!data || data.ok!==1){
      toast('IA', (data && data.message) ? data.message : 'No se pudo generar respuesta');
      return;
    }

    var reply = (data.reply || '').trim();
    if(!reply){
      toast('IA','No devolvió respuesta');
      return;
    }

    ta.value = reply;
    ta.focus();

    var action = (data.data && data.data.action) ? data.data.action : 'DRAFT';
    if(action === 'HUMAN_TAKEOVER') toast('IA', 'Respuesta segura generada (revisar).');
    else toast('IA', 'Borrador generado.');
  }catch(e){
    console.error(e);
    toast('IA','Error generando respuesta');
  }finally{
    btn.disabled=false;
    btn.dataset.locked='0';
    btn.textContent = old;
  }
}

document.addEventListener('DOMContentLoaded',function(){
  var t=document.querySelectorAll('textarea[data-cid]');
  for(var i=0;i<t.length;i++){
    t[i].addEventListener('keydown',function(e){
      if(e.key==='Enter'&&!e.shiftKey){
        e.preventDefault();
        var cid=parseInt(this.dataset.cid,10);
        if(cid>0){enviarRespuesta(cid);}
      }
    });
  }
});

/* =========================
   PREGRABADOS
========================= */
async function cargarPreguntas(){
  if(preguntasData.length>0)return;
  try{
    var r=await fetch('caliente.php?ajax_preguntas=1',{cache:'no-store'});
    var data=await r.json();
    if(data.ok===1 && Array.isArray(data.preguntas)) preguntasData=data.preguntas;
  }catch(e){console.error('Error cargando preguntas:',e);}
}
function abrirPreguntas(cid){
  currentCidForPreguntas=cid;
  var m=document.getElementById('modalPreguntas'), b=document.getElementById('modalPreguntasBody');
  m.classList.add('show');
  b.innerHTML='<div class="modalEmpty">Cargando preguntas pregrabadas...</div>';
  cargarPreguntas().then(function(){renderPreguntas();});
}
function cerrarPreguntas(){
  var m=document.getElementById('modalPreguntas');
  m.classList.remove('show');
  currentCidForPreguntas=null;
}
function renderPreguntas(){
  var b=document.getElementById('modalPreguntasBody');
  if(preguntasData.length===0){
    b.innerHTML='<div class="modalEmpty">No hay preguntas activas</div>';
    return;
  }
  var grouped={};
  for(var i=0;i<preguntasData.length;i++){
    var p=preguntasData[i];
    if(!grouped[p.categoria]) grouped[p.categoria]=[];
    grouped[p.categoria].push(p);
  }
  var emojiCat={'STOCK':'📦','RADIOSNET':'📻','SITIOS':'🌐','JINGLES':'🎵','OTROS':'💡'};
  var html='';
  for(var cat in grouped){
    if(!grouped.hasOwnProperty(cat)) continue;
    var emoji=emojiCat[cat]||'📌';
    html+='<div class="categoriaGroup">';
    html+='<div class="categoriaTitle"><span>'+emoji+'</span> '+escapeHtml(cat)+'</div>';
    for(var j=0;j<grouped[cat].length;j++){
      var pp=grouped[cat][j];
      var texto=pp.texto.length>100 ? pp.texto.substring(0,100)+'...' : pp.texto;
      html+='<div class="preguntaItem" onclick="seleccionarPregunta('+pp.id+')"><div class="preguntaItemTitle">'+escapeHtml(pp.titulo)+'</div><div class="preguntaItemTexto">'+escapeHtml(texto)+'</div></div>';
    }
    html+='</div>';
  }
  b.innerHTML=html;
}
function seleccionarPregunta(preguntaId){
  var pregunta=null;
  for(var i=0;i<preguntasData.length;i++){ if(preguntasData[i].id===preguntaId){pregunta=preguntasData[i];break;} }
  if(!pregunta||!currentCidForPreguntas)return;
  enviarPreguntaPregrabada(currentCidForPreguntas,pregunta.texto);
  cerrarPreguntas();
}
async function enviarPreguntaPregrabada(cid,mensaje){
  var btn=document.getElementById('btn-'+cid);
  if(!btn)return;
  if(btn.dataset.locked==='1')return;

  btn.dataset.locked='1';btn.disabled=true;btn.innerHTML='Enviando...';

  var fd=new FormData();
  fd.append('ajax_send','1');
  fd.append('contacto_id',String(cid));
  fd.append('mensaje',mensaje);

  try{
    var r=await fetch('caliente.php',{method:'POST',body:fd,cache:'no-store'});
    var txt=await r.text();
    var data=null;
    try{data=JSON.parse(txt);}catch(e){console.error('Respuesta no-JSON:',txt);throw new Error('Respuesta inválida');}

    if(!data||data.ok!==1){
      toast('Error',(data&&data.message)?data.message:'No se pudo enviar');
      btn.innerHTML='✓ Enviar';
    }else{
      if(isNoQuitar(cid)){
        toast('Enviado','Mensaje pregrabado enviado (se mantiene)');
        marcarRespondidoSiSeMantiene(cid);
      }else{
        toast('Enviado','Mensaje pregrabado enviado correctamente');
        var card=document.getElementById('card-'+cid);
        if(card){card.classList.add('success-fade');setTimeout(function(){card.remove();},750);}
      }
    }
  }catch(e){
    console.error(e);
    toast('Error de red','No se pudo conectar');
    btn.innerHTML='✓ Enviar';
  }finally{
    setTimeout(function(){if(btn){btn.disabled=false;btn.dataset.locked='0';btn.innerHTML='✓ Enviar';}},900);
  }
}

function escapeHtml(text){var div=document.createElement('div');div.textContent=text;return div.innerHTML;}
document.addEventListener('keydown',function(e){if(e.key==='Escape'){cerrarPreguntas();}});
</script>
</body>
</html>
