<?php
/**
 * All the settings page related functions handle from this file
 */

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

/**
 * Handle Export / Import / Reset actions
 */
add_action('admin_init', function () {

    if (!current_user_can('manage_options')) {
        return;
    }

    // Export
    if (isset($_POST['sapmfly_export_settings'])) {

        $nonce = isset($_POST['sapmfly_export_nonce'])
            ? sanitize_text_field(wp_unslash($_POST['sapmfly_export_nonce']))
            : '';

        if (wp_verify_nonce($nonce, 'sapmfly_export_action')) {
            sapmfly_export_function();
            exit;
        }
    }

    // Import
    if (isset($_POST['sapmfly_import_settings'])) {

        $nonce = isset($_POST['sapmfly_import_nonce'])
            ? sanitize_text_field(wp_unslash($_POST['sapmfly_import_nonce']))
            : '';

        if (wp_verify_nonce($nonce, 'sapmfly_import_action')) {
            sapmfly_import_function();
        }
    }

    // Reset
    if (isset($_POST['sapmfly_reset_settings'])) {

        $nonce = isset($_POST['sapmfly_reset_nonce'])
            ? sanitize_text_field(wp_unslash($_POST['sapmfly_reset_nonce']))
            : '';

        if (wp_verify_nonce($nonce, 'sapmfly_reset_action')) {
            sapmfly_reset_all_settings();
        }
    }
});


/**
 * Export current settings
 */
function sapmfly_export_function()
{

    if (!current_user_can('manage_options')) {
        return;
    }

    if (ob_get_length()) {
        ob_clean();
    }

    global $wpdb;

    $options_to_export = [];

    $like = $wpdb->esc_like('sapmfly_') . '%';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $results = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s",
            $like
        )
    );

    if (!empty($results)) {
        foreach ($results as $row) {
            $options_to_export[$row->option_name] = maybe_unserialize($row->option_value);
        }
    }

    nocache_headers();

    header('Content-Type: application/json; charset=utf-8');
    header(
        'Content-Disposition: attachment; filename=minifly-backup-' .
        sanitize_file_name(gmdate('Y-m-d')) .
        '.json'
    );

    echo wp_json_encode($options_to_export, JSON_PRETTY_PRINT);

    exit;
}


/**
 * Import backup settings
 */
function sapmfly_import_function() {

    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    // Verify nonce again for PHPCS & security
    if (
        ! isset( $_POST['sapmfly_import_nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_POST['sapmfly_import_nonce'] ) ),
            'sapmfly_import_action'
        )
    ) {
        return;
    }

    if (
        ! isset( $_FILES['sapmfly_import_file'] ) ||
        empty( $_FILES['sapmfly_import_file']['tmp_name'] )
    ) {
        return;
    }

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $file = $_FILES['sapmfly_import_file'];

    $filename = sanitize_file_name( $file['name'] );

    // Validate extension
    if ( strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ) !== 'json' ) {

        echo '<div class="error notice"><p>' .
        esc_html__( 'Error: Please upload a valid .json file.', 'minifly' ) .
        '</p></div>';

        return;
    }

    $json = file_get_contents( $file['tmp_name'] );

    if ( ! $json ) {
        return;
    }

    $data = json_decode( $json, true );

    if ( ! is_array( $data ) ) {

        echo '<div class="error notice"><p>' .
        esc_html__( 'Invalid JSON file.', 'minifly' ) .
        '</p></div>';

        return;
    }

    foreach ( $data as $key => $value ) {

        if ( strpos( $key, 'sapmfly_' ) === 0 ) {

            update_option(
                sanitize_key( $key ),
                $value
            );
        }
    }

    echo '<div class="updated notice"><p>' .
    esc_html__( 'Settings successfully imported and applied.', 'minifly' ) .
    '</p></div>';
}

/**
 * Reset all plugin settings
 */
function sapmfly_reset_all_settings()
{

    if (!current_user_can('manage_options')) {
        return;
    }

    global $wpdb;

    $like = $wpdb->esc_like('sapmfly_') . '%';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            $like
        )
    );

    echo '<div class="updated notice"><p>' .
        esc_html__('All settings have been reset.', 'minifly') .
        '</p></div>';
}