<?php

if ( ! defined( 'ABSPATH' ) ) exit;

function docuchat_plugin_register()
{ 
    echo wp_json_encode(docuchat_process_token());   
    wp_die();
}

function docuchat_process_token()
{
    try {
        if (
            isset($_POST["token"]) && !empty($_POST["token"]) &&
            isset($_POST["email"]) && !empty($_POST["email"]) &&
            isset($_POST["nonce"]) && !empty($_POST["nonce"]) &&
            wp_verify_nonce( wp_unslash( $_POST["nonce"])  , 'register' )
        ) {

            $sanitized_unlashed_email = sanitize_file_name( wp_unslash( $_POST["email"]) );
            $sanitized_unlashed_token = sanitize_file_name( wp_unslash( $_POST["token"]) );

            null !== get_option(DOCUCHAT_TOKEN) ? update_option(DOCUCHAT_TOKEN, $sanitized_unlashed_token) : add_option(DOCUCHAT_TOKEN, $sanitized_unlashed_token);
            null !== get_option(DOCUCHAT_EMAIL) ? update_option(DOCUCHAT_EMAIL,  $sanitized_unlashed_email) : add_option(DOCUCHAT_EMAIL,  $sanitized_unlashed_email);

            $getOptions = unserialize(get_option(DOCUCHAT_ACTIVATION_SERIALIZACION));
            $getOptions[0] = false;
            $getOptions[1] = "active";

            update_option(DOCUCHAT_ACTIVATION_SERIALIZACION, serialize($getOptions));

            return array("status" => 200, "message" => "plugin registered successfully");
        } else {
            return array("status" => 400, "message" => "plugin register failed");
        }
    } catch (\Throwable $th) { 
        return array("status" => 400, "message" => "Error registering data: " . $th->getMessage());
    }
}
