<?php
// One-click Database Installer
// Compatible with PHP 7.0 to Latest
// Allows multiple installations (overwrites existing tables).

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Increase memory limit and execution time for large SQL files
ini_set('memory_limit', '256M');
set_time_limit(300);

$message = '';
$error = '';

// Check if config file exists
$configFile = dirname(__DIR__) . '/config/config.php';
$hasConfig = file_exists($configFile);

$dbHost = 'localhost';
$dbName = 'binary_options';
$dbUser = 'root';
$dbPass = '';
$siteUrl = '';

if ($hasConfig) {
    // Try to extract credentials from config.php safely without including it to prevent premature redirects
    $configContent = file_get_contents($configFile);
    if (preg_match("/define\('DB_HOST',\s*'([^']+)'\);/", $configContent, $matches)) $dbHost = $matches[1];
    if (preg_match("/define\('DB_NAME',\s*'([^']+)'\);/", $configContent, $matches)) $dbName = $matches[1];
    if (preg_match("/define\('DB_USER',\s*'([^']+)'\);/", $configContent, $matches)) $dbUser = $matches[1];
    if (preg_match("/define\('DB_PASS',\s*'([^']*)'\);/", $configContent, $matches)) $dbPass = $matches[1];
    if (preg_match("/define\('SITE_URL',\s*'([^']+)'\);/", $configContent, $matches)) $siteUrl = $matches[1];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $dbHost = $_POST['db_host'] ?? $dbHost;
    $dbName = $_POST['db_name'] ?? $dbName;
    $dbUser = $_POST['db_user'] ?? $dbUser;
    $dbPass = $_POST['db_pass'] ?? $dbPass;
    $siteUrl = rtrim(trim($_POST['site_url'] ?? $siteUrl), '/');

    try {
        // Create mysqli connection Without Database First
        $conn = @new mysqli($dbHost, $dbUser, $dbPass);

        if ($conn->connect_error) {
            throw new Exception("Database connection failed: " . $conn->connect_error);
        }

        // Create database if not exists
        if (!$conn->query("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")) {
            throw new Exception("Error creating database: " . $conn->error);
        }
        
        // Select the database
        $conn->select_db($dbName);
        $conn->set_charset("utf8mb4");

        // Find all SQL files in the current directory
        $sqlFiles = glob(__DIR__ . '/*.sql');
        
        if (empty($sqlFiles)) {
            $error = "No SQL files found in the database directory!";
        } else {
            $importedCount = 0;
            
            foreach ($sqlFiles as $file) {
                // Read SQL file
                $sql = file_get_contents($file);
                
                // Convert encoding if file is UTF-16 LE (BOM: FF FE)
                if (substr($sql, 0, 2) === "\xFF\xFE") {
                    $sql = mb_convert_encoding($sql, 'UTF-8', 'UTF-16LE');
                }
                // Convert encoding if file is UTF-16 BE (BOM: FE FF)
                elseif (substr($sql, 0, 2) === "\xFE\xFF") {
                    $sql = mb_convert_encoding($sql, 'UTF-8', 'UTF-16BE');
                }
                // Remove UTF-8 BOM if present
                if (substr($sql, 0, 3) === "\xEF\xBB\xBF") {
                    $sql = substr($sql, 3);
                }
                
                // Execute multi query
                if ($conn->multi_query($sql)) {
                    do {
                        // Store first result set
                        if ($result = $conn->store_result()) {
                            $result->free();
                        }
                    } while ($conn->more_results() && $conn->next_result());
                    
                    if ($conn->errno) {
                        throw new Exception("Error importing file " . basename($file) . ": " . $conn->error);
                    }
                    $importedCount++;
                } else {
                    throw new Exception("Error executing SQL in " . basename($file) . ": " . $conn->error);
                }
            }

            // Update config if fields were changed
            if ($hasConfig && is_writable($configFile)) {
                $configContent = file_get_contents($configFile);
                $configContent = preg_replace("/define\('DB_HOST',\s*'.*?'\);/", "define('DB_HOST', '$dbHost');", $configContent);
                $configContent = preg_replace("/define\('DB_NAME',\s*'.*?'\);/", "define('DB_NAME', '$dbName');", $configContent);
                $configContent = preg_replace("/define\('DB_USER',\s*'.*?'\);/", "define('DB_USER', '$dbUser');", $configContent);
                $configContent = preg_replace("/define\('DB_PASS',\s*'.*?'\);/", "define('DB_PASS', '$dbPass');", $configContent);

                // Update SITE_URL if provided
                if (!empty($siteUrl)) {
                    // Replace dynamic SITE_URL detection block with hardcoded value
                    $siteUrlBlock = "if (!defined('SITE_URL')) {\n"
                        . "    // Site Settings\n"
                        . "    define('SITE_URL', '$siteUrl');\n"
                        . "    define('SITE_NAME', 'BinaryPro');\n"
                        . "    define('APP_NAME', 'BinaryPro');\n"
                        . "}";
                    $configContent = preg_replace(
                        "/if \(!defined\('SITE_URL'\)\)\s*\{.*?\}/s",
                        $siteUrlBlock,
                        $configContent
                    );
                }

                file_put_contents($configFile, $configContent);
            }

            $message = "Installation completed successfully! Imported $importedCount SQL file(s).";
        }
        $conn->close();
    } catch (Exception $e) {
        $error = "Error: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Database Installer</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
        .install-container { background: white; padding: 30px 40px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); width: 100%; max-width: 500px; }
        h1 { text-align: center; color: #2c3e50; margin-bottom: 20px; font-size: 24px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: 600; color: #555; }
        input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-size: 14px; }
        input[type="text"]:focus, input[type="password"]:focus { border-color: #3498db; outline: none; }
        .btn { background-color: #3498db; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; width: 100%; font-size: 16px; font-weight: bold; transition: background 0.3s; }
        .btn:hover { background-color: #2980b9; }
        .alert { padding: 15px; border-radius: 4px; margin-bottom: 20px; text-align: center; }
        .alert-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .note { font-size: 13px; color: #777; margin-top: 20px; text-align: center; }
    </style>
</head>
<body>

<div class="install-container">
    <h1>1-Click Database Installer</h1>
    
    <?php if ($message): ?>
        <div class="alert alert-success">
            <strong>Success!</strong><br><?php echo $message; ?>
            <br><br>
            <a href="../index.php" class="btn" style="text-decoration:none; display:inline-block; margin-top:10px;">Go to Homepage</a>
        </div>
    <?php else: ?>
        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo $error; ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <div class="form-group">
                <label for="db_host">Database Host</label>
                <input type="text" id="db_host" name="db_host" value="<?php echo htmlspecialchars($dbHost); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="db_user">Database Username</label>
                <input type="text" id="db_user" name="db_user" value="<?php echo htmlspecialchars($dbUser); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="db_pass">Database Password</label>
                <input type="password" id="db_pass" name="db_pass" value="<?php echo htmlspecialchars($dbPass); ?>" placeholder="Leave empty for XAMPP">
            </div>
            
            <div class="form-group">
                <label for="db_name">Database Name</label>
                <input type="text" id="db_name" name="db_name" value="<?php echo htmlspecialchars($dbName); ?>" required>
            </div>

            <hr style="margin:20px 0; border:none; border-top:1px solid #eee;">

            <div class="form-group">
                <label for="site_url">Website URL</label>
                <input type="text" id="site_url" name="site_url" value="<?php echo htmlspecialchars($siteUrl); ?>" placeholder="https://yourdomain.com/binary" required>
                <small style="color:#888; font-size:12px;">Enter your full website URL without trailing slash. All paths (admin, user, api) will auto-update.</small>
            </div>
            
            <button type="submit" class="btn">Install Database</button>
        </form>
        
        <div class="note">
            This installer works with PHP 7.0 to the latest versions. It will create the database '<strong><?php echo htmlspecialchars($dbName); ?></strong>' and import all <code>.sql</code> files in this folder.<br>
            <strong>Note:</strong> Installing again will overwrite existing tables since the SQL file contains DROP TABLE statements.
        </div>
    <?php endif; ?>
</div>

</body>
</html>
