<?php

namespace GriffinForms\Admin\Js\Local;

class CapabilityMatrix extends \GriffinForms\Admin\Js\Local\Settings
{
    public function getOptionsDataJs(): string
    {
        $js = 'function getOptionsData() {' . PHP_EOL .
              '    getApiFeatureEnabledOption();' . PHP_EOL .
              '    getApiKillSwitchOption();' . PHP_EOL .
              '    getApiWebhookSubmissionCreatedEnabledOption();' . PHP_EOL .
              '    getApiWebhookSubmissionCreatedUrlOption();' . PHP_EOL .
              '    getApiWebhookSubmissionCreatedSecretOption();' . PHP_EOL .
              '    getApiWebhookSubmissionCreatedTimeoutOption();' . PHP_EOL .
              '    getApiRoleCapabilityMapOption();' . PHP_EOL .
              '    getApiUserCapabilityOverridesOption();' . PHP_EOL .
              '}' . PHP_EOL;

        $js .= $this->getApiFeatureEnabledOptionJs();
        $js .= $this->getApiKillSwitchOptionJs();
        $js .= $this->getApiWebhookSubmissionCreatedEnabledOptionJs();
        $js .= $this->getApiWebhookSubmissionCreatedUrlOptionJs();
        $js .= $this->getApiWebhookSubmissionCreatedSecretOptionJs();
        $js .= $this->getApiWebhookSubmissionCreatedTimeoutOptionJs();
        $js .= $this->getApiRoleCapabilityMapOptionJs();
        $js .= $this->getApiUserCapabilityOverridesOptionJs();
        $js .= $this->getDeviceRegistryAdminJs();

        return $js;
    }

