<?php
/**
 * Complete Database Setup Script
 * This script creates all necessary database structures for WHP
 * Run this script as root to set up the complete database environment
 */

// Check if running as root (alternative method without posix extension)
$current_user = shell_exec('whoami');
if (trim($current_user) !== 'root') {
    die("This script must be run as root\n");
}

/**
 * Read MySQL password from /root/.my.cnf
 */
function getMySQLPasswordFromConfig() {
    $config_file = '/root/.my.cnf';
    
    if (!file_exists($config_file)) {
        die("ERROR: MySQL config file not found: $config_file\n");
    }
    
    $config_content = file_get_contents($config_file);
    if ($config_content === false) {
        die("ERROR: Cannot read MySQL config file: $config_file\n");
    }
    
    // Parse the MySQL config file manually (more robust than parse_ini_string)
    $lines = explode("\n", $config_content);
    $in_client_section = false;
    $password = null;
    
    foreach ($lines as $line) {
        $line = trim($line);
        
        // Skip empty lines and comments
        if (empty($line) || $line[0] === '#') {
            continue;
        }
        
        // Check for section headers
        if (preg_match('/^\[([^\]]+)\]$/', $line, $matches)) {
            $in_client_section = ($matches[1] === 'client');
            continue;
        }
        
        // Look for password in client section
        if ($in_client_section && preg_match('/^password\s*=\s*(.*)$/', $line, $matches)) {
            $password = trim($matches[1]);
            // Remove quotes if present
            $len = strlen($password);
            if ($len >= 2 && 
                (($password[0] === '"' && $password[$len-1] === '"') || 
                 ($password[0] === "'" && $password[$len-1] === "'"))) {
                $password = substr($password, 1, -1);
            }
            break;
        }
    }
    
    if ($password === null) {
        die("ERROR: MySQL password not found in config file: $config_file\n");
    }
    
    return $password;
}

// Set the MySQL password for the mysqlmgmt to use
$mysql_password = getMySQLPasswordFromConfig();
define('MYSQL_PASS', $mysql_password);

// Load libraries
require_once('/root/whp/web-files/libs/mysqlmgmt.php');

$MySQLMgmt = new mysqlmgmt();

echo "WHP Complete Database Setup Script\n";
echo "==================================\n\n";

// Test MySQL connection
echo "Testing MySQL connection...\n";
$test_result = $MySQLMgmt->testConnection('root', trim(MYSQL_PASS));
if ($test_result['status'] !== '0') {
    echo "ERROR: Cannot connect to MySQL as root. Please check:\n";
    echo "1. MySQL is running\n";
    echo "2. Root password is configured in /root/.my.cnf\n";
    echo "3. MySQL root user has proper privileges\n\n";
    exit(1);
}
echo "✓ MySQL connection successful\n\n";

// Read and execute the complete database setup file
echo "Setting up complete WHP database structure...\n";
$sql_file = '/root/whp/sql/complete-database-setup.sql';

if (!file_exists($sql_file)) {
    echo "ERROR: SQL file not found: $sql_file\n";
    exit(1);
}

$sql_content = file_get_contents($sql_file);
$sql_statements = explode(';', $sql_content);

$pdo = $MySQLMgmt->getMySQLConnection();
if (!$pdo) {
    echo "ERROR: Failed to get MySQL connection\n";
    exit(1);
}

$success_count = 0;
$error_count = 0;
$table_count = 0;
$insert_count = 0;

echo "Processing database setup statements...\n";
echo "----------------------------------------\n";

