-- Fix All Missing Tables and Columns
-- Comprehensive migration to ensure existing installations have all required schema
-- Fixes issues found between migrations and complete-database-setup.sql

USE whp;

-- ================================================
-- WordPress Sites Table Fixes
-- ================================================

-- Add missing WordPress columns if they don't exist
ALTER TABLE wordpress_sites 
ADD COLUMN IF NOT EXISTS database_name VARCHAR(64) DEFAULT NULL AFTER admin_username;

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 missing indexes
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;

-- ================================================
-- Client Allowances Table Fixes
-- ================================================

-- Add API columns to client_allowances if missing
ALTER TABLE client_allowances 
ADD COLUMN IF NOT EXISTS api_enabled BOOLEAN DEFAULT FALSE AFTER max_email_accounts;

ALTER TABLE client_allowances 
ADD COLUMN IF NOT EXISTS api_rate_limit INT DEFAULT 100 AFTER api_enabled;

-- ================================================
-- Email Forwarders Table Fixes
-- ================================================

-- Add destination_type column if missing
ALTER TABLE email_forwarders 
ADD COLUMN IF NOT EXISTS destination_type ENUM('email', 'domain') DEFAULT 'email' AFTER destination_email;

-- ================================================
-- WordPress Security Settings Enhancements
-- ================================================

-- Add enhanced security columns if missing
ALTER TABLE wp_security_settings 
ADD COLUMN IF NOT EXISTS security_headers_enabled BOOLEAN DEFAULT TRUE AFTER limit_login_attempts;

ALTER TABLE wp_security_settings 
ADD COLUMN IF NOT EXISTS block_php_uploads BOOLEAN DEFAULT TRUE AFTER security_headers_enabled;

ALTER TABLE wp_security_settings 
ADD COLUMN IF NOT EXISTS force_strong_passwords BOOLEAN DEFAULT FALSE AFTER block_php_uploads;

-- ================================================
-- API System Tables (ensure they exist)
-- ================================================

