?php

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

function step1() {
	echo "<h2>Nixfile Backup Installer</h2>";
	echo "<p>backup.zip found. Click continue to extract files.</p>";
	echo '<a href="?step=2"><button>Continue</button></a>';
}

function step2() {
	echo "<h2>Extracting backup...</h2>";

	if ( ! file_exists( "backup.zip" ) ) {
		die( "<p><strong>Error:</strong> backup.zip not found in this folder.</p>" );
	}

	$zip = new ZipArchive;
	if ( $zip->open( "backup.zip" ) === true ) {
		$zip->extractTo( "./restore/" );
		$zip->close();
		echo "<p>Backup extracted successfully.</p>";
	} else {
		die( "<p>Error opening ZIP file.</p>" );
	}

	echo '<a href="?step=3"><button>Restore Database</button></a>';
}

function step3() {
	echo "<h2>Restore Database</h2>";

	if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
		echo '
        <form method="post">
            <input type="hidden" name="step" value="3" />
            <label>DB Host: <input name="db_host" value="localhost"></label><br>
            <label>DB User: <input name="db_user"></label><br>
            <label>DB Pass: <input name="db_pass"></label><br>
            <label>DB Name: <input name="db_name"></label><br>
            <button>Run Restore</button>
        </form>';

		return;
	}

	$mysqli = @new mysqli( $_POST['db_host'], $_POST['db_user'], $_POST['db_pass'], $_POST['db_name'] );

	if ( $mysqli->connect_errno ) {
		die( "<p>Connection error: " . $mysqli->connect_error . "</p>" );
	}

	$sql = file_get_contents( "./restore/database.sql" );
	if ( ! $mysqli->multi_query( $sql ) ) {
		die( "<p>SQL Error: " . $mysqli->error . "</p>" );
	}

	echo "<p><strong>Database restored successfully!</strong></p>";
	echo '<a href="?step=4"><button>Finish</button></a>';
}

function step4() {
	echo "<h2>Installation Complete</h2>";
	echo "<p>Your website has been restored. You may now remove installer.php and restore folder.</p>";
}

$step = isset( $_GET['step'] ) ? intval( $_GET['step'] ) : 1;

switch ( $step ) {
	case 1:
		step1();
		break;
	case 2:
		step2();
		break;
	case 3:
		step3();
		break;
	case 4:
		step4();
		break;
	default:
		step1();
}


