-- Fix Missing WordPress Sites Table Columns
-- Fixes: Column not found: 1054 Unknown column 'database_name' in 'INSERT INTO'

USE whp;

-- Add database_name column if missing
ALTER TABLE wordpress_sites 
ADD COLUMN IF NOT EXISTS database_name VARCHAR(64) DEFAULT NULL AFTER admin_username;

-- Add backup target columns if missing
ALTER TABLE wordpress_sites 
ADD COLUMN IF NOT EXISTS preferred_backup_target_id INT DEFAULT NULL AFTER auto_backup_before_update;

ALTER TABLE wordpress_sites 
ADD COLUMN IF NOT EXISTS backup_target_id INT DEFAULT NULL AFTER preferred_backup_target_id;

-- Add indexes if they don't exist
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);
CREATE INDEX IF NOT EXISTS idx_preferred_backup_target ON wordpress_sites(preferred_backup_target_id);

-- Add foreign key constraints if they don't exist
SET @fk_exists = (
    SELECT COUNT(*) 
    FROM information_schema.TABLE_CONSTRAINTS 
    WHERE CONSTRAINT_SCHEMA = 'whp' 
    AND TABLE_NAME = 'wordpress_sites' 
    AND CONSTRAINT_NAME = 'fk_wordpress_backup_target'
);

SET @sql = IF(@fk_exists = 0,
    'ALTER TABLE wordpress_sites ADD CONSTRAINT fk_wordpress_backup_target FOREIGN KEY (preferred_backup_target_id) REFERENCES backup_targets(id) ON DELETE SET NULL',
    'SELECT "fk_wordpress_backup_target already exists" as notice'
);

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

-- Add backup_target_id foreign key
SET @fk_exists2 = (
    SELECT COUNT(*) 
    FROM information_schema.TABLE_CONSTRAINTS 
    WHERE CONSTRAINT_SCHEMA = 'whp' 
    AND TABLE_NAME = 'wordpress_sites' 
    AND CONSTRAINT_NAME = 'fk_wp_backup_target'
);

SET @sql2 = IF(@fk_exists2 = 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 "fk_wp_backup_target already exists" as notice'
);

PREPARE stmt2 FROM @sql2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;