<?php

/*
 * Utilities class for Google Sheet Connector
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 *  Utilities class - singleton class
 *
 * @since 1.0.0
 */

class GSHFJF_JetForm_Connector_Utility
{
    /**
     * Private constructor to prevent direct instantiation of the class.
     *
     * Ensures the class follows the singleton pattern or controlled instantiation.
     *
     * @access private
     * @since 1.0.0 Initial version
     */

    private function __construct()
    {
        // Do Nothing
    }

    /**
     * Add Sub Menu in Jet Forms
     *
     * @return singleton instance of GSHFJF_JetForm_Connector_Utility
     */

    public static function instance()
    {
        static $instance = null;
        if (is_null($instance)) {
            $instance = new GSHFJF_JetForm_Connector_Utility();
        }
        return $instance;
    }

    /**
     * Prints message (string or array) in the debug.log file
     *
     * @param mixed $message
     */

    public function logger($message)
    {
        if (defined('WP_DEBUG') && WP_DEBUG === true) {
            if (is_array($message) || is_object($message)) {
                GSHFJF_JetForm_Connector_Utility::gshfjf_debug_log($message->getMessage());
            } else {
                GSHFJF_JetForm_Connector_Utility::gshfjf_debug_log($message->getMessage());
            }
        }
    }

    /**
     * Display error or success message in the admin section
     *
     * @param array $data containing type and message
     * @return string with html containing the error message
     *
     * @since 1.0.0 initial version
     */

    public function admin_notice($data = array())
    {
        // extract message and type from the $data array
        $message = isset($data['message']) ? $data['message'] : '';
        $message_type = isset($data['type']) ? $data['type'] : '';
        switch ($message_type) {
            case 'error':
                $admin_notice = '<div id="message" class="error notice is-dismissible">';
                break;
            case 'update':
                $admin_notice = '<div id="message" class="updated notice is-dismissible">';
                break;
            case 'update-nag':
                $admin_notice = '<div id="message" class="update-nag">';
                break;
            case 'auth-expired-notice':
                $admin_notice = '<div id="message" class="error notice gshfjf-auth-expired-adds is-dismissible">';
                break;
            case 'upgrade':
                $admin_notice = '<div id="message" class="error notice gsc-upgrade is-dismissible">';
                break;
            default:
                $message = __('There\'s something wrong with your code...', 'gsheetconnector-for-jetform');
                $admin_notice = "<div id=\"message\" class=\"error\">\n";
                break;
        }
        $admin_notice .= "    <p>" . esc_html($message, 'gsheetconnector-for-jetform') . "</p>\n";
        $admin_notice .= "</div>\n";
        return $admin_notice;
    }

    /**
     * Get the current logged-in user's role.
     *
     * - Iterates through all available roles.
     * - Returns the first role that the current user has capability for.
     *
     * @access public
     * @return string|null Role slug of the current user or null if none found.
     * @since 1.0.0 Initial version
     */

    public function get_current_user_role()
    {
        global $wp_roles;
        foreach ($wp_roles->role_names as $role => $name):
            if (current_user_can($role)) {
                return $role;
            }
        endforeach;
    }

    /**
     * Save API credentials from remote server.
     *
     * - Creates a secure nonce and prepares API request params.
     * - Makes a GET request to remote API endpoint.
     * - On success, decodes the response and saves credentials to DB.
     * - Supports both single site and multisite WordPress.
     *
     * @access public
     * @since 1.0.0 Initial version
     */

    public function save_api_credentials()
    {
        // Create a nonce
        $nonce = wp_create_nonce('gshfjf_jetform_free_api_creds');

        // Prepare parameters for the API call
        $params = array(
            'action' => 'get_data',
            'nonce' => $nonce,
            'plugin' => 'CF7GSC',
            'method' => 'get',
        );

        // Add nonce and any other security parameters to the API request
        $api_url = add_query_arg($params, GSHFJF_JETFORM_CONNECTOR_API_URL);

        // Make the API call using wp_remote_get
        $response = wp_remote_get($api_url);

        // Check for errors
        if (is_wp_error($response)) {
            // Handle error
            self::gshfjf_debug_log(__METHOD__ . ' Error: ' . $response->get_error_message());
        } else {
            // API call was successful, process the data
            $response = wp_remote_retrieve_body($response);


            $decoded_response = json_decode($response);

            if (isset($decoded_response->api_creds) && (!empty($decoded_response->api_creds))) {

                $api_creds = wp_parse_args($decoded_response->api_creds);
                if (is_multisite()) {
                    // If it's a multisite, update the site option (network-wide)
                    update_site_option('gshfjf_jetform_free_api_creds', $api_creds);
                } else {
                    // If it's not a multisite, update the regular option
                    update_option('gshfjf_jetform_free_api_creds', $api_creds);
                }
            }
        }
    }

