-- Script SQL para tabla de plantillas WhatsApp
-- Ejecutar en phpMyAdmin después del crm_setup.sql

CREATE TABLE IF NOT EXISTS whatsapp_templates (
  id INT AUTO_INCREMENT PRIMARY KEY,
  template_id VARCHAR(50) NOT NULL UNIQUE,
  name VARCHAR(100) NOT NULL,
  status ENUM('PENDING','APPROVED','REJECTED','PAUSED','DISABLED') NOT NULL,
  category ENUM('MARKETING','UTILITY','AUTHENTICATION','TRANSACTIONAL') NOT NULL,
  language VARCHAR(10) DEFAULT 'es',
  body_text TEXT NOT NULL,
  variables JSON COMMENT 'Array de variables mapeadas: {"1":"nombre","2":"pedido"}',
  variable_count INT DEFAULT 0 COMMENT 'Número total de variables en la plantilla',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  synced_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_status (status),
  INDEX idx_category (category),
  INDEX idx_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Tabla para mapeo personalizado de variables por plantilla
CREATE TABLE IF NOT EXISTS template_variable_mapping (
  id INT AUTO_INCREMENT PRIMARY KEY,
  template_id VARCHAR(50) NOT NULL,
  variable_position INT NOT NULL COMMENT 'Posición en Meta (1,2,3...)',
  variable_name VARCHAR(50) NOT NULL COMMENT 'Nombre descriptivo (nombre, pedido, etc)',
  variable_type ENUM('text','number','date','phone') DEFAULT 'text',
  is_required TINYINT(1) DEFAULT 1,
  example_value VARCHAR(100) DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY unique_mapping (template_id, variable_position),
  FOREIGN KEY (template_id) REFERENCES whatsapp_templates(template_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Insertar algunas plantillas de ejemplo (para testing)
INSERT IGNORE INTO whatsapp_templates (template_id, name, status, category, body_text, variable_count) VALUES 
('mensaje_prueba', 'mensaje_prueba', 'APPROVED', 'UTILITY', 'Hola {{1}}, este es un mensaje de prueba.', 1),
('pedido_confirmacion', 'pedido_confirmacion', 'APPROVED', 'TRANSACTIONAL', 'Hola {{1}}, tu pedido {{2}} ha sido confirmado. Total: ${{3}}', 3),
('mensaje_simple', 'mensaje_simple', 'APPROVED', 'UTILITY', 'Este es un mensaje simple sin variables.', 0);

-- Mapeos de ejemplo
INSERT IGNORE INTO template_variable_mapping (template_id, variable_position, variable_name, variable_type, example_value) VALUES
('mensaje_prueba', 1, 'nombre', 'text', 'Juan Pérez'),
('pedido_confirmacion', 1, 'cliente_nombre', 'text', 'María González'),
('pedido_confirmacion', 2, 'numero_pedido', 'text', '#12345'),
('pedido_confirmacion', 3, 'monto_total', 'number', '25.99');