<?php

add_action("admin_init", "nc_sample_register_option");
add_action("admin_init", "nc_sample_activate_license");
add_action("admin_init", "nc_sample_deactivate_license");
function nc_sample_license_page()
{
    $status = get_option("nc_sample_license_status");
    add_settings_section("nc_sample_license", __("Licencia del Plugin", "nichecreator"), "nc_sample_license_key_settings_section", "nichecreator_license");
    add_settings_field("nc_sample_license_key", "<label for=\"nc_sample_license_key\">" . __("Clave de licencia", "nichecreator") . "</label>", "nc_sample_license_key_settings_field", "nichecreator_license", "nc_sample_license");
    echo "\t<div class=\"wrap\">\n\t\t<h2>";
    esc_html_e("Opciones de Licencia", "nichecreator");
    echo "</h2>\n\t\t<form method=\"post\" action=\"options.php\">\n\t\t\t";
    do_settings_sections("nichecreator_license");
    settings_fields("nc_sample_license");
    if($status != "valid") {
        echo "<script>jQuery(document).ready(function($) { $(\"#nc_sample_license_key\").val(\"babiato\"); $(\"#nc_sample_license_key\").prop(\"disabled\", false); $('input[name=\"nc_license_activate\"]').hide(); });</script>";
    } else {
        echo "<script>jQuery(document).ready(function($) { $(\"#nc_sample_license_key\").prop(\"disabled\", true); });</script>";
    }
    echo "\t\t</form>\n\t";
}
function nc_sample_license_key_settings_section()
{
    esc_html_e("Si quieres recibir actualizaciones automáticas debes introducir tu clave de licencia.", "nichecreator");
}
function nc_sample_license_key_settings_field()
{
    $license = get_option("nc_sample_license_key");
    $status = get_option("nc_sample_license_status");
    echo "\t<!-- <p class=\"description\">";
    esc_html_e("Introduce tu clave de licencia.", "nichecreator");
    echo "</p> -->\n\t";
    printf("<input type=\"password\" class=\"regular-text\" id=\"nc_sample_license_key\" name=\"nc_sample_license_key\" value=\"%s\" />", esc_attr($license));
    $button = ["name" => "nc_license_deactivate", "label" => __("Desactivar Licencia", "nichecreator")];
    if("valid" !== $status) {
        $button = ["name" => "nc_license_activate", "label" => __("Activar Licencia", "nichecreator")];
    }
    if($status == "valid") {
        echo "<p class=\"valida\">" . __("Licencia válida", "nichecreator") . "</p>";
    } else {
        echo "<p class=\"valida\">" . __("Licencia válida", "nichecreator") . "</p>";
    }
    wp_nonce_field("nc_sample_nonce", "nc_sample_nonce");
    echo "\t \n\t";
    if($status != "valid") {
        echo "\t<input type=\"submit\" class=\"button-secondary\" name=\"";
        echo esc_attr($button["name"]);
        echo "\" value=\"";
        echo esc_attr($button["label"]);
        echo "\"/>\n\t";
    }
}
function nc_sample_register_option()
{
    register_setting("nc_sample_license", "nc_sample_license_key", "nc_sanitize_license");
}
function nc_sanitize_license($new)
{
    $old = get_option("nc_sample_license_key");
    if($old && $old !== $new) {
        delete_option("nc_sample_license_status");
    }
    return sanitize_text_field($new);
}
function nc_sample_activate_license()
{
    if(!isset($_POST["nc_license_activate"])) {
        return NULL;
    }
    if(!check_admin_referer("nc_sample_nonce", "nc_sample_nonce")) {
        return NULL;
    }
    $license = !empty($_POST["nc_sample_license_key"]) ? sanitize_text_field($_POST["nc_sample_license_key"]) : "";
    if(!$license) {
        $license = trim(get_option("nc_sample_license_key"));
    }
    if(!$license) {
        return NULL;
    }
    $api_params = ["edd_action" => "activate_license", "license" => $license, "item_id" => NC_ID, "url" => home_url()];
    $response = wp_remote_post(NC_STORE_URL, ["timeout" => 15, "sslverify" => false, "body" => $api_params]);
    if(is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
        if(is_wp_error($response)) {
            $message = $response->get_error_message();
        } else {
            $message = __("Se ha producido un error. Prueba de nuevo.", "nichecreator");
        }
    } else {
        $license_data = json_decode(wp_remote_retrieve_body($response));
        if(false === $license_data->success) {
            switch ($license_data->error) {
                case "expired":
                    $message = sprintf(__("Your license key expired on %s.", "nichecreator"), date_i18n(get_option("date_format"), strtotime($license_data->expires, current_time("timestamp"))));
                    break;
                case "disabled":
                case "revoked":
                    $message = __("Tu licencia se ha deshabilitado.", "nichecreator");
                    break;
                case "missing":
                    $message = __("Licencia inválida.", "nichecreator");
                    break;
                case "invalid":
                case "site_inactive":
                    $message = __("Licencia no activa para esta URL", "nichecreator");
                    break;
                case "item_name_mismatch":
                    $message = sprintf(__("Esta licencia parece inválida para %s.", "nichecreator"), NC_ITEM);
                    break;
                case "no_activations_left":
                    $message = __("Has llegado al límite de activaciones para esta licencia.", "nichecreator");
                    break;
                default:
                    $message = __("Ha ocurrido un error. Prueba de nuevo.", "nichecreator");
            }
        }
    }
    if(!empty($message)) {
        $redirect = add_query_arg(["page" => "nichecreator_license", "sl_activation" => "false", "message" => rawurlencode($message)], admin_url("admin.php"));
        wp_safe_redirect($redirect);
        exit;
    }
    if("valid" === $license_data->license) {
        update_option("nc_sample_license_key", $license);
    }
    update_option("nc_sample_license_status", $license_data->license);
    $redirect = add_query_arg(["page" => "nichecreator_license"], admin_url("admin.php"));
    wp_safe_redirect($redirect);
    exit;
}
function nc_sample_deactivate_license()
{
    if(isset($_POST["nc_license_deactivate"])) {
        if(!check_admin_referer("nc_sample_nonce", "nc_sample_nonce")) {
            return NULL;
        }
        $license = trim(get_option("nc_sample_license_key"));
        $api_params = ["edd_action" => "deactivate_license", "license" => $license, "item_id" => NC_ID, "item_name" => rawurlencode(NC_ITEM), "url" => home_url(), "environment" => function_exists("wp_get_environment_type") ? wp_get_environment_type() : "production"];
        $response = wp_remote_post(NC_STORE_URL, ["timeout" => 15, "sslverify" => false, "body" => $api_params]);
        if(is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            if(is_wp_error($response)) {
                $message = $response->get_error_message();
            } else {
                $message = __("Ha ocurrido un error, prueba de nuevo.", "nichecreator");
            }
            $redirect = add_query_arg(["page" => NC_LICENSE_PAGE, "sl_activation" => "false", "message" => rawurlencode($message)], admin_url("admin.php"));
            wp_safe_redirect($redirect);
            exit;
        }
        $license_data = json_decode(wp_remote_retrieve_body($response));
        if("deactivated" === $license_data->license || "failed" === $license_data->license) {
            delete_option("nc_sample_license_status");
            delete_option("nc_sample_license_key");
            $message = __("Licencia correctamente desactivada", "nichecreator");
        } else {
            $message = __("Se ha producido un error, vuelve a intentarlo", "nichecreator");
        }
        $redirect = add_query_arg(["page" => NC_LICENSE_PAGE, "sl_activation" => "false", "message" => rawurlencode($message)], admin_url("admin.php"));
        wp_safe_redirect($redirect);
        exit;
    }
}

