-- Adds call type/direction support for WebRTC call history/details.
-- Safe to run multiple times in phpMyAdmin.
-- If a column already exists, this script will skip it instead of failing.

SET @has_call_request_direction := (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'call_requests'
    AND COLUMN_NAME = 'call_direction'
);

SET @sql := IF(
  @has_call_request_direction = 0,
  'ALTER TABLE call_requests ADD COLUMN call_direction ENUM(''inbound'',''outbound'') NOT NULL DEFAULT ''inbound'' AFTER call_reason',
  'SELECT ''call_requests.call_direction already exists'' AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE call_requests
SET call_direction = 'inbound'
WHERE call_direction IS NULL OR call_direction = '';

SET @has_call_log_direction := (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'call_logs'
    AND COLUMN_NAME = 'call_direction'
);

SET @sql := IF(
  @has_call_log_direction = 0,
  'ALTER TABLE call_logs ADD COLUMN call_direction ENUM(''inbound'',''outbound'') NOT NULL DEFAULT ''inbound'' AFTER customer_email',
  'SELECT ''call_logs.call_direction already exists'' AS info'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE call_logs
SET call_direction = 'inbound'
WHERE call_direction IS NULL OR call_direction = '';
