<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
function freshenup_get_or_generate_site_key() {
    $site_key = get_option( 'freshenup_site_key' );
    if ( !$site_key ) {
        $site_key = wp_generate_password( 64, true, true );
        update_option( 'freshenup_site_key', $site_key );
    }
    return $site_key;
}

function freshenup_encrypt_for_transit(  $data  ) {
    $site_key = freshenup_get_or_generate_site_key();
    $method = "AES-256-CBC";
    $iv = openssl_random_pseudo_bytes( openssl_cipher_iv_length( $method ) );
    $encrypted = openssl_encrypt(
        $data,
        $method,
        $site_key,
        0,
        $iv
    );
    return base64_encode( $encrypted . '::' . $iv );
}

function freshenup_encrypt(  $data  ) {
    $key = wp_salt( 'auth' );
    $method = "AES-256-CBC";
    $iv = openssl_random_pseudo_bytes( openssl_cipher_iv_length( $method ) );
    $encrypted = openssl_encrypt(
        $data,
        $method,
        $key,
        0,
        $iv
    );
    if ( $encrypted === false ) {
        return false;
    }
    return base64_encode( $encrypted . '::' . $iv );
}

function freshenup_decrypt(  $data  ) {
    $key = wp_salt( 'auth' );
    $method = "AES-256-CBC";
    list( $encrypted_data, $iv ) = explode( '::', base64_decode( $data ), 2 );
    $decrypted = openssl_decrypt(
        $encrypted_data,
        $method,
        $key,
        0,
        $iv
    );
    if ( $decrypted === false ) {
        return false;
    }
    return $decrypted;
}

function freshenup_get_api_key() {
    $encrypted_key = get_option( 'freshenup_openai_api_key' );
    if ( empty( $encrypted_key ) ) {
        return false;
    }
    $decrypted_key = freshenup_decrypt( $encrypted_key );
    if ( $decrypted_key === false ) {
        return false;
    }
    return $decrypted_key;
}

function freshenup_validate_openai_api_key(  $api_key  ) {
    $result = array(
        'is_valid'      => false,
        'response_code' => null,
        'body'          => '',
        'error'         => '',
    );
    $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
        ),
        'body'    => wp_json_encode( array(
            'model'      => 'gpt-3.5-turbo',
            'messages'   => array(array(
                'role'    => 'user',
                'content' => 'test',
            )),
            'max_tokens' => 1,
        ) ),
        'timeout' => 20,
    ) );
    if ( is_wp_error( $response ) ) {
        $result['error'] = $response->get_error_message();
        return $result;
    }
    $result['response_code'] = wp_remote_retrieve_response_code( $response );
    $result['body'] = wp_remote_retrieve_body( $response );
    $data = json_decode( $result['body'], true );
    $result['is_valid'] = $result['response_code'] === 200;
    if ( !$result['is_valid'] && isset( $data['error'] ) ) {
        $result['error'] = ( isset( $data['error']['message'] ) ? $data['error']['message'] : 'Unknown error occurred' );
    }
    return $result;
}

// Usage in sanitization function
function freshenup_sanitize_openai_api_key(  $input  ) {
    if ( empty( $input ) ) {
        return '';
    }
    $sanitized_input = sanitize_text_field( $input );
    $old_encrypted_key = get_option( 'freshenup_openai_api_key' );
    $old_key = ( $old_encrypted_key ? freshenup_decrypt( $old_encrypted_key ) : '' );
    $masked_old_key = freshenup_mask_api_key( $old_key );
    // Check if the input matches the masked version of the old key
    if ( $sanitized_input === $masked_old_key ) {
        return $old_encrypted_key;
    }
    // If the input is different from both the old key and its masked version, encrypt it
    if ( $sanitized_input !== $old_key ) {
        $encrypted_key = freshenup_encrypt( $sanitized_input );
        if ( $encrypted_key === false ) {
            add_settings_error(
                'freshenup_options',
                'encryption_failed',
                __( 'Failed to securely store the API key. Please try again.', 'freshenup' ),
                'error'
            );
            return $old_encrypted_key;
        }
        return $encrypted_key;
    }
    return $old_encrypted_key;
}

