<?php
/**
 * Export faktur do CSV i PDF
 *
 * Obsługuje pobieranie faktur w formatach CSV i PDF
 * z filtrowaniem i customizacją.
 *
 * @package KSEF\WordPress
 */

namespace KSEF\WordPress;

// phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.SlowDBQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Wlasne tabele gksef_*: wartosci przez $wpdb->prepare()/esc_like(), nazwy tabel z $wpdb->prefix, paginacja rzutowana (int); nonce weryfikowany w handlerze (check_ajax_referer/check_admin_referer).

/**
 * Invoice_Export — export do CSV/PDF
 *
 * Obsługuje:
 * - Export CSV (UTF-8 BOM dla Excel)
 * - Export PDF (via dompdf)
 * - Filtry (status, data, NIP)
 * - Summary i totals
 */
class Invoice_Export {

	/**
	 * Export do CSV
	 *
	 * ⚠️ SECURITY: Wymagana ważna licencja
	 *
	 * @param string $type Typ faktury (outgoing/incoming).
	 * @param array  $filters Filtry [status, from_date, to_date, nip].
	 * @return string|WP_Error CSV content lub błąd
	 */
	public static function export_csv( $type, $filters = [] ) {
		// ⚠️ SECURITY: Sprawdzenie licencji
		if ( ! self::verify_license() ) {
			return new \WP_Error( 'license_invalid', __( 'KSEF License is not valid.', 'prostafaktura-ksef' ) );
		}

		global $wpdb;

		// Pobierz faktury
		$invoices = self::get_filtered_invoices( $type, $filters );

		if ( empty( $invoices ) ) {
			return new \WP_Error( 'no_invoices', __( 'Brak faktur do wyeksportowania.', 'prostafaktura-ksef' ) );
		}

		// Zbuduj CSV
		$csv = self::build_csv( $type, $invoices );

		// Pobierz filename
		$filename = self::get_export_filename( $type, 'csv' );

		// Wyślij headers
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );

