-- Add Missing WordPress Sites Table Columns
-- Date: 2025-07-21
-- Description: Add database_name and backup_target_id columns to wordpress_sites table

USE whp;

-- Add database_name column to track WordPress database
ALTER TABLE wordpress_sites 
ADD COLUMN IF NOT EXISTS database_name VARCHAR(64) DEFAULT NULL AFTER admin_username;

-- Add backup_target_id column for backup integration  
ALTER TABLE wordpress_sites 
ADD COLUMN IF NOT EXISTS backup_target_id INT DEFAULT NULL AFTER auto_backup_before_update;

-- Add foreign key constraint for backup_target_id if backup_targets table exists
SET @table_exists = (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'whp' AND table_name = 'backup_targets');

SET @sql = IF(@table_exists > 0, 
    'ALTER TABLE wordpress_sites ADD CONSTRAINT fk_wp_backup_target FOREIGN KEY (backup_target_id) REFERENCES backup_targets(id) ON DELETE SET NULL',
    'SELECT "backup_targets table does not exist, skipping foreign key constraint" as notice'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Add indexes for better performance
CREATE INDEX IF NOT EXISTS idx_database_name ON wordpress_sites(database_name);
CREATE INDEX IF NOT EXISTS idx_backup_target ON wordpress_sites(backup_target_id);

-- Verify the structure
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'whp' 
  AND TABLE_NAME = 'wordpress_sites'
  AND COLUMN_NAME IN ('database_name', 'backup_target_id')
ORDER BY ORDINAL_POSITION;