<?php

require_once __DIR__ . "/vendor/autoload.php";
include_once "Fury/fury.php";
$app = fury_init("SHServ");

function console() {
	global $argv;

	if(!isset($argv[1])) {
		echo "Usage: php console.php <command> [args]\n";
		echo "\nCommands:\n";
		echo "  get.config                           Show server config (without DB credentials)\n";
		echo "  run-regular-script <alias>           Run a regular control script by alias\n";
		echo "  migrate                              Run all pending migrations\n";
		echo "  migrate:rollback [steps]             Rollback last batch of migrations\n";
		echo "  migrate:status                       Show applied and pending migrations\n";
		echo "  migrate:create <name>                Generate a new migration file\n";
		echo "\n";
		return;
	}

	$command = $argv[1];

	switch($command) {
		case "get.config":
			$config = FCONF;
			unset($config['db']['password']);
			unset($config['db']['user']);
			echo json_encode($config);
		break;

		case "run-regular-script":
			if(!isset($argv[2])) {
				echo "No alias provided\n";
				exit(1);
			}
			$alias = $argv[2];
			$result = \SHServ\Middleware\ControlScripts::run_regular_script($alias);
			if(!$result) {
				exit(1);
			}
		break;

		case "migrate":
			$manager = new \SHServ\Migrations\MigrationsManager();
			$applied = $manager -> migrate();
			if(empty($applied)) {
				echo "Nothing to migrate.\n";
			} else {
				echo "Applied " . count($applied) . " migration(s):\n";
				foreach($applied as $file) {
					echo "  ✓ {$file}\n";
				}
			}
		break;

		case "migrate:rollback":
			$steps = isset($argv[2]) ? (int) $argv[2] : 1;
			$manager = new \SHServ\Migrations\MigrationsManager();
			$rolled = $manager -> rollback($steps);
			if(empty($rolled)) {
				echo "Nothing to rollback.\n";
			} else {
				echo "Rolled back " . count($rolled) . " migration(s):\n";
				foreach($rolled as $file) {
					echo "  ↶ {$file}\n";
				}
			}
		break;

		case "migrate:status":
			$manager = new \SHServ\Migrations\MigrationsManager();
			$status = $manager -> status();
			echo "Applied migrations:\n";
			if(empty($status['applied'])) {
				echo "  (none)\n";
			} else {
				foreach($status['applied'] as $row) {
					echo "  [batch {$row['batch']}] {$row['file']}\n";
				}
			}
			echo "\nPending migrations:\n";
			if(empty($status['pending'])) {
				echo "  (none)\n";
			} else {
				foreach($status['pending'] as $file) {
					echo "  … {$file}\n";
				}
			}
		break;

		case "migrate:create":
			if(!isset($argv[2])) {
				echo "Migration name required.\n";
				echo "Usage: php console.php migrate:create <name>\n";
				exit(1);
			}
			$name = $argv[2];
			$manager = new \SHServ\Migrations\MigrationsManager();
			$filename = $manager -> create($name);
			echo "Created migration: {$filename}\n";
		break;

		default:
			echo "Unknown command: {$command}\n";
			exit(1);
	}

	echo "\n";
}

console();
