<?php
use SiteZen\Telemetry\Bootstrap;
use SiteZen\Telemetry\Connectors\Application;


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

define('SITEZEN_CONNECTOR_VERSION', '1.6.0');
define('SITEZEN_CONNECTOR_TYPE', 'mailbeez');

include __DIR__ . '/../sitezen/Bootstrap/bootstrap.php';
include __DIR__ . '/../sitezen/Bootstrap/env.php';
include __DIR__ . '/../sitezen/Bootstrap/config.php';
include __DIR__ . '/../connectors/Application.php';
include __DIR__ . '/../connectors/DatabaseAdapter/MysqliAdapter.php';


// locate env file and map env settings
$envFilePath = realpath(dirname(__FILE__) . '/../.sitezen.env.php');


try {
    // load config
    $config = Bootstrap\config::config($envFilePath);

    $headerToken = $_SERVER['HTTP_X_SITEZEN_TOKEN'] ?? ''; // should not happen as this is required in inc_mailhive.php

    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

    \SiteZen\Telemetry\Bootstrap\helper::sitezen_header();

    // check gate
    Bootstrap\Gate::check($config, $headerToken, $method);

} catch (\Exception $e) {

    $code = $e->getCode() ?: 401;

    header('X-SiteZen-Status: ' . $code);
    header('X-SiteZen-Reason: ' . $e->getMessage());
    header('HTTP/1.0 ' . $code);

    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage(), 'code' => $code]);
    exit;
}

// start performance measurement
Bootstrap\Performance::start();

$config['db_adapter'] = new \SiteZen\Telemetry\Connectors\DatabaseAdapters\MysqliAdapter($config);


// the root path set to analyse the disk usage for this wordpress installation
// this allows sitezen to find the largest files and folders
$config['rootPath'] = $_SERVER['DOCUMENT_ROOT'] . '/';

// assign server variables
$config['SERVER_NAME'] = $_SERVER['SERVER_NAME']??'';
$config['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']??'';
$config['SERVER_SOFTWARE'] = $_SERVER['SERVER_SOFTWARE']??'';

// assign system information
$config['PHP_OS_FAMILY'] = PHP_OS_FAMILY;

$payload = file_get_contents("php://input");
$request = json_decode($payload, true);

// initialize process handler
$process = new Bootstrap\Process($config, $request);

// register plugin handlers
    $process->registerHandler('application:data', function ($request) use ($config) {
    return Application::applicationData($config);
});

$process->registerHandler('threats:admin_users', fn($request) => Application::threatsUserData($config));


//$process->registerHandler('application:cleanup', function ($request) use ($config) {
//    return [
//        'cleanup' => Application::cleanup($config, $request),
//    ];
//});

$data = $process->executeHandler();

// return data as json
(new Bootstrap\Data($data, Bootstrap\Performance::end()))->output();
