<?php
/**
 * Announcements Setup Script
 * This script creates the announcements table in the database
 * Run this script as root to set up the announcements feature
 */

// 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 "Announcements 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 SQL file
echo "Creating announcements table...\n";
$sql_file = '/root/whp/sql/announcements.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;

foreach ($sql_statements as $statement) {
    $statement = trim($statement);
    if (empty($statement) || strpos($statement, '--') === 0) {
        continue;
    }
    
    try {
        $pdo->exec($statement);
        $success_count++;
        if (strpos(strtoupper($statement), 'CREATE TABLE') !== false) {
            echo "✓ Table created successfully\n";
        } elseif (strpos(strtoupper($statement), 'INSERT') !== false) {
            echo "✓ Sample data inserted\n";
        }
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'already exists') !== false) {
            echo "⚠ Table already exists (skipping)\n";
        } else {
            echo "✗ Error executing statement: " . $e->getMessage() . "\n";
            $error_count++;
        }
    }
}

echo "\nSetup completed!\n";
echo "Successfully executed: $success_count statements\n";
echo "Errors: $error_count statements\n\n";

if ($error_count == 0) {
    echo "✓ Announcements feature is ready to use!\n";
    echo "\nYou can now:\n";
    echo "1. Access the web panel as root\n";
    echo "2. Navigate to 'Announcements Management'\n";
    echo "3. Create and manage server announcements\n";
    echo "4. Users will see announcements on the dashboard\n\n";
} else {
    echo "⚠ Some errors occurred during setup. Please check the output above.\n";
}

echo "Done.\n";
?> 