-- Create api_keys table if missing
CREATE TABLE IF NOT EXISTS api_keys (
    id INT PRIMARY KEY AUTO_INCREMENT,
    key_name VARCHAR(255) NOT NULL,
    api_key VARCHAR(64) UNIQUE NOT NULL,
    api_secret VARCHAR(255) NOT NULL,
    created_by VARCHAR(50) NOT NULL,
    permissions JSON DEFAULT NULL,
    rate_limit_per_hour INT DEFAULT 100,
    ip_whitelist TEXT DEFAULT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    last_used_at TIMESTAMP NULL,
    usage_count INT DEFAULT 0,
    notes TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_api_key (api_key),
    INDEX idx_created_by (created_by),
    INDEX idx_is_active (is_active),
    INDEX idx_last_used (last_used_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create api_usage_logs table if missing
CREATE TABLE IF NOT EXISTS api_usage_logs (
    id INT PRIMARY KEY AUTO_INCREMENT,
    api_key_id INT NOT NULL,
    endpoint VARCHAR(255) NOT NULL,
    method VARCHAR(10) NOT NULL,
    request_ip VARCHAR(45) NOT NULL,
    response_code INT NOT NULL,
    response_time_ms INT DEFAULT NULL,
    request_size_bytes INT DEFAULT NULL,
    response_size_bytes INT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (api_key_id) REFERENCES api_keys(id) ON DELETE CASCADE,
    INDEX idx_api_key_id (api_key_id),
    INDEX idx_endpoint (endpoint),
    INDEX idx_created_at (created_at),
    INDEX idx_ip_address (request_ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create api_tokens table if missing
CREATE TABLE IF NOT EXISTS api_tokens (
    id INT AUTO_INCREMENT PRIMARY KEY,
    token VARCHAR(128) NOT NULL UNIQUE,
    username VARCHAR(50) NOT NULL,
    expires_at DATETIME NOT NULL,
    ip_address VARCHAR(45) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_token (token),
    INDEX idx_username (username),
    INDEX idx_expires (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ================================================
-- Terminal System Tables (ensure they exist)
-- ================================================

-- Create terminal_access_log table if missing
CREATE TABLE IF NOT EXISTS terminal_access_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL,
    container_id VARCHAR(255) NOT NULL,
    container_user VARCHAR(255) NOT NULL,
    shell VARCHAR(50) NOT NULL DEFAULT 'bash',
    connected_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    disconnected_at TIMESTAMP NULL,
    commands_executed INT DEFAULT 0,
    INDEX idx_username (username),
    INDEX idx_container_id (container_id),
    INDEX idx_connected_at (connected_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create terminal_preferences table if missing
CREATE TABLE IF NOT EXISTS terminal_preferences (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL UNIQUE,
    default_shell VARCHAR(50) DEFAULT 'bash',
    default_user VARCHAR(255) DEFAULT NULL,
    font_size INT DEFAULT 14,
    theme VARCHAR(50) DEFAULT 'dark',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_username (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ================================================
-- cpanel Import Tables (ensure they exist)
-- ================================================

-- Create cpanel_imports table if missing
CREATE TABLE IF NOT EXISTS cpanel_imports (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL,
    import_file VARCHAR(500) NOT NULL,
    total_size BIGINT DEFAULT 0,
    status ENUM('pending', 'extracting', 'analyzing', 'importing', 'completed', 'failed') DEFAULT 'pending',
    progress_percent INT DEFAULT 0,
    domains_found INT DEFAULT 0,
    databases_found INT DEFAULT 0,
    files_found INT DEFAULT 0,
    current_step VARCHAR(255) DEFAULT NULL,
    error_message TEXT DEFAULT NULL,
    started_at TIMESTAMP NULL,
    completed_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_username (username),
    INDEX idx_status (status),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create cpanel_imported_domains table if missing
CREATE TABLE IF NOT EXISTS cpanel_imported_domains (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id INT NOT NULL,
    domain_name VARCHAR(255) NOT NULL,
    domain_type ENUM('main', 'addon', 'subdomain', 'parked') NOT NULL,
    document_root VARCHAR(500) DEFAULT NULL,
    import_status ENUM('pending', 'importing', 'completed', 'failed', 'skipped') DEFAULT 'pending',
    error_message TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(id) ON DELETE CASCADE,
    INDEX idx_import_id (import_id),
    INDEX idx_domain_name (domain_name),
    INDEX idx_domain_type (domain_type),
    INDEX idx_import_status (import_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create cpanel_imported_databases table if missing
CREATE TABLE IF NOT EXISTS cpanel_imported_databases (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id INT NOT NULL,
    database_name VARCHAR(255) NOT NULL,
    database_size BIGINT DEFAULT 0,
    import_status ENUM('pending', 'importing', 'completed', 'failed', 'skipped') DEFAULT 'pending',
    error_message TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(id) ON DELETE CASCADE,
    INDEX idx_import_id (import_id),
    INDEX idx_database_name (database_name),
    INDEX idx_import_status (import_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create cpanel_imported_files table if missing
CREATE TABLE IF NOT EXISTS cpanel_imported_files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id INT NOT NULL,
    file_path VARCHAR(1000) NOT NULL,
    file_size BIGINT DEFAULT 0,
    file_type ENUM('file', 'directory') NOT NULL,
    import_status ENUM('pending', 'importing', 'completed', 'failed', 'skipped') DEFAULT 'pending',
    error_message TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(id) ON DELETE CASCADE,
    INDEX idx_import_id (import_id),
    INDEX idx_file_path (file_path(255)),
    INDEX idx_import_status (import_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create cpanel_imported_mysql_users table if missing
CREATE TABLE IF NOT EXISTS cpanel_imported_mysql_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id INT NOT NULL,
    username VARCHAR(255) NOT NULL,
    associated_databases TEXT DEFAULT NULL,
    import_status ENUM('pending', 'importing', 'completed', 'failed', 'skipped') DEFAULT 'pending',
    error_message TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(id) ON DELETE CASCADE,
    INDEX idx_import_id (import_id),
    INDEX idx_username (username),
    INDEX idx_import_status (import_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ================================================
-- Add missing indexes for performance
-- ================================================

-- Add missing indexes to cpanel import tables
CREATE INDEX IF NOT EXISTS idx_username_status ON cpanel_imports(username, status);
CREATE INDEX IF NOT EXISTS idx_domain_type ON cpanel_imported_domains(domain_type);
CREATE INDEX IF NOT EXISTS idx_import_status ON cpanel_imported_databases(import_status);

-- ================================================
-- Verification
-- ================================================

-- Verify all critical tables exist
SELECT 
    'wordpress_sites' as table_name,
    COUNT(*) as column_count
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = 'whp' AND TABLE_NAME = 'wordpress_sites'
    AND COLUMN_NAME IN ('database_name', 'preferred_backup_target_id', 'backup_target_id')

UNION ALL

SELECT 
    'client_allowances' as table_name,
    COUNT(*) as column_count
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = 'whp' AND TABLE_NAME = 'client_allowances'
    AND COLUMN_NAME IN ('api_enabled', 'api_rate_limit')

UNION ALL

SELECT 
    'api_tokens' as table_name,
    COUNT(*) as table_exists
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'whp' AND TABLE_NAME = 'api_tokens'

UNION ALL

SELECT 
    'terminal_access_log' as table_name,
    COUNT(*) as table_exists
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'whp' AND TABLE_NAME = 'terminal_access_log';