<?php
/**
 * This file is responsible to manage error logs.
 *
 * @package Webdigit
 */

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

/**
 * Class to log errors.
 */
require_once WD_CHATBOT_PATH . 'includes/logs/class-wdgpt-error-logs-table.php';

add_action( 'admin_init', 'wdgpt_handle_export_error_logs_csv' );

/**
 * Handle CSV export of error logs when requested.
 *
 * @return void
 */
function wdgpt_handle_export_error_logs_csv() {
	if ( ! isset( $_GET['page'] ) || 'wdgpt_error_logs' !== sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
		return;
	}
	if ( ! isset( $_GET['export_csv'] ) || '1' !== sanitize_text_field( wp_unslash( $_GET['export_csv'] ) ) ) {
		return;
	}
	if ( ! wp_verify_nonce( isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '', 'wdgpt_export_error_logs_csv' ) ) {
		return;
	}
	if ( ! current_user_can( 'edit_others_posts' ) ) {
		return;
	}

	global $wpdb;
	$table_name = $wpdb->prefix . 'wd_error_logs';
	// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Table name is from wpdb prefix, not user input.
	$logs = $wpdb->get_results( "SELECT id, question, error_type, error_code, error, created_at FROM {$table_name} ORDER BY created_at DESC", ARRAY_A );

	$filename = 'wdgpt-error-logs-' . gmdate( 'Y-m-d-H-i-s' ) . '.csv';
	header( 'Content-Type: text/csv; charset=utf-8' );
	header( 'Content-Disposition: attachment; filename=' . $filename );
	header( 'Pragma: no-cache' );
	header( 'Expires: 0' );

	$output = fopen( 'php://output', 'w' );
	if ( false === $output ) {
		return;
	}

	// BOM for Excel UTF-8 compatibility.
	fprintf( $output, chr(0xEF) . chr(0xBB) . chr(0xBF) );

	$columns = array(
		'id'         => __( 'ID', 'webdigit-chatbot' ),
		'question'   => __( 'Question', 'webdigit-chatbot' ),
		'error_type' => __( 'Error Type', 'webdigit-chatbot' ),
		'error_code' => __( 'Error Code', 'webdigit-chatbot' ),
		'error'      => __( 'Error', 'webdigit-chatbot' ),
		'created_at' => __( 'Created At', 'webdigit-chatbot' ),
	);
	fputcsv( $output, array_values( $columns ), ';' );

	foreach ( $logs as $log ) {
		fputcsv( $output, array_values( $log ), ';' );
	}

	fclose( $output );
	exit;
}

/**
 * Function to log errors.
 */
function wdgpt_error_logs() {
	global $wpdb;
	$table = new WDGPT_Error_Logs_Table();
	?>
	<div class="wrap">
		<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
		<h2><?php esc_html_e( 'Error Logs', 'webdigit-chatbot' ); ?>
		</h2>
		<?php
		if ( isset( $_REQUEST['wdgpt_error_logs_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['wdgpt_error_logs_nonce'] ) ), 'wdgpt_error_logs' ) ) {
			if ( isset( $_GET['deleted'] ) ) {
				if ( 0 === $_GET['deleted'] ) {
					new WDGPT_Admin_Notices( 2, __( 'Deleted all logs.', 'webdigit-chatbot' ) );
				} elseif ( 1 === $_GET['deleted'] ) {
					$months = isset( $_GET['months'] ) ? intval( $_GET['months'] ) : 0;
					/* translators: %d: number of months */
					new WDGPT_Admin_Notices( 2, sprintf( esc_html__( 'Deleted logs older than %d months.', 'webdigit-chatbot' ), $months ) );
				}
			}
		}
		$database_updater = new WDGPT_Database_Updater( wdgpt_chatbot()->get_version() );
		$updates          = $database_updater->check_for_updates();
		if ( empty( $updates ) ) {
			$table->prepare_items();
			$page = isset( $_REQUEST['page'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['page'] ) ) : '';

			?>
		<form method="post">
			<?php wp_nonce_field( 'wdgpt_error_logs', 'wdgpt_error_logs_nonce' ); ?>
			<input type="hidden" name="page" value="<?php echo esc_html( $page ); ?>" />
			<?php $table->display(); ?>
		</form>
	</div>
			<?php
		}
} ?>
