<?php
/**
 * GGM Commerce Variation Type CSV Exporter
 *
 * Handles CSV export functionality for variation types
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class GGM_Commerce_Variation_Type_CSV_Exporter
 *
 * Exports variation types to CSV format
 */
class GGM_Commerce_Variation_Type_CSV_Exporter {

	/**
	 * Export variation types to CSV
	 *
	 * @param array $options Export options.
	 * @return array|WP_Error Result with file path or error.
	 */
	public function export( $options = array() ) {
		$defaults = array(
			'status' => '', // Empty means all statuses.
		);

		$options = wp_parse_args( $options, $defaults );

		// Get data to export.
		$data    = $this->get_variation_types( $options );
		$headers = $this->get_headers();

		if ( empty( $data ) ) {
			return new WP_Error(
				'no_data',
				__( 'No variation types found to export', 'ggm-commerce' )
			);
		}

		// Build CSV rows.
		$rows = array();
		foreach ( $data as $item ) {
			$rows[] = $this->build_row( $item );
		}

		// Generate CSV file.
		$filename = 'ggm-variation-types-export-' . gmdate( 'Y-m-d-His' ) . '.csv';
		$filepath = $this->get_export_directory() . $filename;

		$this->write_csv( $filepath, $headers, $rows );

		return array(
			'success'  => true,
			'file'     => $filepath,
			'filename' => $filename,
			'count'    => count( $rows ),
			'type'     => 'variation_types',
		);
	}

	/**
	 * Get variation type headers
	 *
	 * @return array CSV headers for variation types.
	 */
	private function get_headers() {
		return array(
			'name',
			'slug',
			'input_type',
			'options',
			'display_order',
			'status',
		);
	}

	/**
	 * Get variation types for export
	 *
	 * @param array $options Filter options.
	 * @return array Variation types.
	 */
	private function get_variation_types( $options ) {
		global $wpdb;

		$where = array( '1=1' );

		if ( ! empty( $options['status'] ) ) {
			$where[] = $wpdb->prepare( 'status = %s', $options['status'] );
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->get_results(
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			"SELECT * FROM {$wpdb->prefix}ggmc_variation_types
			 WHERE " . implode( ' AND ', $where ) . '
			 ORDER BY display_order ASC, name ASC'
		);
	}

	/**
	 * Build a variation type row for CSV export
	 *
	 * @param object $variation_type Variation type object.
	 * @return array Row data.
	 */
	private function build_row( $variation_type ) {
		// Handle options - already JSON in database, keep as-is or re-encode.
		$options = '';
		if ( ! empty( $variation_type->options ) ) {
			// Decode and re-encode to ensure proper formatting.
			$decoded = json_decode( $variation_type->options, true );
			if ( is_array( $decoded ) ) {
				$options = wp_json_encode( $decoded, JSON_UNESCAPED_UNICODE );
			}
		}

		return array(
			'name'          => $variation_type->name,
			'slug'          => $variation_type->slug,
			'input_type'    => $variation_type->input_type ?? 'select',
			'options'       => $options,
			'display_order' => $variation_type->display_order ?? 0,
			'status'        => $variation_type->status ?? 'active',
		);
	}

	/**
	 * Get export directory path
	 *
	 * @return string Directory path.
	 */
	private function get_export_directory() {
		$upload_dir = wp_upload_dir();
		$export_dir = $upload_dir['basedir'] . '/ggm-commerce-exports/';

		if ( ! file_exists( $export_dir ) ) {
			wp_mkdir_p( $export_dir );

			// Add index.php to prevent directory listing.
			file_put_contents( $export_dir . 'index.php', '<?php // Silence is golden' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents

			// Add .htaccess to protect files.
			file_put_contents( $export_dir . '.htaccess', "deny from all\n" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
		}

		return $export_dir;
	}

	/**
	 * Write CSV file
	 *
	 * @param string $filepath File path.
	 * @param array  $headers CSV headers.
	 * @param array  $rows Data rows.
	 */
	private function write_csv( $filepath, $headers, $rows ) {
		$handle = fopen( $filepath, 'w' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen

		// Add BOM for Excel UTF-8 compatibility.
		fwrite( $handle, "\xEF\xBB\xBF" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite

		// Write headers.
		fputcsv( $handle, $headers );

		// Write rows.
		foreach ( $rows as $row ) {
			// Ensure row values are in header order.
			$ordered_row = array();
			foreach ( $headers as $header ) {
				$ordered_row[] = isset( $row[ $header ] ) ? $row[ $header ] : '';
			}
			fputcsv( $handle, $ordered_row );
		}

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

	/**
	 * Generate a template CSV for import reference
	 *
	 * @return array|WP_Error Result with file path or error.
	 */
	public function generate_template() {
		$headers = $this->get_headers();

		$example_rows = array(
			array(
				'name'          => 'Size',
				'slug'          => 'size',
				'input_type'    => 'select',
				'options'       => '[{"value":"S","label":"Small"},{"value":"M","label":"Medium"},{"value":"L","label":"Large"}]',
				'display_order' => '0',
				'status'        => 'active',
			),
			array(
				'name'          => 'Color',
				'slug'          => 'color',
				'input_type'    => 'color',
				'options'       => '[{"value":"Red","label":"Red","color":"#FF0000"},{"value":"Blue","label":"Blue","color":"#0000FF"}]',
				'display_order' => '1',
				'status'        => 'active',
			),
		);

		$filename = 'ggm-variation-types-template.csv';
		$filepath = $this->get_export_directory() . $filename;

		$this->write_csv( $filepath, $headers, $example_rows );

		return array(
			'success'  => true,
			'file'     => $filepath,
			'filename' => $filename,
			'type'     => 'variation_types',
		);
	}
}
