USE whp;

-- Hotfix for cPanel import system - create tables without system_logs dependency
-- This addresses the issue where the original migration failed due to missing system_logs table

-- Create table for tracking cPanel imports
CREATE TABLE IF NOT EXISTS cpanel_imports (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id VARCHAR(64) NOT NULL UNIQUE,
    username VARCHAR(32) NOT NULL,
    backup_file VARCHAR(512) NOT NULL,
    status ENUM('pending', 'running', 'completed', 'failed') NOT NULL DEFAULT 'pending',
    progress INT DEFAULT 0,
    error_message TEXT NULL,
    log LONGTEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMP NULL,
    INDEX idx_username (username),
    INDEX idx_status (status),
    INDEX idx_created (created_at)
);

-- Create table for tracking imported domains from cPanel backups
CREATE TABLE IF NOT EXISTS cpanel_imported_domains (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id VARCHAR(64) NOT NULL,
    domain VARCHAR(255) NOT NULL,
    domain_type ENUM('primary', 'addon', 'subdomain', 'parked') NOT NULL,
    original_path VARCHAR(512) NULL,
    whp_site_id INT NULL,
    ssl_imported BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_import_id (import_id),
    INDEX idx_domain (domain),
    INDEX idx_whp_site_id (whp_site_id),
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(import_id) ON DELETE CASCADE
);

-- Create table for tracking imported databases from cPanel backups
CREATE TABLE IF NOT EXISTS cpanel_imported_databases (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id VARCHAR(64) NOT NULL,
    original_db_name VARCHAR(255) NOT NULL,
    whp_db_name VARCHAR(255) NOT NULL,
    whp_db_user VARCHAR(255) NOT NULL,
    whp_db_password VARCHAR(255) NOT NULL,
    size_bytes BIGINT DEFAULT 0,
    import_status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
    error_message TEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_import_id (import_id),
    INDEX idx_original_name (original_db_name),
    INDEX idx_whp_db_name (whp_db_name),
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(import_id) ON DELETE CASCADE
);

-- Create table for tracking imported MySQL users from cPanel backups
CREATE TABLE IF NOT EXISTS cpanel_imported_mysql_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id VARCHAR(64) NOT NULL,
    original_username VARCHAR(255) NOT NULL,
    whp_username VARCHAR(255) NOT NULL,
    whp_password VARCHAR(255) NOT NULL,
    host VARCHAR(255) DEFAULT 'localhost',
    privileges TEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_import_id (import_id),
    INDEX idx_original_username (original_username),
    INDEX idx_whp_username (whp_username),
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(import_id) ON DELETE CASCADE
);

-- Create table for tracking file imports from cPanel backups
CREATE TABLE IF NOT EXISTS cpanel_imported_files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    import_id VARCHAR(64) NOT NULL,
    domain VARCHAR(255) NOT NULL,
    source_path VARCHAR(512) NOT NULL,
    destination_path VARCHAR(512) NOT NULL,
    file_count INT DEFAULT 0,
    total_size_bytes BIGINT DEFAULT 0,
    import_status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
    error_message TEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_import_id (import_id),
    INDEX idx_domain (domain),
    INDEX idx_status (import_status),
    FOREIGN KEY (import_id) REFERENCES cpanel_imports(import_id) ON DELETE CASCADE
);

-- Create table for tracking additional domains assigned to sites
CREATE TABLE IF NOT EXISTS site_domains (
    id INT AUTO_INCREMENT PRIMARY KEY,
    site_id INT NOT NULL,
    domain VARCHAR(255) NOT NULL,
    domain_type ENUM('primary', 'additional', 'subdomain') NOT NULL DEFAULT 'additional',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_site_domain (site_id, domain),
    INDEX idx_site_id (site_id),
    INDEX idx_domain (domain),
    INDEX idx_domain_type (domain_type)
);

-- Add cleanup procedure for old import records (older than 30 days)
DELIMITER //
CREATE PROCEDURE IF NOT EXISTS CleanupOldCpanelImports()
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE import_id_to_delete VARCHAR(64);
    DECLARE cur CURSOR FOR 
        SELECT import_id FROM cpanel_imports 
        WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)
        AND status IN ('completed', 'failed');
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN cur;
    
    read_loop: LOOP
        FETCH cur INTO import_id_to_delete;
        IF done THEN
            LEAVE read_loop;
        END IF;
        
        -- Delete all related records (cascade will handle most)
        DELETE FROM cpanel_imports WHERE import_id = import_id_to_delete;
    END LOOP;
    
    CLOSE cur;
END//
DELIMITER ;

-- Create event to run cleanup weekly (if event scheduler is enabled)
CREATE EVENT IF NOT EXISTS cleanup_old_cpanel_imports
ON SCHEDULE EVERY 1 WEEK
STARTS CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO CALL CleanupOldCpanelImports();

-- Add indexes for better performance (using procedure to handle IF NOT EXISTS)
DELIMITER //
CREATE PROCEDURE IF NOT EXISTS AddCpanelImportIndexes()
BEGIN
    -- Add index if it doesn't exist
    SET @sql = (SELECT IF(
        (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
         WHERE table_schema = DATABASE() AND table_name = 'cpanel_imports' AND index_name = 'idx_username_status') > 0,
        'SELECT ''Index idx_username_status already exists''',
        'ALTER TABLE cpanel_imports ADD INDEX idx_username_status (username, status)'
    ));
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    SET @sql = (SELECT IF(
        (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
         WHERE table_schema = DATABASE() AND table_name = 'cpanel_imported_domains' AND index_name = 'idx_domain_type') > 0,
        'SELECT ''Index idx_domain_type already exists''',
        'ALTER TABLE cpanel_imported_domains ADD INDEX idx_domain_type (domain_type)'
    ));
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    SET @sql = (SELECT IF(
        (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS 
         WHERE table_schema = DATABASE() AND table_name = 'cpanel_imported_databases' AND index_name = 'idx_import_status') > 0,
        'SELECT ''Index idx_import_status already exists''',
        'ALTER TABLE cpanel_imported_databases ADD INDEX idx_import_status (import_status)'
    ));
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END//
DELIMITER ;

-- Execute the procedure and then drop it
CALL AddCpanelImportIndexes();
DROP PROCEDURE AddCpanelImportIndexes;

-- cPanel import functionality tables created successfully