<?php

require_once(MH_DIR_CONFIG . 'config_api/classes/apibeez.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'common/functions/email_engine_php_mailer.php');
require_once(mh_cfg('MH_DIR_CONFIG') . 'config_email_engine.php');
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . '/common/classes/mailbeez_system.php');

error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', mh_cfg('MAILBEEZ_API_DEBUG', 0));


class api_public_sitezen_application extends apibeez
{

    function __construct()
    {
        parent::__construct();
        $this->has_get = true;
        mh_session_write_close();
    }


    // GET api/public/v1.0/sitezen/application/
    // requires HTTP_X_TOKEN
    function _get($request_data, $payload_data)
    {
        if (isset($_SERVER['HTTP_X_TOKEN']) && $_SERVER['HTTP_X_TOKEN'] == mh_cfg('MAILBEEZ_CONFIG_SITEZEN_TOKEN')) {
            if ($request_data[0]??'' == 'threats_users') {
                $result = self::get_admin_user();
            } else {
                $result = [
                    'platform' => mh_cfg('MH_SITEZEN_PLATFORM', false),
                    'version' => mh_cfg('MH_SITEZEN_PLATFORM_VERSION', false),
                    'configuration' => self::get_configuration(),
                    'plugins' => self::get_plugins(),
                ];
            }
        } else {
            $result = ['error' => 'invalid request'];
        }



        $return = $result;
        $return['_request'] = [
            'time' => round(microtime(true) - constant('MAILHIVE_START_TIME'), 3),
            'memory' => round((memory_get_usage() - constant('MAILHIVE_START_MEMORY')) / 1024 / 1024, 3),
        ];

//        $return['_request'] = [
//            'time' => round(microtime(true) - constant('SITEZEN_START_TIME'), 3),
//            'memory' => round((memory_get_usage() - constant('SITEZEN_START_MEMORY')) / 1024 / 1024, 3),
//        ];

        header('Content-Type: application/json; Charset=UTF-8');
        echo json_encode($return);
        mh_exit();

    }

    public static function get_admin_user()
    {

        $query = mh_db_query("select customers_id, customers_firstname, customers_lastname, customers_email_address, customers_date_added, customers_last_modified from " . TABLE_CUSTOMERS . " where customers_status = 0");
        $admin_users = [];


        while ($row = mh_db_fetch_array($query)) {
            $admin_users[] = [
                'id' => $row['customers_id'],
                'username' => $row['customers_firstname'] . ' ' . $row['customers_lastname'],
                'email' => self::obfuscate_email($row['customers_email_address']),
                'email_hash' =>  hash('sha256', trim(strtolower($row['customers_email_address']))),
                'active' => true,
                'created_at' => $row['customers_date_added'] ?? '',
                'updated_at' => $row['customers_last_modified'] ?? ''
            ];
        }
        return [
            'admin_users' => $admin_users
        ];

    }

    static function obfuscate_email($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return 'Invalid email';
        }

        [$user, $domain] = explode('@', $email);

        // Show first and last character, replace middle with asterisks
        $obfuscated_user = substr($user, 0, 2) . str_repeat('*', max(1, strlen($user) - 3)) . substr($user, -1);

        return $obfuscated_user . '@' . $domain;
    }

    public static function get_configuration()
    {
        $result = [
            'mail' => [
                // allow to check mail transport
                'transport' => mh_cfg('EMAIL_TRANSPORT', false),
                // allow to check if mail sender is valid
                'from' => mh_cfg('EMAIL_FROM', false),
            ]
        ];
        return $result;
    }

    public static function get_plugins()
    {


        $transport = (mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE', false) == 'PHPMailer') ? 'SMTP' : mh_cfg('MAILBEEZ_CONFIG_EMAIL_ENGINE', false);
        $server = '';
        $connectionTest = '';

        if ($transport == 'SMTP') {
            $server = mh_cfg('MAILBEEZ_SMTP_MAIN_SERVER', false);
            $connectionTest = config_email_engine::connection_test();
        }

        if ($transport == 'mlbz_ubvx') {
            $server = 'mailbeez.email';
            $connectionTest = config_email_engine::connection_test();
        }

        /*
             "akismet/akismet.php": {
        "name": "Akismet Anti-spam: Spam Protection",
        "version": "5.3.3",
        "active": false,
        "update": {
            "new_version": "5.3.5",
            "wp_requires": "5.8",
            "wp_tested": "6.7.1",
            "requires_php": "5.6.20",
            "requires_plugins": []
        }
    },
         *
         */

        $result = [
            'mailbeez' => [
                'name' => "Mailbeez",
                // allow to check if mailbeez is up to date
                'version' => mh_cfg('MAILBEEZ_VERSION', false),
                'active' => true,
                'update' => [
                    'new_version' => false,
                    'requires_php' => 7.4,
                ],
                'meta' => [
                    // allow to check email trasport
                    'transport' => $transport,
                    'server' => $server,

                    'connection_test' => $connectionTest,
                    // allow to check if system runs
                    'last_action' => mailbeez_system::getLastAction(),
                    // allow to check if gambiocloud
                    'is_cloud' => mh_cfg('is_cloud', false)
                ]
            ],
        ];
        return $result;
    }

}