    protected function getApiFeatureEnabledOptionJs(): string
    {
        return 'function getApiFeatureEnabledOption() {' . PHP_EOL .
               '    optionsData["api_feature_enabled"] = jQuery("#griffinforms-settings-capabilitymatrix-apifeatureenabled").prop("checked");' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getApiKillSwitchOptionJs(): string
    {
        return 'function getApiKillSwitchOption() {' . PHP_EOL .
               '    optionsData["api_kill_switch"] = jQuery("#griffinforms-settings-capabilitymatrix-apikillswitch").prop("checked");' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getApiWebhookSubmissionCreatedEnabledOptionJs(): string
    {
        return 'function getApiWebhookSubmissionCreatedEnabledOption() {' . PHP_EOL .
               '    optionsData["api_webhook_submission_created_enabled"] = jQuery("#griffinforms-settings-capabilitymatrix-apiwebhooksubmissioncreatedenabled").prop("checked");' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getApiWebhookSubmissionCreatedUrlOptionJs(): string
    {
        return 'function getApiWebhookSubmissionCreatedUrlOption() {' . PHP_EOL .
               '    optionsData["api_webhook_submission_created_url"] = jQuery("#griffinforms-settings-capabilitymatrix-apiwebhooksubmissioncreatedurl").val();' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getApiWebhookSubmissionCreatedSecretOptionJs(): string
    {
        return 'function getApiWebhookSubmissionCreatedSecretOption() {' . PHP_EOL .
               '    optionsData["api_webhook_submission_created_secret"] = jQuery("#griffinforms-settings-capabilitymatrix-apiwebhooksubmissioncreatedsecret").val();' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getApiWebhookSubmissionCreatedTimeoutOptionJs(): string
    {
        return 'function getApiWebhookSubmissionCreatedTimeoutOption() {' . PHP_EOL .
               '    optionsData["api_webhook_submission_created_timeout"] = jQuery("#griffinforms-settings-capabilitymatrix-apiwebhooksubmissioncreatedtimeout").val();' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getApiRoleCapabilityMapOptionJs(): string
    {
        return 'function getApiRoleCapabilityMapOption() {' . PHP_EOL .
               '    var matrix = {};' . PHP_EOL .
               '    jQuery("[data-gf-role-cap]").each(function(){' . PHP_EOL .
               '        var role = jQuery(this).data("role");' . PHP_EOL .
               '        var cap = jQuery(this).data("cap");' . PHP_EOL .
               '        if (!role || !cap) { return; }' . PHP_EOL .
               '        if (!matrix[role]) { matrix[role] = {}; }' . PHP_EOL .
               '        matrix[role][cap] = jQuery(this).prop("checked");' . PHP_EOL .
               '    });' . PHP_EOL .
               '    optionsData["api_role_capability_map"] = matrix;' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getApiUserCapabilityOverridesOptionJs(): string
    {
        return 'function getApiUserCapabilityOverridesOption() {' . PHP_EOL .
               '    var raw = jQuery("#griffinforms-settings-capabilitymatrix-apiusercapabilityoverrides").val();' . PHP_EOL .
               '    raw = raw ? raw.trim() : "";' . PHP_EOL .
               '    if (raw === "") {' . PHP_EOL .
               '        optionsData["api_user_capability_overrides"] = {};' . PHP_EOL .
               '        return;' . PHP_EOL .
               '    }' . PHP_EOL .
               '    try {' . PHP_EOL .
               '        var parsed = JSON.parse(raw);' . PHP_EOL .
               '        optionsData["api_user_capability_overrides"] = parsed;' . PHP_EOL .
               '    } catch (e) {' . PHP_EOL .
               '        optionsErrors["api_user_capability_overrides"] = "' . esc_js($this->lang->getText('api_user_capability_overrides_invalid_json')) . '";' . PHP_EOL .
               '    }' . PHP_EOL .
               '}' . PHP_EOL;
    }

    protected function getDeviceRegistryAdminJs(): string
    {
        return 'function gfDeviceRegistryNonce() {' . PHP_EOL .
               '    return jQuery("#gf-device-registry-admin-nonce").val() || "";' . PHP_EOL .
               '}' . PHP_EOL .
               PHP_EOL .
               'function gfDeviceRegistryRequest(payload, $button) {' . PHP_EOL .
               '    if ($button && $button.length) { $button.prop("disabled", true); }' . PHP_EOL .
               '    $.post(ajaxurl, {' . PHP_EOL .
               '        action: "griffinformsManageDeviceRegistry",' . PHP_EOL .
               '        nonce: gfDeviceRegistryNonce(),' . PHP_EOL .
               '        user_id: payload.user_id,' . PHP_EOL .
               '        device_id: payload.device_id || "",' . PHP_EOL .
               '        device_ids: JSON.stringify(payload.device_ids || []),' . PHP_EOL .
               '        remove_all: payload.remove_all ? 1 : 0' . PHP_EOL .
               '    }, function(response) {' . PHP_EOL .
               '        try {' . PHP_EOL .
               '            if (typeof response === "string") {' . PHP_EOL .
               '                response = JSON.parse(response);' . PHP_EOL .
               '            }' . PHP_EOL .
               '        } catch (e) {' . PHP_EOL .
               '            alert("Failed to parse device-management response.");' . PHP_EOL .
               '            if ($button && $button.length) { $button.prop("disabled", false); }' . PHP_EOL .
               '            return;' . PHP_EOL .
               '        }' . PHP_EOL .
               '        if (!response || !response.success) {' . PHP_EOL .
               '            alert((response && response.msg) ? response.msg : "Unable to remove device(s).");' . PHP_EOL .
               '            if ($button && $button.length) { $button.prop("disabled", false); }' . PHP_EOL .
               '            return;' . PHP_EOL .
               '        }' . PHP_EOL .
               '        window.location.reload();' . PHP_EOL .
               '    });' . PHP_EOL .
               '}' . PHP_EOL .
               PHP_EOL .
               'jQuery(document).on("click", ".gf-device-remove-btn", function() {' . PHP_EOL .
               '    var $btn = jQuery(this);' . PHP_EOL .
               '    var userId = parseInt($btn.data("user-id"), 10) || 0;' . PHP_EOL .
               '    var deviceId = ($btn.data("device-id") || "").toString();' . PHP_EOL .
               '    if (!userId || !deviceId) { return; }' . PHP_EOL .
               '    if (!window.confirm("Remove this device from registry?")) { return; }' . PHP_EOL .
               '    gfDeviceRegistryRequest({ user_id: userId, device_id: deviceId, remove_all: false }, $btn);' . PHP_EOL .
               '});' . PHP_EOL .
               PHP_EOL .
               'jQuery(document).on("change", ".gf-device-select-all", function() {' . PHP_EOL .
               '    var userId = parseInt(jQuery(this).data("user-id"), 10) || 0;' . PHP_EOL .
               '    if (!userId) { return; }' . PHP_EOL .
               '    var checked = jQuery(this).prop("checked");' . PHP_EOL .
               '    jQuery(".gf-device-select[data-user-id=\'" + userId + "\']").prop("checked", checked);' . PHP_EOL .
               '});' . PHP_EOL .
               PHP_EOL .
               'jQuery(document).on("click", ".gf-device-remove-selected-btn", function() {' . PHP_EOL .
               '    var $btn = jQuery(this);' . PHP_EOL .
               '    var userId = parseInt($btn.data("user-id"), 10) || 0;' . PHP_EOL .
               '    if (!userId) { return; }' . PHP_EOL .
               '    var deviceIds = [];' . PHP_EOL .
               '    jQuery(".gf-device-select[data-user-id=\'" + userId + "\']:checked").each(function() {' . PHP_EOL .
               '        deviceIds.push((jQuery(this).data("device-id") || "").toString());' . PHP_EOL .
               '    });' . PHP_EOL .
               '    if (deviceIds.length < 1) { alert("Select at least one device."); return; }' . PHP_EOL .
               '    if (!window.confirm("Remove selected devices?")) { return; }' . PHP_EOL .
               '    gfDeviceRegistryRequest({ user_id: userId, device_ids: deviceIds, remove_all: false }, $btn);' . PHP_EOL .
               '});' . PHP_EOL .
               PHP_EOL .
               'jQuery(document).on("click", ".gf-device-remove-all-btn", function() {' . PHP_EOL .
               '    var $btn = jQuery(this);' . PHP_EOL .
               '    var userId = parseInt($btn.data("user-id"), 10) || 0;' . PHP_EOL .
               '    if (!userId) { return; }' . PHP_EOL .
               '    if (!window.confirm("Remove all devices for this user?")) { return; }' . PHP_EOL .
               '    gfDeviceRegistryRequest({ user_id: userId, remove_all: true }, $btn);' . PHP_EOL .
               '});' . PHP_EOL;
    }
}