    /**
     * Write debug logs for JetForm Google Sheet Connector.
     *
     * - Initializes WP Filesystem if not already.
     * - Creates `logs` directory if missing.
     * - Deletes default log file (`log.txt`) if it exists.
     * - Appends error to existing unique log file, or creates a new one.
     * - Supports logging arrays and plain strings.
     *
     * @param mixed $error Error data to log (string or array).
     *
     * @access public
     * @since 1.0.0 Initial version
     */

    public static function gshfjf_debug_log($error)
    {
        if (class_exists('GSHFJF_JetForm_Error_Logs')) {
            GSHFJF_JetForm_Error_Logs::gshfjf_log_from_debug($error);
        }
    }

    /**
     * Get all editable system roles.
     *
     * - Returns an array of role slugs and their display names.
     *
     * @return array List of editable roles
     *
     * @access public
     * @since 1.0.0 Initial version
     */

    public function get_system_roles()
    {
        $participating_roles = array();
        $editable_roles = get_editable_roles();
        foreach ($editable_roles as $role => $details) {
            $participating_roles[$role] = $details['name'];
        }
        return $participating_roles;
    }

    /**
     * Render a list of role-based checkboxes for access control settings.
     *
     * - Administrator role is shown as always checked and disabled.
     * - Other roles are listed with checkboxes and pre-selected if in $selected_roles.
     *
     * @param string $setting_name   Name attribute for checkboxes.
     * @param array  $selected_roles Array of selected role slugs.
     *
     * @access public
     * @since 1.0.0 Initial version
     */

    public function gshfjf_jetform_checkbox_roles_multi($setting_name, $selected_roles)
    {
        $selected_row = '';
        $checked = '';
        $roles = array();
        $system_roles = $this->get_system_roles();
        if (!empty($selected_roles)) {
            foreach ($selected_roles as $role => $display_name) {
                array_push($roles, $role);
            }
        }

        $selected_row = '';
        $selected_row  .= "<div class='gsc-access-wrapper mt-30'>";
        $selected_row .= "<div class='gsc-access-box bg-white pt-15 pb-15 pl-15 pr-15'> 
        <div class='para-heading fw-600 mb-20'>" . esc_html__('Allowed Roles', 'gsheetconnector-for-jetform') . "</div>";


        $selected_row .= "<div class='gsc-role-card mb-10'>
        <div class='custom-check d-flex justify-between alien-center'>
        <label class='role-label gsc-switch'> ";
        $selected_row .= __("Administrator", 'gsheetconnector-for-jetform');
        $selected_row .= "</label>";
        $selected_row .= "<input type='checkbox' class='check-toggle' disabled='disabled' checked='checked'/><label class='button-toggle'></label>";
        $selected_row .= "</div>";
        $selected_row .= "</div>";
        foreach ($system_roles as $role => $display_name) {
            if ($role === "administrator") {
                continue;
            }
            if (!empty($roles) && is_array($roles) && in_array(esc_attr($role), $roles)) { // preselect specified role
                $checked = " checked='checked'";
            } else {
                $checked = '';
            }

            $selected_row .= "<div class='gsc-role-card mb-10'><div class='custom-check d-flex justify-between alien-center'><label class='role-label gsc-switch'>";
            $selected_row .= esc_html($display_name, 'gsheetconnector-for-jetform');
            $selected_row .= "</label><input type='checkbox' class=''check-toggle'
            name='" . esc_attr($setting_name) . "[]' value='" . esc_attr($role) . "'" . $checked . "/>";
            $selected_row .= "<label class='button-toggle'></label>";
            $selected_row .= "</div></div>";
        }



        echo wp_kses($selected_row, array(
            'div' => array('class' => array()),
            'label' => array('class' => array(), 'for' => array()),
            'input' => array(
                'type' => array(),
                'class' => array(),
                'name' => array(),
                'value' => array(),
                'checked' => array(),
                'disabled' => array()
            ),
            'span' => array('class' => array())
        ));
    }
}