foreach ($sql_statements as $statement) {
    $statement = trim($statement);
    if (empty($statement) || strpos($statement, '--') === 0) {
        continue;
    }
    
    try {
        $pdo->exec($statement);
        $success_count++;
        
        // Provide specific feedback based on statement type
        if (stripos($statement, 'CREATE DATABASE') !== false) {
            echo "✓ Database 'whp' created/verified\n";
        } elseif (stripos($statement, 'CREATE TABLE') !== false) {
            $table_count++;
            // Extract table name
            preg_match('/CREATE TABLE.*?`?(\w+)`?\s*\(/i', $statement, $matches);
            $table_name = isset($matches[1]) ? $matches[1] : 'unknown';
            echo "✓ Table '$table_name' created/verified\n";
        } elseif (stripos($statement, 'ALTER TABLE') !== false) {
            // Extract table name from ALTER statement
            preg_match('/ALTER TABLE.*?`?(\w+)`?\s/i', $statement, $matches);
            $table_name = isset($matches[1]) ? $matches[1] : 'unknown';
            echo "✓ Table '$table_name' structure updated\n";
        } elseif (stripos($statement, 'INSERT') !== false) {
            $insert_count++;
            // Extract table name from INSERT statement
            preg_match('/INSERT.*?INTO.*?`?(\w+)`?\s*\(/i', $statement, $matches);
            $table_name = isset($matches[1]) ? $matches[1] : 'unknown';
            echo "✓ Sample data inserted into '$table_name'\n";
        } elseif (stripos($statement, 'SELECT') !== false && stripos($statement, 'status') !== false) {
            echo "✓ Setup verification completed\n";
        }
        
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'already exists') !== false) {
            echo "⚠ Resource already exists (skipping)\n";
        } elseif (strpos($e->getMessage(), 'Duplicate entry') !== false) {
            echo "⚠ Duplicate data entry (skipping)\n";
        } else {
            echo "✗ Error executing statement: " . $e->getMessage() . "\n";
            echo "Statement: " . substr($statement, 0, 100) . "...\n";
            $error_count++;
        }
    }
}

echo "\n";
echo "Database Setup Summary\n";
echo "======================\n";
echo "Total statements processed: " . ($success_count + $error_count) . "\n";
echo "Successful operations: $success_count\n";
echo "Tables created/verified: $table_count\n";
echo "Data insertions: $insert_count\n";
echo "Errors encountered: $error_count\n\n";

// Verify critical tables exist
echo "Verifying critical database structure...\n";
echo "----------------------------------------\n";

$critical_tables = [
    'user_databases' => 'Database management',
    'database_users' => 'Database user management', 
    'user_passwords' => 'User authentication',
    'client_allowances' => 'Resource management',
    'container_types' => 'Container configurations',
    'domains' => 'Domain management',
    'containers' => 'Container instances',
    'announcements' => 'Announcements system',
    'container_env_templates' => 'Environment templates',
    'container_user_variables' => 'User variables'
];

$missing_tables = [];
foreach ($critical_tables as $table => $description) {
    try {
        $result = $pdo->query("SHOW TABLES LIKE " . $pdo->quote($table));
        if ($result->rowCount() > 0) {
            echo "✓ $table ($description)\n";
        } else {
            echo "✗ $table ($description) - MISSING\n";
            $missing_tables[] = $table;
        }
    } catch (PDOException $e) {
        echo "✗ $table ($description) - ERROR: " . $e->getMessage() . "\n";
        $missing_tables[] = $table;
    }
}

echo "\n";

if (count($missing_tables) == 0 && $error_count == 0) {
    echo "🎉 DATABASE SETUP COMPLETED SUCCESSFULLY!\n";
    echo "=========================================\n\n";
    echo "✓ All critical tables are present\n";
    echo "✓ No errors encountered\n";
    echo "✓ WHP database is ready for use\n\n";
    echo "Next steps:\n";
    echo "1. Complete the WHP setup process\n";
    echo "2. Create system users for hosting clients\n";
    echo "3. Access the web panel to verify functionality\n";
    echo "4. Check announcements system in the dashboard\n\n";
} else {
    echo "⚠ SETUP COMPLETED WITH ISSUES\n";
    echo "==============================\n\n";
    if (count($missing_tables) > 0) {
        echo "Missing tables: " . implode(', ', $missing_tables) . "\n";
    }
    if ($error_count > 0) {
        echo "SQL errors encountered: $error_count\n";
    }
    echo "\nPlease review the output above and address any issues.\n";
    echo "You may need to run the setup again or manually create missing tables.\n\n";
}

echo "Done.\n";
?> 