-- INTERLINK WhatsApp v2.7 - Comprobantes profesionales
-- Migración segura: agrega columnas solo si faltan (MariaDB 10.11+ soporta IF NOT EXISTS).

CREATE TABLE IF NOT EXISTS wa2_payment_receipts (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  phone VARCHAR(32) NOT NULL,
  customer_id BIGINT UNSIGNED DEFAULT NULL,
  customer_name VARCHAR(190) DEFAULT NULL,
  message_id VARCHAR(190) DEFAULT NULL,
  media_id VARCHAR(190) DEFAULT NULL,
  media_type VARCHAR(40) DEFAULT NULL,
  mime_type VARCHAR(120) DEFAULT NULL,
  status VARCHAR(40) NOT NULL DEFAULT 'pending_review',
  note TEXT DEFAULT NULL,
  analysis_json LONGTEXT DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT NULL,
  PRIMARY KEY (id),
  KEY idx_phone (phone),
  KEY idx_customer (customer_id),
  KEY idx_status (status),
  KEY idx_message_id (message_id),
  KEY idx_media_id (media_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE wa2_payment_receipts
  ADD COLUMN IF NOT EXISTS local_path VARCHAR(255) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS original_filename VARCHAR(190) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS file_size BIGINT UNSIGNED DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS detected_amount DECIMAL(15,2) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS detected_date DATE DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS detected_reference VARCHAR(190) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS detected_origin_name VARCHAR(190) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS detected_destination_name VARCHAR(190) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS admin_note TEXT DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS reviewed_by BIGINT UNSIGNED DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS reviewed_at DATETIME DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS approved_at DATETIME DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS rejected_at DATETIME DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS payment_id BIGINT UNSIGNED DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS imputed_at DATETIME DEFAULT NULL;

CREATE TABLE IF NOT EXISTS wa2_receipt_audit (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  receipt_id BIGINT UNSIGNED NOT NULL,
  action VARCHAR(80) NOT NULL,
  details_json LONGTEXT DEFAULT NULL,
  created_by BIGINT UNSIGNED DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_receipt (receipt_id),
  KEY idx_action (action)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