// Make sure you have this function defined
function freshenup_mask_api_key(  $api_key  ) {
    if ( strlen( $api_key ) > 8 ) {
        return substr( $api_key, 0, 4 ) . str_repeat( '*', strlen( $api_key ) - 8 ) . substr( $api_key, -4 );
    }
    return str_repeat( '*', strlen( $api_key ) );
}

// Function to display the masked API key in the admin
function freshenup_display_api_key_field() {
    $api_key = freshenup_get_api_key();
    $masked_key = ( $api_key ? freshenup_mask_api_key( $api_key ) : '' );
    ?>
    <input type="text" id="freshenup_openai_api_key" name="freshenup_openai_api_key" value="<?php 
    echo esc_attr( $masked_key );
    ?>" class="regular-text" />
    <?php 
}

function freshenup_display_admin_notice(  $id, $message, $type = 'warning'  ) {
    if ( get_user_meta( get_current_user_id(), "freshenup_{$id}_notice_dismissed", true ) ) {
        return;
    }
    $nonce = wp_create_nonce( 'freshenup_nonce_ajax' );
    ?>
    <div class="notice notice-<?php 
    echo esc_attr( $type );
    ?> is-dismissible" id="freshenup-<?php 
    echo esc_attr( $id );
    ?>-notice" data-notice-id="<?php 
    echo esc_attr( $id );
    ?>" data-nonce="<?php 
    echo esc_attr( $nonce );
    ?>">
        <p><?php 
    echo wp_kses( $message, array(
        'a' => array(
            'href' => array(),
        ),
    ) );
    ?></p>
    </div>
    <?php 
}

function freshenup_api_key_notice() {
    if ( !freshenup_get_api_key() ) {
        $setting_page_url = admin_url( 'admin.php?page=freshenup_settings' );
        $notice = sprintf( 
            /* translators: %1$s: opening link tag, %2$s: closing link tag */
            esc_html__( 'Please %1$sSet your AI provider API key%2$s to start using Freshenup.', 'freshenup' ),
            '<a href="' . esc_url( $setting_page_url ) . '">',
            '</a>'
         );
        freshenup_display_admin_notice( 'api_key', $notice );
    }
}

function freshenup_enqueue_admin_notice_scripts() {
    wp_enqueue_script(
        'freshenup-admin-notice',
        plugin_dir_url( __FILE__ ) . 'js/admin-notice.js',
        array('jquery'),
        FRESHENUP_VERSION,
        true
    );
    wp_localize_script( 'freshenup-admin-notice', 'freshenupAjax', array(
        'ajaxurl'               => admin_url( 'admin-ajax.php' ),
        'nonce'                 => wp_create_nonce( 'freshenup_nonce_ajax' ),
        'dismiss_notice_action' => 'freshenup_dismiss_notice',
        'check_api_key_nonce'   => wp_create_nonce( 'freshenup_check_api_key' ),
        'checking_text'         => __( 'Checking...', 'freshenup' ),
        'check_key_text'        => __( 'Check API Key', 'freshenup' ),
        'invalid_key_text'      => __( 'API key is invalid. Error:', 'freshenup' ),
        'ajax_error_text'       => __( 'Request failed. Please try again.', 'freshenup' ),
    ) );
}

function freshenup_dismiss_notice() {
    if ( !current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Unauthorized user', 'freshenup' ) );
    }
    check_ajax_referer( 'freshenup_nonce_ajax', 'nonce' );
    if ( !isset( $_POST['notice_id'] ) ) {
        wp_send_json_error( 'Missing notice_id' );
    }
    $notice_id = sanitize_text_field( wp_unslash( $_POST['notice_id'] ) );
    $user_id = get_current_user_id();
    update_user_meta( $user_id, "freshenup_{$notice_id}_notice_dismissed", true );
    wp_send_json_success();
}

function freshenup_reset_notices() {
    delete_metadata(
        'user',
        0,
        'freshenup_api_key_notice_dismissed',
        '',
        true
    );
}

// Hooks
add_action( 'admin_notices', 'freshenup_api_key_notice' );
add_action( 'admin_enqueue_scripts', 'freshenup_enqueue_admin_notice_scripts' );
add_action( 'wp_ajax_freshenup_dismiss_notice', 'freshenup_dismiss_notice' );