<?php

class DXOperationPage
{
    public function  __construct()
    {
        require_once(DANCE_X_PLUGIN_PATH . '/includes/evidence-sync.php');

        // Hook for logged-in users
        //Admin Post Actions admin_post_{hidden_action_in_form}
        add_action('admin_post_sync_with_evidence', array($this, 'syncWithEvidence'));
        add_action('admin_post_verifyEndpoints', array($this, 'verifyEndpoints'));
        add_action('admin_post_drop_all_cct_data', array($this, 'dropAllCctData'));
        add_action('admin_post_executePluginInitialization', array($this, 'executePluginInitialization'));

        add_action('admin_post_add_image_to_media_library', array($this, 'addImageToMediaLibrary'));
        add_action('admin_post_do_activity', array($this, 'doActivity'));
    }

    //static -> to init it in plugin-main-class
    public static function operations_html()
    {
        // check user capabilities
        if (!current_user_can('manage_options')) {
            return;
        }

        if (key_exists("notice", $_GET) && key_exists("type", $_GET)) {
            DXUtil::outputWpNotice($_GET['notice'], $_GET['type']);
        }

        $loadingAsset = plugins_url('assets/img/Blocks@1x-1.0s-200px-200px.svg', __FILE__);

?>

        <div class="loader-block-overlay">
            <div class="loader-svg">
                <img src="<?= esc_url($loadingAsset) ?>" alt="animated loading svg" />
            </div>
        </div>

        <div class="wrap">

            <h1><?php echo get_admin_page_title(); ?></h1>

            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=sync_with_evidence')); ?>">
                <input type="submit" name="submit_form" class="button button-primary w-100" style="font-size: x-large;" value="Synchronize data from Dance-X-Backend (Drop & Create)" onclick="displayLoadingUi()">
            </form>

        </div>

        <div class="wrap" style="margin-top: 40px;">
            <h1>Verifikation</h1>

            <!--  hack: somehow the form-tags have a certain height -> just hacked it with  margin-top:-40px :-/ -->
            <div style="display: flex; flex-direction: row; justify-content: flex-start; margin-top:-30px;">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=verifyEndpoints')); ?>">
                    <input type="submit" name="submit_form" class="button button-secondary mt-5" style="font-size: large;" value="Test Endpoints (WS V1 & WS V2)" onclick="return displayLoadingUi()">
                </form>
            </div>
        </div>

        <div class="wrap" style="margin-top: 40px;">
            <h1>Wartung <span style="font-size: smaller;">(Eltern haften für ihre Kinder!)</span></h1>

            <!--  hack: somehow the form-tags have a certain height -> just hacked it with  margin-top:-40px :-/ -->
            <div style="display: flex; flex-direction: row; justify-content: flex-start; margin-top:-30px;">
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php?action=drop_all_cct_data')); ?>">
                    <input type="submit" name="submit_form" class="button button-secondary mt-5" style="font-size: large;" value="Delete all synchronized data" onclick="return displayLoadingUi('Bist du sicher, das alle synchronisierten Daten gelöscht werden sollen?')">
                </form>

                <form method="post" style="margin-left:20px;" action="<?php echo esc_url(admin_url('admin-post.php?action=executePluginInitialization')); ?>">
                    <input type="submit" name="submit_form" class="button button-secondary mt-5" style="font-size: large;" value="Execute plugin initialization" onclick="return displayLoadingUi('Bei der Dance-X-Plugin-Initialisierung werden alle DX-Tabellen gelöscht (falls vorhanden) und neu angelegt. Zusätzlich werden alle Einträge (von ID 1-999) in der Tabelle jet_post_types neu angelegt.\n\nFortfahren?')">
                </form>
            </div>
        </div>
<?php
    }

