<?php

declare( strict_types=1 );

namespace StrykeWP\Modules\Backup;

/**
 * Renders the backup history as a paginated WP_List_Table.
 *
 * Migrated from STRYKE_Log_List_Table. Global constant STRYKE_LOG_TABLE
 * replaced by BackupSettings::get_table_name().
 *
 * @package StrykeWP\Modules\Backup
 */
class LogListTable extends \WP_List_Table {

	public function __construct() {
		parent::__construct(
			array(
				'singular' => 'backup_log',
				'plural'   => 'backup_logs',
				'ajax'     => false,
			)
		);
	}

	// -----------------------------------------------------------------------
	// Column Definitions
	// -----------------------------------------------------------------------

	public function get_columns(): array {
		return array(
			'timestamp' => esc_html__( 'Datum & Uhrzeit', 'stryke-wp' ),
			'filename'  => esc_html__( 'Dateiname', 'stryke-wp' ),
			'filesize'  => esc_html__( 'Größe', 'stryke-wp' ),
			'status'    => esc_html__( 'Status', 'stryke-wp' ),
			'actions'   => esc_html__( 'Aktionen', 'stryke-wp' ),
		);
	}

	// -----------------------------------------------------------------------
	// Column Rendering
	// -----------------------------------------------------------------------

	/**
	 * @param array<string, mixed> $item
	 */
	public function column_default( $item, $column_name ): string {
		return isset( $item[ $column_name ] ) ? esc_html( (string) $item[ $column_name ] ) : '';
	}

	/**
	 * @param array<string, mixed> $item
	 */
	public function column_timestamp( array $item ): string {
		$datetime = strtotime( $item['timestamp'] );
		if ( false === $datetime ) {
			return esc_html__( 'Ungültiges Datum', 'stryke-wp' );
		}
		return esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $datetime ) );
	}

	/**
	 * @param array<string, mixed> $item
	 */
	public function column_filesize( array $item ): string {
		$bytes = (int) $item['filesize'];
		if ( $bytes < 1024 ) {
			return $bytes . ' B';
		}
		$units = array( 'KB', 'MB', 'GB', 'TB' );
		$i     = (int) floor( log( $bytes, 1024 ) );
		return round( $bytes / ( 1024 ** $i ), 2 ) . ' ' . ( $units[ $i - 1 ] ?? 'B' );
	}

	/**
	 * @param array<string, mixed> $item
	 */
	public function column_status( array $item ): string {
		$status = strtoupper( (string) $item['status'] );

		$color = match ( $status ) {
			'SUCCESS' => '#189ba7',
			'FAILED'  => '#f44336',
			default   => '#9e9e9e',
		};

		return sprintf(
			'<span style="color:%s;font-weight:bold;">%s</span>',
			esc_attr( $color ),
			esc_html( $status )
		);
	}

	/**
	 * @param array<string, mixed> $item
	 */
	public function column_actions( array $item ): string {
		$actions = array();

		if ( 'Success' === $item['status'] && ! empty( $item['google_drive_file_id'] ) ) {
			$download_url = wp_nonce_url(
				admin_url( 'admin-post.php?action=stryke_download_backup&id=' . (int) $item['ID'] ),
				'stryke_download_backup'
			);
			$actions[]    = sprintf(
				'<a href="%s" style="color:#189ba7;">%s</a>',
				esc_url( $download_url ),
				esc_html__( 'Download', 'stryke-wp' )
			);
		}

		$actions[] = sprintf(
			'<a href="#" class="stryke-delete-log-link" data-id="%d" style="color:#f44336;">%s</a>',
			(int) $item['ID'],
			esc_html__( 'Löschen', 'stryke-wp' )
		);

		return implode( ' | ', $actions );
	}

	// -----------------------------------------------------------------------
	// Data Preparation
	// -----------------------------------------------------------------------

	public function prepare_items(): void {
		global $wpdb;

		$per_page     = 10;
		$current_page = $this->get_pagenum();
		$offset       = ( $current_page - 1 ) * $per_page;

		$table = BackupSettings::get_table_name();

		$data = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->prepare(
				"SELECT * FROM {$table} ORDER BY ID DESC LIMIT %d OFFSET %d", // phpcs:ignore WordPress.DB.PreparedSQL
				$per_page,
				$offset
			),
			ARRAY_A
		);

		$total_items = (int) $wpdb->get_var( "SELECT COUNT(ID) FROM {$table}" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL

		$this->_column_headers = array( $this->get_columns(), array(), array(), $this->get_primary_column_name() );

		$this->set_pagination_args(
			array(
				'total_items' => $total_items,
				'per_page'    => $per_page,
				'total_pages' => (int) ceil( $total_items / $per_page ),
			)
		);

		$this->items = $data ?? array();
	}

	protected function get_primary_column_name(): string {
		return 'timestamp';
	}
}
