-- ============================================================
-- Club Palestino CRM v2.0 — MÓDULO COMUNICACIONES WHATSAPP
-- Fase 9 — WATI API Oficial Meta + Email + Push
-- ============================================================

-- ── 1. CONFIGURACIÓN WATI POR EMPRESA ────────────────────────
CREATE TABLE IF NOT EXISTS `wati_config` (
    `id`          TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `empresa_id`  TINYINT UNSIGNED NOT NULL,
    `nombre`      VARCHAR(80)      NOT NULL,
    `api_endpoint` VARCHAR(200)    NOT NULL COMMENT 'Ej: https://live-server.wati.io',
    `api_token`   VARCHAR(500)     NOT NULL COMMENT 'Bearer token WATI (cifrado)',
    `numero_wa`   VARCHAR(20)      NOT NULL COMMENT 'Número WhatsApp Business',
    `activo`      TINYINT(1)       NOT NULL DEFAULT 1,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_empresa` (`empresa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `wati_config` (`empresa_id`,`nombre`,`api_endpoint`,`api_token`,`numero_wa`) VALUES
(1,'Club Palestino Principal','https://live-server.wati.io','TOKEN_AQUI','+56XXXXXXXXX')
ON DUPLICATE KEY UPDATE nombre=VALUES(nombre);

-- ── 2. TEMPLATES APROBADOS META ───────────────────────────────
CREATE TABLE IF NOT EXISTS `wa_templates` (
    `id`          INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    `empresa_id`  TINYINT UNSIGNED NOT NULL DEFAULT 1,
    `nombre`      VARCHAR(80)      NOT NULL COMMENT 'Nombre exacto en WATI/Meta',
    `categoria`   ENUM('MARKETING','UTILITY','AUTHENTICATION') NOT NULL DEFAULT 'UTILITY',
    `idioma`      VARCHAR(10)      NOT NULL DEFAULT 'es',
    `descripcion` VARCHAR(200)     NULL,
    `cuerpo`      TEXT             NOT NULL COMMENT 'Texto del template con {{variables}}',
    `variables`   JSON             NULL COMMENT 'Lista de variables requeridas',
    `uso`         VARCHAR(100)     NULL COMMENT 'Cuándo se usa: reserva_confirmada, etc.',
    `activo`      TINYINT(1)       NOT NULL DEFAULT 1,
    `created_at`  TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_empresa_nombre` (`empresa_id`,`nombre`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Templates base (registrar y aprobar en Meta Business Manager)
INSERT INTO `wa_templates` (`empresa_id`,`nombre`,`categoria`,`descripcion`,`cuerpo`,`variables`,`uso`) VALUES
(1,'bienvenida_socio','UTILITY','Bienvenida a nuevo socio',
 'Hola {{1}}, ¡bienvenido/a al Club Palestino! 🎉\nTu membresía ha sido activada.\nAccede al portal: sociosclubpalestino.cl\n¿Tienes dudas? Escríbenos aquí.',
 '["nombre_socio"]','nuevo_socio'),

(1,'membresia_por_vencer','UTILITY','Aviso vencimiento membresía',
 'Hola {{1}}, tu membresía en Club Palestino vence el *{{2}}*.\nRenueva fácilmente en: sociosclubpalestino.cl\nPara más info escríbenos o llama al +56 2 XXXX XXXX.',
 '["nombre","fecha_vencimiento"]','membresia_vencer'),

(1,'reserva_cancha_confirmada','UTILITY','Confirmación reserva cancha',
 '✅ *Reserva confirmada — Club Palestino*\nHola {{1}}\n🎾 Cancha: {{2}}\n📅 Fecha: {{3}}\n⏰ Hora: {{4}}\nRecuerda traer raqueta y llegar 5 min antes.',
 '["nombre","cancha","fecha","hora"]','reserva_confirmada'),

(1,'reserva_recordatorio','UTILITY','Recordatorio reserva 2h antes',
 '⏰ *Recordatorio — Club Palestino*\nHola {{1}}, tienes una reserva en *{{2}}* hoy a las *{{3}}*.\n¿No puedes asistir? Anula con anticipación en la app.',
 '["nombre","instalacion","hora"]','reserva_recordatorio'),

(1,'estacionamiento_cupo_libre','UTILITY','Cupo estacionamiento liberado',
 '🟢 *Club Palestino — Estacionamiento*\nHola {{1}}, se liberó un cupo en el estacionamiento interior.\nTu vehículo {{2}} ya puede ingresar.',
 '["nombre","patente"]','estac_cupo_libre'),

(1,'estacionamiento_sin_cupo','UTILITY','Estacionamiento interior lleno',
 '🔴 *Club Palestino — Estacionamiento*\nHola {{1}}, el estacionamiento interior está lleno ({{2}}/{{3}} cupos).\nTe avisaremos cuando se libere un cupo. Puedes usar el estacionamiento exterior.',
 '["nombre","cupos_usados","cupos_pagados"]','estac_sin_cupo'),

(1,'acceso_denegado','UTILITY','Acceso denegado al club',
 '⛔ *Club Palestino — Aviso de acceso*\nHola {{1}}, tu ingreso fue denegado.\nMotivo: {{2}}\nContacta administración: socios@clubpalestino.cl',
 '["nombre","motivo"]','acceso_denegado'),

(1,'pago_registrado','UTILITY','Confirmación de pago',
 '✅ *Pago registrado — Club Palestino*\nHola {{1}}\nMonto: {{2}}\nConcepto: {{3}}\nFecha: {{4}}\nGracias por tu pago.',
 '["nombre","monto","concepto","fecha"]','pago_registrado'),

(1,'evento_inscripcion','UTILITY','Confirmación inscripción evento',
 '🎉 *Club Palestino — Inscripción confirmada*\nHola {{1}}, quedaste inscrito/a en:\n📌 *{{2}}*\n📅 {{3}}\n📍 {{4}}\n¡Te esperamos!',
 '["nombre","evento","fecha","lugar"]','evento_inscripcion'),

(1,'boleta_emitida','UTILITY','Boleta electrónica emitida',
 '🧾 *Club Palestino — Documento tributario*\nHola {{1}}\n{{2}} N° {{3}}\nMonto: {{4}}\nFecha: {{5}}\nDescarga: {{6}}',
 '["nombre","tipo_doc","folio","monto","fecha","url_pdf"]','dte_emitido'),

(1,'comunicado_general','MARKETING','Comunicado general del club',
 '📢 *Club Palestino — Comunicado*\n\n{{1}}\n\nMás información: sociosclubpalestino.cl',
 '["mensaje"]','comunicado'),

(1,'evento_promo','MARKETING','Promoción de evento',
 '🎊 *{{1}}*\n\n{{2}}\n\n📅 Fecha: {{3}}\n📍 Lugar: {{4}}\n\nInscríbete: sociosclubpalestino.cl',
 '["titulo_evento","descripcion","fecha","lugar"]','evento_marketing'),

(1,'previred_recordatorio','UTILITY','Recordatorio pago Previred',
 '📤 *Recordatorio Previred — {{1}}*\nPeriodo: {{2}}\nTotal a pagar: {{3}}\nFecha límite: {{4}}\nSubir en: previred.com',
 '["empresa","periodo","total","fecha_limite"]','previred_recordatorio');

-- ── 3. CAMPAÑAS DE DIFUSIÓN ───────────────────────────────────
CREATE TABLE IF NOT EXISTS `wa_campanas` (
    `id`          INT UNSIGNED     NOT NULL AUTO_INCREMENT,
    `empresa_id`  TINYINT UNSIGNED NOT NULL DEFAULT 1,
    `nombre`      VARCHAR(150)     NOT NULL,
    `template_id` INT UNSIGNED     NOT NULL,
    `tipo`        ENUM('masiva','segmentada','individual') NOT NULL DEFAULT 'masiva',
    -- Segmentación
    `segmento`    JSON             NULL COMMENT 'Filtros: tipo_socio, rama, edad, etc.',
    `total_dest`  INT UNSIGNED     NOT NULL DEFAULT 0,
    -- Programación
    `programada_at' DATETIME       NULL COMMENT 'NULL = envío inmediato',
    -- Variables de la campaña
    `variables_globales' JSON      NULL COMMENT 'Variables fijas para toda la campaña',
    -- Estado
    `estado`      ENUM('borrador','programada','enviando','enviada','cancelada') NOT NULL DEFAULT 'borrador',
    `enviados'    INT UNSIGNED     NOT NULL DEFAULT 0,
    `entregados`  INT UNSIGNED     NOT NULL DEFAULT 0,
    `leidos`      INT UNSIGNED     NOT NULL DEFAULT 0,
    `errores`     INT UNSIGNED     NOT NULL DEFAULT 0,
    `created_by`  INT UNSIGNED     NULL,
    `created_at`  TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `sent_at`     TIMESTAMP        NULL,
    PRIMARY KEY (`id`),
    KEY `idx_empresa_campana` (`empresa_id`,`estado`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ── 4. MENSAJES INDIVIDUALES ──────────────────────────────────
CREATE TABLE IF NOT EXISTS `wa_mensajes` (
    `id`          BIGINT UNSIGNED  NOT NULL AUTO_INCREMENT,
    `empresa_id`  TINYINT UNSIGNED NOT NULL DEFAULT 1,
    `campana_id`  INT UNSIGNED     NULL,
    `socio_id`    INT UNSIGNED     NULL,
    `telefono`    VARCHAR(20)      NOT NULL,
    `nombre`      VARCHAR(150)     NULL,
    `template_id` INT UNSIGNED     NULL,
    `tipo`        ENUM('template','session','manual') NOT NULL DEFAULT 'template',
    `direccion`   ENUM('saliente','entrante') NOT NULL DEFAULT 'saliente',
    `contenido`   TEXT             NOT NULL,
    `variables`   JSON             NULL,
    -- Estado de entrega
    `wati_msg_id` VARCHAR(100)     NULL COMMENT 'ID del mensaje en WATI',
    `estado`      ENUM('pendiente','enviado','entregado','leido','fallido','respondido') NOT NULL DEFAULT 'pendiente',
    `error_msg`   VARCHAR(300)     NULL,
    `intentos`    TINYINT          NOT NULL DEFAULT 0,
    `enviado_at`  TIMESTAMP        NULL,
    `entregado_at' TIMESTAMP       NULL,
    `leido_at`    TIMESTAMP        NULL,
    `created_at`  TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_socio_msg`    (`socio_id`,`created_at`),
    KEY `idx_campana_msg`  (`campana_id`),
    KEY `idx_pendientes`   (`estado`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ── 5. CONVERSACIONES (respuestas de socios) ──────────────────
CREATE TABLE IF NOT EXISTS `wa_conversaciones` (
    `id`          INT UNSIGNED  NOT NULL AUTO_INCREMENT,
    `socio_id`    INT UNSIGNED  NULL,
    `telefono`    VARCHAR(20)   NOT NULL,
    `mensaje`     TEXT          NOT NULL,
    `tipo`        ENUM('entrante','saliente') NOT NULL,
    `leido`       TINYINT(1)    NOT NULL DEFAULT 0,
    `asignado_a`  INT UNSIGNED  NULL COMMENT 'Usuario admin responsable',
    `created_at`  TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_tel_conv` (`telefono`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ── 6. COLA DE NOTIFICACIONES (todas las fuentes) ─────────────
-- Tabla unificada para todos los tipos de notificación
CREATE TABLE IF NOT EXISTS `notificaciones_cola` (
    `id`          BIGINT UNSIGNED  NOT NULL AUTO_INCREMENT,
    `empresa_id`  TINYINT UNSIGNED NOT NULL DEFAULT 1,
    `socio_id`    INT UNSIGNED     NULL,
    `telefono`    VARCHAR(20)      NULL,
    `email`       VARCHAR(100)     NULL,
    `canal`       ENUM('whatsapp','email','push','sms') NOT NULL DEFAULT 'whatsapp',
    `template_id` INT UNSIGNED     NULL,
    `template_nombre` VARCHAR(80)  NULL,
    `variables`   JSON             NULL,
    `mensaje_fallback` TEXT        NULL COMMENT 'Mensaje si no hay template',
    `prioridad`   TINYINT          NOT NULL DEFAULT 5 COMMENT '1=urgente 10=baja',
    `estado`      ENUM('pendiente','procesando','enviado','fallido') NOT NULL DEFAULT 'pendiente',
    `intentos`    TINYINT          NOT NULL DEFAULT 0,
    `max_intentos' TINYINT         NOT NULL DEFAULT 3,
    `error_msg`   VARCHAR(300)     NULL,
    `programado_at' DATETIME       NULL COMMENT 'NULL = enviar ASAP',
    `enviado_at`  TIMESTAMP        NULL,
    `created_at`  TIMESTAMP        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_pendientes_prio` (`estado`,`prioridad`,`created_at`),
    KEY `idx_socio_notif`     (`socio_id`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ── 7. SUSCRIPCIONES / PREFERENCIAS DE COMUNICACIÓN ──────────
CREATE TABLE IF NOT EXISTS `comunicacion_preferencias` (
    `socio_id`    INT UNSIGNED NOT NULL,
    `wa_activo`   TINYINT(1)   NOT NULL DEFAULT 1,
    `email_activo' TINYINT(1)  NOT NULL DEFAULT 1,
    `push_activo` TINYINT(1)   NOT NULL DEFAULT 1,
    `marketing`   TINYINT(1)   NOT NULL DEFAULT 1 COMMENT 'Acepta comunicados y promociones',
    `transaccional' TINYINT(1) NOT NULL DEFAULT 1 COMMENT 'Reservas, pagos, accesos',
    `updated_at`  TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`socio_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