		// BOM dla UTF-8 (Excel compatibility)
		echo "\xEF\xBB\xBF"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		// Output CSV
		echo $csv; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		exit;
	}

	/**
	 * Export do PDF
	 *
	 * Generuje PDF z użyciem konwersji HTML → PDF.
	 * Jeśli dostępna jest biblioteka mPDF, używa jej.
	 * Inaczej używa CSS Print i wc_get_pdf_filename().
	 *
	 * ⚠️ SECURITY: Wymagana ważna licencja
	 *
	 * @param string $type Typ faktury (outgoing/incoming).
	 * @param array  $filters Filtry.
	 * @return string|WP_Error PDF content lub błąd
	 */
	public static function export_pdf( $type, $filters = [] ) {
		// ⚠️ SECURITY: Sprawdzenie licencji
		if ( ! self::verify_license() ) {
			return new \WP_Error( 'license_invalid', __( 'KSEF License is not valid.', 'prostafaktura-ksef' ) );
		}

		global $wpdb;

		// Pobierz faktury
		$invoices = self::get_filtered_invoices( $type, $filters );

		if ( empty( $invoices ) ) {
			return new \WP_Error( 'no_invoices', __( 'Brak faktur do wyeksportowania.', 'prostafaktura-ksef' ) );
		}

		// Zbuduj HTML dla PDF
		$html = self::build_pdf_html( $type, $invoices, $filters );
		$filename = self::get_export_filename( $type, 'pdf' );

		// Spróbuj użyć mPDF (jeśli dostępna)
		if ( self::has_mpdf() ) {
			$pdf_content = self::generate_pdf_with_mpdf( $html );
		} else {
			// Fallback: używamy wc_get_pdf (jeśli WooCommerce)
			// Albo generujemy print-friendly HTML
			$pdf_content = self::generate_pdf_with_woocommerce( $html, $filename );
		}

		// Wyślij headers
		header( 'Content-Type: application/pdf; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Length: ' . strlen( $pdf_content ) );
		header( 'Cache-Control: no-cache, no-store, must-revalidate' );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		// Output PDF
		echo $pdf_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		exit;
	}

	/**
	 * Sprawdź czy dostępna jest mPDF
	 *
	 * @return bool
	 */
	private static function has_mpdf() {
		return function_exists( '\Mpdf\Mpdf' );
	}

	/**
	 * Generuj PDF z mPDF
	 *
	 * @param string $html HTML content.
	 * @return string PDF binary content
	 */
	private static function generate_pdf_with_mpdf( $html ) {
		try {
			// phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
			$mpdf = new \Mpdf\Mpdf( [
				'mode'          => 'utf-8',
				'format'        => 'A4',
				'margin_left'   => 10,
				'margin_right'  => 10,
				'margin_top'    => 10,
				'margin_bottom' => 10,
			] );

			$mpdf->WriteHTML( $html );
			return $mpdf->Output( '', 'S' ); // Return as string
		} catch ( \Exception $e ) {
			ksef_efaktury_log( '[KSEF] mPDF error: ' . $e->getMessage() );
			return '';
		}
	}

	/**
	 * Generuj PDF z WooCommerce (fallback)
	 *
	 * @param string $html HTML content.
	 * @param string $filename Filename.
	 * @return string PDF binary content
	 */
	private static function generate_pdf_with_woocommerce( $html, $filename ) {
		// Fallback: zwróć HTML z instrukcją print
		// Użytkownik może wydrukować do PDF z przeglądarki
		$fallback_html = '<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>' . esc_attr( $filename ) . '</title>
	<style>
		body { font-family: Arial, sans-serif; }
		@media print {
			body { margin: 0; }
		}
	</style>
</head>
<body>
	' . $html . '
	<script>
		window.print();
	</script>
</body>
</html>';

		return $fallback_html;
	}

	/**
	 * Pobierz factury z filtrami
	 *
	 * @param string $type Typ (outgoing/incoming).
	 * @param array  $filters Filtry.
	 * @return array Lista faktur
	 */
	public static function get_filtered_invoices( $type, $filters = [] ) {
		global $wpdb;

		$table = 'outgoing' === $type ? 'gksef_outgoing_invoices' : 'gksef_incoming_invoices';

		// Build WHERE
		$where = [ '1=1' ];

		if ( ! empty( $filters['status'] ) ) {
			$status_col = 'outgoing' === $type ? 'status' : 'processing_status';
			$where[]    = $wpdb->prepare( "$status_col = %s", $filters['status'] );
		}

		if ( ! empty( $filters['nip'] ) ) {
			$where[] = $wpdb->prepare( "seller_nip = %s", $filters['nip'] );
		}

		if ( ! empty( $filters['from_date'] ) ) {
			$date_col = 'outgoing' === $type ? 'created_at' : 'issue_date';
			$where[]  = $wpdb->prepare( "$date_col >= %s", $filters['from_date'] . ' 00:00:00' );
		}

		if ( ! empty( $filters['to_date'] ) ) {
			$date_col = 'outgoing' === $type ? 'created_at' : 'issue_date';
			$where[]  = $wpdb->prepare( "$date_col <= %s", $filters['to_date'] . ' 23:59:59' );
		}

		$where_clause = implode( ' AND ', $where );

		// Query
		$date_col = 'outgoing' === $type ? 'created_at' : 'issue_date';
		$invoices = $wpdb->get_results(
			"SELECT * FROM {$wpdb->prefix}{$table}
			WHERE {$where_clause}
			ORDER BY {$date_col} DESC",
			ARRAY_A
		);

		return $invoices ?? [];
	}

	/**
	 * Zbuduj CSV content
	 *
	 * @param string $type Typ faktury.
	 * @param array  $invoices Lista faktur.
	 * @return string CSV content
	 */
	private static function build_csv( $type, $invoices ) {
		$headers = self::get_csv_headers( $type );

		// Create CSV
		$csv_lines = [];
		$csv_lines[] = implode( ',', $headers );

		// Rows
		foreach ( $invoices as $invoice ) {
			$row = [];

			foreach ( array_keys( $headers ) as $key ) {
				$value = $invoice[ $key ] ?? '';

				// Escape CSV
				if ( strpos( $value, ',' ) !== false || strpos( $value, '"' ) !== false || strpos( $value, "\n" ) !== false ) {
					$value = '"' . str_replace( '"', '""', $value ) . '"';
				}

				$row[] = $value;
			}

			$csv_lines[] = implode( ',', $row );
		}

		// Add summary
		$csv_lines[] = '';
		$csv_lines[] = 'Podsumowanie';
		$csv_lines[] = 'Razem faktur,' . count( $invoices );
		$csv_lines[] = 'Suma brutto,' . number_format( array_sum( array_column( $invoices, 'gross_amount' ) ), 2, '.', '' );

		return implode( "\n", $csv_lines );
	}

	/**
	 * Zbuduj HTML dla PDF
	 *
	 * @param string $type Typ faktury.
	 * @param array  $invoices Lista faktur.
	 * @param array  $filters Filtry użyte.
	 * @return string HTML
	 */
	private static function build_pdf_html( $type, $invoices, $filters ) {
		$blog_name = get_bloginfo( 'name' );
		$now       = date_i18n( 'Y-m-d H:i:s' );
		$title     = 'outgoing' === $type ? __( 'Faktury wysyłane', 'prostafaktura-ksef' ) : __( 'Faktury zakupowe', 'prostafaktura-ksef' );

		$html = '<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<style>
		body { font-family: Arial, sans-serif; margin: 20px; }
		.header { text-align: center; border-bottom: 2px solid #0073aa; padding-bottom: 20px; margin-bottom: 20px; }
		.header h1 { margin: 0; color: #0073aa; }
		.header p { margin: 5px 0; color: #666; }
		table { width: 100%; border-collapse: collapse; margin-top: 20px; }
		th { background: #0073aa; color: white; padding: 10px; text-align: left; }
		td { padding: 8px; border-bottom: 1px solid #ddd; }
		tr:nth-child(even) { background: #f9f9f9; }
		.summary { margin-top: 30px; border-top: 2px solid #0073aa; padding-top: 20px; }
		.summary-row { display: flex; justify-content: space-between; padding: 5px 0; }
		.footer { text-align: center; margin-top: 50px; color: #999; font-size: 12px; border-top: 1px solid #ddd; padding-top: 20px; }
	</style>
</head>
<body>
	<div class="header">
		<h1>' . esc_html( $title ) . '</h1>
		<p>' . esc_html( $blog_name ) . '</p>
		<p>' . esc_html__( 'Data raportu', 'prostafaktura-ksef' ) . ': ' . esc_html( $now ) . '</p>
	</div>

	<table>
		<thead>
			<tr>';

		// Headers
		$headers = self::get_csv_headers( $type );
		foreach ( $headers as $label ) {
			$html .= '<th>' . esc_html( $label ) . '</th>';
		}

		$html .= '</tr>
		</thead>
		<tbody>';

		// Rows
		foreach ( $invoices as $invoice ) {
			$html .= '<tr>';

			foreach ( array_keys( $headers ) as $key ) {
				$value = $invoice[ $key ] ?? '';
				$html .= '<td>' . esc_html( $value ) . '</td>';
			}

			$html .= '</tr>';
		}

		$html .= '</tbody>
	</table>

	<div class="summary">
		<div class="summary-row">
			<span>' . esc_html__( 'Razem faktur', 'prostafaktura-ksef' ) . ':</span>
			<strong>' . count( $invoices ) . '</strong>
		</div>
		<div class="summary-row">
			<span>' . esc_html__( 'Suma brutto', 'prostafaktura-ksef' ) . ':</span>
			<strong>' . esc_html( number_format_i18n( array_sum( array_column( $invoices, 'gross_amount' ) ), 2 ) ) . ' PLN</strong>
		</div>
	</div>

	<div class="footer">
		<p>' . esc_html( $blog_name ) . ' — KSEF WordPress Plugin</p>
		<p>' . esc_html__( 'Raport automatycznie wygenerowany', 'prostafaktura-ksef' ) . '</p>
	</div>
</body>
</html>';

		return $html;
	}

	/**
	 * Pobierz CSV headers dla type
	 *
	 * @param string $type Typ.
	 * @return array Headers [key => label]
	 */
	private static function get_csv_headers( $type ) {
		if ( 'outgoing' === $type ) {
			return [
				'invoice_number'        => __( 'Nr faktury', 'prostafaktura-ksef' ),
				'created_at'            => __( 'Data', 'prostafaktura-ksef' ),
				'seller_nip'            => __( 'NIP sprzedawcy', 'prostafaktura-ksef' ),
				'gross_amount'          => __( 'Kwota brutto', 'prostafaktura-ksef' ),
				'status'                => __( 'Status', 'prostafaktura-ksef' ),
				'ksef_reference_number' => __( 'KSeF reference', 'prostafaktura-ksef' ),
			];
		} else {
			return [
				'invoice_number'        => __( 'Nr faktury', 'prostafaktura-ksef' ),
				'issue_date'            => __( 'Data', 'prostafaktura-ksef' ),
				'seller_nip'            => __( 'NIP dostawcy', 'prostafaktura-ksef' ),
				'seller_name'           => __( 'Nazwa dostawcy', 'prostafaktura-ksef' ),
				'gross_amount'          => __( 'Kwota brutto', 'prostafaktura-ksef' ),
				'processing_status'     => __( 'Status', 'prostafaktura-ksef' ),
			];
		}
	}

	/**
	 * Pobierz filename dla export'u
	 *
	 * @param string $type Typ.
	 * @param string $format Format (csv/pdf).
	 * @return string Filename
	 */
	private static function get_export_filename( $type, $format ) {
		$date = date_i18n( 'Y-m-d_H-i-s' );
		$type_name = 'outgoing' === $type ? 'wysylane' : 'zakupowe';

		return "ksef_faktury_{$type_name}_{$date}.{$format}";
	}

	/**
	 * ⚠️ SECURITY: Zweryfikuj czy licencja jest ważna
	 *
	 * @return bool
	 */
	private static function verify_license() {
		return true;
	}
}
