<?php
if ( ! defined( 'WPINC' ) ) {
	exit;
}

if ( ! class_exists( 'Tpaep_Export_Submissions' ) ) {

	class Tpaep_Export_Submissions {

		private static $instance = null;

		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		public function __construct() {
			add_action(
				'admin_post_tpae_export_all_submissions',
				[ $this, 'tpae_export_all_submissions_csv' ]
			);
			add_action(
				'admin_post_tpae_export_selected_submissions',
				[ $this, 'tpae_export_selected_submissions_csv' ]
			);
		}

		public function tpae_export_all_submissions_csv() {

			check_admin_referer( 'tpae_export_all', '_wpnonce' );

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_die( esc_html__( 'Unauthorized', 'theplus' ) );
			}

			global $wpdb;
			$table = $wpdb->prefix . 'tpaep_formsmeta';

			// Guard: abort gracefully if the table does not yet exist.
			if ( ! (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) ) {
				wp_die( esc_html__( 'Form submissions table does not exist.', 'theplus' ) );
			}

			// ---- Build WHERE from active filters ----
			$where = [];

			if ( ! empty( $_GET['filter_form'] ) ) {
				$where[] = $wpdb->prepare( 'form_name = %s', sanitize_text_field( $_GET['filter_form'] ) );
			}

			if ( ! empty( $_GET['filter_page'] ) ) {
				$where[] = $wpdb->prepare( 'post_id = %d', absint( $_GET['filter_page'] ) );
			}

			$date_filter = isset( $_GET['date_filter'] ) ? sanitize_text_field( $_GET['date_filter'] ) : '';
			switch ( $date_filter ) {
				case 'today':
					$where[] = "DATE(submitted_at) = CURDATE()";
					break;
				case 'yesterday':
					$where[] = "DATE(submitted_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
					break;
				case 'last_7':
					$where[] = "submitted_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
					break;
				case 'last_30':
					$where[] = "submitted_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
					break;
				case 'custom':
					if ( ! empty( $_GET['date_from'] ) ) {
						$where[] = $wpdb->prepare( 'DATE(submitted_at) >= %s', sanitize_text_field( $_GET['date_from'] ) );
					}
					if ( ! empty( $_GET['date_to'] ) ) {
						$where[] = $wpdb->prepare( 'DATE(submitted_at) <= %s', sanitize_text_field( $_GET['date_to'] ) );
					}
					break;
			}

			if ( ! empty( $_GET['s'] ) ) {
				$s = '%' . $wpdb->esc_like( sanitize_text_field( $_GET['s'] ) ) . '%';
				$where[] = $wpdb->prepare(
					'(form_name LIKE %s OR form_fields LIKE %s)',
					$s, $s
				);
			}

			$where_sql = $where ? 'WHERE ' . implode( ' AND ', $where ) : '';
			$is_filtered = ! empty( $where );

			$rows = $wpdb->get_results(
				"SELECT * FROM $table $where_sql ORDER BY submitted_at DESC",
				ARRAY_A
			);

			if ( empty( $rows ) ) {
				wp_die( esc_html__( 'No data found', 'theplus' ) );
			}

			// CRITICAL: no output before headers
			while ( ob_get_level() ) {
				ob_end_clean();
			}

			$filename = $is_filtered ? 'form-submissions-filtered.csv' : 'form-submissions.csv';

			header( 'Content-Type: text/csv; charset=utf-8' );
			header( 'Content-Disposition: attachment; filename=' . $filename );
			header( 'Pragma: no-cache' );
			header( 'Expires: 0' );

			$out = fopen( 'php://output', 'w' );
			fputcsv( $out, array_keys( $rows[0] ), ',', '"', '\\' );

			foreach ( $rows as $row ) {
				fputcsv( $out, $row, ',', '"', '\\' );
			}

			fclose( $out );
			exit;
		}

		public function tpae_export_selected_submissions_csv() {

			check_admin_referer( 'tpae_export_selected', '_wpnonce' );

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_die( esc_html__( 'Unauthorized', 'theplus' ) );
			}

			if ( empty( $_GET['submission_ids'] ) ) {
				wp_die( esc_html__( 'No submissions selected.', 'theplus' ) );
			}

			// Sanitize: allow only comma-separated integers
			$raw_ids = sanitize_text_field( $_GET['submission_ids'] );
			$ids     = array_filter( array_map( 'absint', explode( ',', $raw_ids ) ) );

			if ( empty( $ids ) ) {
				wp_die( esc_html__( 'Invalid submission IDs.', 'theplus' ) );
			}

			global $wpdb;
			$table = $wpdb->prefix . 'tpaep_formsmeta';

			// Guard: abort gracefully if the table does not yet exist.
			if ( ! (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) ) {
				wp_die( esc_html__( 'Form submissions table does not exist.', 'theplus' ) );
			}

			$ids_sql = implode( ',', $ids );

			$rows = $wpdb->get_results(
				"SELECT * FROM $table WHERE id IN ($ids_sql) ORDER BY submitted_at DESC",
				ARRAY_A
			);

			if ( empty( $rows ) ) {
				wp_die( esc_html__( 'No data found for the selected submissions.', 'theplus' ) );
			}

			// No output before headers
			while ( ob_get_level() ) {
				ob_end_clean();
			}

			header( 'Content-Type: text/csv; charset=utf-8' );
			header( 'Content-Disposition: attachment; filename=form-submissions-selected-' . gmdate( 'Y-m-d' ) . '.csv' );
			header( 'Pragma: no-cache' );
			header( 'Expires: 0' );

			$out = fopen( 'php://output', 'w' );
			fputcsv( $out, array_keys( $rows[0] ), ',', '"', '\\' );
			foreach ( $rows as $row ) {
				fputcsv( $out, $row, ',', '"', '\\' );
			}
			fclose( $out );
			exit;
		}
	}
}

Tpaep_Export_Submissions::get_instance();