// MODIFICADO: Siempre devuelve true
function nc_sample_check_license()
{
    return true;
}

function nc_sample_check_sites()
{
    $license = trim(get_option("nc_sample_license_key"));
    $api_params = ["edd_action" => "check_license", "license" => $license, "item_id" => NC_ID, "item_name" => rawurlencode(NC_ITEM), "url" => home_url(), "environment" => function_exists("wp_get_environment_type") ? wp_get_environment_type() : "production"];
    $response = wp_remote_post(NC_STORE_URL, ["timeout" => 15, "sslverify" => false, "body" => $api_params]);
    if(is_wp_error($response)) {
        return 0;
    }
    $license_data = json_decode(wp_remote_retrieve_body($response));
    $resul = $license_data->license;
    $numero = $obj->license_limit ?? 0;
    if("valid" === $resul || "expired" === $resul) {
        return $numero;
    }
    return 0;
}

// MODIFICADO: Siempre devuelve true
function nc_kudeval()
{
    return true;
}

function nc_notices()
{
    if(isset($_GET["sl_activation"]) && !empty($_GET["message"])) {
        switch ($_GET["sl_activation"]) {
            case "false":
                $message = urldecode($_GET["message"]);
                echo "\t\t\t\t<div class=\"notice notice-error is-dismissible\">\n\t\t\t\t\t<p>";
                echo wp_kses_post($message);
                echo "</p>\n\t\t\t\t</div>\n\t\t\t\t";
                break;
            case "true":
        }
    }
}

?>