<?php
/**
 * Export Class
 *
 * @package Giraforms
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class GiraForms_Export
 */
class GiraForms_Export {

	/**
	 * Export submissions to CSV.
	 *
	 * @param string $form_id Form ID.
	 * @param array  $args Additional arguments.
	 */
	public static function export_to_csv( $form_id = '', $args = array() ) {
		// Verify nonce
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'giraforms_export_csv' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'giraforms' ) );
		}

		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have the necessary permissions.', 'giraforms' ) );
		}

		// Validate form_id if provided
		if ( ! empty( $form_id ) ) {
			$form_id = sanitize_text_field( $form_id );
			$valid_forms = GiraForms_Submissions::get_form_ids();
			if ( ! in_array( $form_id, $valid_forms, true ) ) {
				wp_die( esc_html__( 'Invalid form ID.', 'giraforms' ) );
			}
		}

		// Get submissions
		$query_args = array_merge(
			array(
				'form_id' => $form_id,
				'limit'   => 9999,
			),
			$args
		);

		$submissions = GiraForms_Submissions::get_submissions( $query_args );

		if ( empty( $submissions ) ) {
			wp_die( esc_html__( 'No submissions to export.', 'giraforms' ) );
		}

		// Prepare CSV headers
		$headers = self::get_csv_headers( $submissions );

		// Set headers for download
		$filename = 'giraforms-' . ( $form_id ? sanitize_file_name( $form_id ) . '-' : '' ) . 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' );

		// Open output stream
		$output = fopen( 'php://output', 'w' );

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

		// Write headers
		fputcsv( $output, $headers );

		// Write data
		foreach ( $submissions as $submission ) {
			$row = self::prepare_csv_row( $submission, $headers );
			fputcsv( $output, $row );
		}

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
		fclose( $output );
		exit;
	}

	/**
	 * Get CSV headers from submissions.
	 *
	 * @param array $submissions Submissions array.
	 * @return array
	 */
	private static function get_csv_headers( $submissions ) {
		$headers = array(
			'ID',
			'Form ID',
			'Date',
			'Status',
			'IP Address',
		);

		// Get all unique field keys
		$field_keys = array();
		foreach ( $submissions as $submission ) {
			if ( isset( $submission['data'] ) && is_array( $submission['data'] ) ) {
				foreach ( $submission['data'] as $key => $value ) {
					// Skip internal fields
					if ( strpos( $key, '_' ) === 0 ) {
						continue;
					}
					if ( ! in_array( $key, $field_keys, true ) ) {
						$field_keys[] = $key;
					}
				}
			}
		}

		// Add field keys to headers
		$headers = array_merge( $headers, $field_keys );

		return $headers;
	}

	/**
	 * Prepare CSV row data.
	 *
	 * @param array $submission Submission data.
	 * @param array $headers CSV headers.
	 * @return array
	 */
	private static function prepare_csv_row( $submission, $headers ) {
		$row = array();

		foreach ( $headers as $header ) {
			switch ( $header ) {
				case 'ID':
					$row[] = $submission['id'];
					break;
				case 'Form ID':
					$row[] = $submission['form_id'];
					break;
				case 'Date':
					$row[] = $submission['created_at'];
					break;
				case 'Status':
					$row[] = $submission['status'];
					break;
				case 'IP Address':
					$row[] = $submission['user_ip'];
					break;
				default:
					// Field data
					$value = isset( $submission['data'][ $header ] ) ? $submission['data'][ $header ] : '';
					if ( is_array( $value ) ) {
						$value = implode( ', ', $value );
					}
					$row[] = $value;
					break;
			}
		}

		return $row;
	}
}
