<?php

require_once SC_PLUGIN_PATH . '/commands/wp/getmeta.php';
require_once SC_PLUGIN_PATH . '/commands/users/get.php';
require_once SC_PLUGIN_PATH . '/commands/users/createsession.php';
require_once SC_PLUGIN_PATH . '/commands/favicon/get.php';
require_once SC_PLUGIN_PATH . '/commands/plugin/update.php';
require_once SC_PLUGIN_PATH . '/commands/matomo/hastracker.php';
require_once SC_PLUGIN_PATH . '/commands/matomo/settrackingcode.php';

$sc_command_map = [
  'wp getmeta'             => new SC_Command_WP_Getmeta(),
  'users get'              => new SC_Command_Users_Get(),
  'users createsession'    => new SC_Command_Users_CreateSession(),
  'favicon get'            => new SC_Command_Favicon_Get(),
  'plugin update'          => new SC_Commamd_Plugin_Update(),
  'matomo hastracker'      => new SC_Command_Matomo_Has_Tracker(),
  'matomo settrackingcode' => new SC_Command_Matomo_Set_Tracking_Code()
];

function sc_command_dispatch(string $command, array $arguments)
{
    global $sc_command_map;
    if (!isset($sc_command_map[$command])) {
        throw new Exception('Invalid request. Command ' . $command . ' does not exist. The plugin might be outdated.');
    }

    $commandInstance = $sc_command_map[$command];
    $commandInstance->set_args($arguments);

    // attempt to execute the command...
    try {
        $result = $commandInstance->execute();
        if ($result['success']) {
            return [
              'success' => true,
              'message' => $result['message'],
              'data'    => $result['data']
            ];
        } else {
            // bad command execution...
            return [
              'success' => false,
              'message' => $result['message'],
              'data'    => []
            ];
        }
    } catch (Exception $e) {
        throw new Exception('Error during execute command thread: ' . $e->getMessage());
    }
}
