<?php
/**
 * Settings class file.
 *
 * @package WordPress Plugin Template/Settings
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * This class is used to add, edit, and display all services.
 */
class panelhelper_api_servers{
        public function save_meta_boxes() {
        }
    
        public function __construct() {
            
            add_action( 'save_post', array( $this, 'save_meta_boxes' ), 10, 1 );
    
        }
        
        //creates a table if it doesnt exist
        function panelhelper_create_custom_table() {
            $id =1;
            
            global $wpdb;
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}panelhelper_api_servers (
                ID int NOT NULL AUTO_INCREMENT,
                API_URL varchar(255) NOT NULL,
                API_KEY varchar(255) NOT NULL,
                BALANCE double,
                MAIN INT(1) DEFAULT 0,
                PRIMARY KEY (id),
                UNIQUE (API_KEY)
            ) $charset_collate;";
            require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
            dbDelta( $sql );
        }
    
      


    //displays the table page
    function panelhelper_api_server_table_page() {
        $tab_link = add_query_arg( 'tab', 'addserver' );
        global $wpdb;
        $rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}panelhelper_api_servers" );
        ?>
        <br><titletagph class="panelhelper-title">Add Servers</titletagph><br>

        <a href="<?php echo esc_url( $tab_link ); ?>" class="button-link-ph">Add Server</a>
           
        
    <table class="panelhelper-table">
        <tr>
            <th>API URL</th>
            <th>API Key</th>
            <th>Balance</th>
            <th>Actions</th>
        </tr>
        <?php foreach ($rows as $row) : 
                $api_key = $row->API_KEY;
                $api_url = $row->API_URL;
                
                            
?>
            
            <tr>
                
            <td><?php echo esc_html($row->API_URL); ?></td>
<td><?php echo esc_html($this->maskApiKey($row->API_KEY)); ?></td>

                <td>
    <?php 
    if (strpos($api_url, 'http') === 0) {
        $api = new panelhelper_api_adder(); // Replace YourAPI with the actual class name or API client
        $balance = $api->api_balance($api_key, $api_url); // Assuming order_id exists
        if (!empty($balance->balance)) {
            echo esc_html($balance->balance) . esc_html($balance->currency);
        }} else {
            echo "Connection error"; // or any other message you prefer for empty balances
        }
    ?>
</td>

                <td>
                <form class="" action="" method="post" autocomplete="off">
            </form>
		<form method="post">
			<input type="hidden" id="api_key" name="api_key" value="<?php echo esc_attr($row->API_KEY); ?>">
			<button type="submit" name="delete_button" class="button">Delete</button>
            <?php  wp_nonce_field( 'delete_button_nonce', 'delete_button' ); ?>
		</form>

                

                </td>
            </tr>
        <?php endforeach; ?>
    </table>
   
    
    <?php
if (isset($_POST['delete_button']) && wp_verify_nonce( sanitize_text_field( wp_unslash (   $_POST['delete_button'])), 'delete_button_nonce' ) ) {
    $api_key = sanitize_text_field($_POST['api_key']);
    $this->panelhelper_handle_server_deletion($api_key);

    // Reload the page after form submission
    exit;
} 
	}

    function maskApiKey($apiKey) {
        if(strlen($apiKey) >= 4){

            // Get the first 4 characters of the API Key
            $firstFour = substr($apiKey, 0, 4);
            // Calculate the length of the remaining characters
            $remainingLength = strlen($apiKey) - 4;
            // Create a string of asterisks with the same length as the remaining characters
            $masked = str_repeat('*', $remainingLength);
            // Concatenate the first 4 characters with the masked string
            return $firstFour . $masked;
        } else {
            return $apiKey; // Return the original key if it's 5 characters or less
        }
    }

	//triggered if the user wants to delete a server
    function panelhelper_handle_server_deletion($api_key) {
        global $wpdb;
    
        $api_key = sanitize_text_field($api_key);
    
        // Perform deletion

        $wpdb->query(
            $wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}panelhelper_api_servers WHERE
            (API_KEY)
            = ( %s)",
            $api_key
            )
            );
    
        // You can echo a message or do something else if needed
        echo "<script>window.location.href = '" . esc_url($tab_link) . "';</script>";
    
        // Always exit to avoid further execution
        exit();
    }

    //triggered if a user wants to add server
	function panelhelper_insert_values_into_custom_table($name, $api_key) {
		global $wpdb;
		
		// Table name
		$table_name = $wpdb->prefix . 'panelhelper_api_servers';
	
		// Insert data into the table

        $wpdb->query(
            $wpdb->prepare(
            "INSERT INTO {$wpdb->prefix}panelhelper_api_servers
            ( API_URL, API_KEY)
            VALUES ( %s, %s)",
            $name,
            $api_key
            )
            );
	}

    //server add form page
    function panelhelper_api_server_add() {
        $tab_link = add_query_arg( 'tab', 'Servers' );
        global $wpdb;
        $rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}panelhelper_api_servers" );
        ?>


        <a href="<?php echo esc_url( $tab_link ); ?>" class="button-link-ph">Back</a>
        
            <form class="" action="" method="post" autocomplete="off">
            </form>
		<form class="wrap-add" method="post">
        <h1>Add Server</h1><br>
            <div class="wrap-items">
			<label for="url">API URL</label> <br>
			<input type="text" id="url" name="url" required><br><br>
			<label for="api_key">API KEY</label><br>
			<input type="text" id="api_key" name="api_key" required><br><br>
			<button type="submit" class="button-submit">Submit</button>
            <?php  wp_nonce_field( 'button-submit_nonce', 'button-submit' ); ?>
    </div>
		</form>


        
        
    <?php
		if (isset($_POST['url']) && isset($_POST['api_key']) && wp_verify_nonce( sanitize_text_field( wp_unslash (  $_POST['button-submit'])), 'button-submit_nonce' ) ) {
			$name = sanitize_text_field($_POST['url']);
			$api_key = sanitize_text_field($_POST['api_key']);
			$this->panelhelper_insert_values_into_custom_table($name, $api_key);

            // Reload the page after form submission
            $redirect_url = add_query_arg( array(
                'page' => 'panelhelper_settings',
                'tab' => 'Servers'
            ), admin_url( 'admin.php' ) );
        
            wp_redirect($redirect_url);
            exit;
		}
	}

   




    

    
    }