    function syncWithEvidence()
    {
        try {
            $syncer = new DXEvidenceSync();
            $result = $syncer->processSync();

            if ($result) {
                $this->redirectToAdminPage("Sync successfully done.", "success");
            } else {
                $this->redirectToAdminPage("Sync failed!", "error");
            }
        } catch (\Throwable $th) {
            $this->redirectToAdminPage("Something went wrong. Message:" . $th->getMessage(), "error");
        }
    }

    function verifyEndpoints()
    {
        $backendComm = new DXBackendCommunication();

        try {

            $options = $backendComm->getRestApiOptions();

            $isWsV1Callable = $backendComm->isWsV1Callable();
            $isWsV2Callable = $backendComm->isWsV2Callable();

            if ($isWsV1Callable && $isWsV2Callable) {
                $this->redirectToAdminPage("Both Endpoints {$options->endpoint} and {$options->endpointV2} are answering successfully.", "success");
            } else if (!$isWsV1Callable && $isWsV2Callable) {
                $this->redirectToAdminPage("Endpoint {$options->endpoint} IS NOT answering and {$options->endpointV2} is answering successfully!", "error");
            } else if ($isWsV1Callable && !$isWsV2Callable) {
                $this->redirectToAdminPage("Endpoint {$options->endpoint} is answering successfully and {$options->endpointV2} IS NOT answering!", "error");
            } else {
                $this->redirectToAdminPage("Both Endpoints {$options->endpoint} and {$options->endpointV2} ARE NOT answering!", "error");
            }
        } catch (\Throwable $th) {
            $this->redirectToAdminPage("Something went wrong. Message:" . $th->getMessage(), "error");
        }
    }

    function dropAllCctData()
    {
        try {
            $da = new DXDataAccess();
            $result = $da->cleanupDatabaseFromDanceXData();

            if ($result) {
                $this->redirectToAdminPage("Delete all synced data done.", "success");
            } else {
                $this->redirectToAdminPage("Something went wrong...", "error");
            }
        } catch (\Throwable $th) {
            $this->redirectToAdminPage("Something went wrong. Message:" . $th->getMessage(), "error");
        }
    }

    function executePluginInitialization()
    {
        try {

            //we execute this method additonally to also remove old CPT-data of the DX-CCTs (which are living in table wp_posts)
            $this->dropAllCctData();

            $installer = new DXInstaller();
            $ret = $installer->executePluginInitialization();

            if ($ret) {
                $this->redirectToAdminPage("Plugin successfully initializied.", "success");
            } else {
                $this->redirectToAdminPage("Something went wrong. More infos in log.", "error");
            }
        } catch (\Throwable $th) {
            $this->redirectToAdminPage("Something went wrong. Message:" . $th->getMessage(), "error");
        }
    }

    function addImageToMediaLibrary()
    {
        if (!(key_exists("_wpnonce", $_POST) && wp_verify_nonce($_POST['_wpnonce'], "n2"))) {
            $this->redirectToAdminPage("Nonce invalid!", "error");
            exit;
        }

        $base64Image = file_get_contents(DANCE_X_PLUGIN_PATH . "base64Img.txt");
        DXUtil::importImageToMediaLibrary($base64Image);

        $this->redirectToAdminPage("Image added.", "success");

        exit;
    }

    function doActivity()
    {
        if (!(key_exists("_wpnonce", $_POST) && wp_verify_nonce($_POST['_wpnonce'], "n3"))) {
            $this->redirectToAdminPage("Nonce invalid!", "error");
            exit;
        }

        try {

            //add code here to do some stuff

            $this->redirectToAdminPage("Ok: Keine Aktivität definiert ...", "info");
        } catch (\Throwable $th) {
            $this->redirectToAdminPage("Ex happended: " . $th->getMessage(), "error");
        }
        exit;
    }

    function redirectToAdminPage($notice, $type)
    {
        $encodedNotice = urlencode($notice);
        wp_redirect(admin_url("admin.php?page=dxcp_operations&notice=$encodedNotice&type=$type"));
    }
}

$dxOperationPage = new DXOperationPage();
