<?php
/**
 * GGM Commerce Attribute CSV Exporter
 *
 * Handles CSV export functionality for attribute groups and attributes
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

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

/**
 * Class GGM_Commerce_Attribute_CSV_Exporter
 *
 * Exports attribute groups and attributes to CSV format
 */
class GGM_Commerce_Attribute_CSV_Exporter {

	/**
	 * Export type: 'groups' or 'attributes'
	 *
	 * @var string
	 */
	private $export_type;

	/**
	 * Constructor
	 *
	 * @param string $export_type Export type ('groups' or 'attributes').
	 */
	public function __construct( $export_type = 'attributes' ) {
		$this->export_type = $export_type;
	}

	/**
	 * Export data 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.
		if ( 'groups' === $this->export_type ) {
			$data    = $this->get_attribute_groups( $options );
			$headers = $this->get_group_headers();
		} else {
			$data    = $this->get_attributes( $options );
			$headers = $this->get_attribute_headers();
		}

		if ( empty( $data ) ) {
			return new WP_Error(
				'no_data',
				sprintf(
					/* translators: %s: export type */
					__( 'No %s found to export', 'ggm-commerce' ),
					'groups' === $this->export_type ? __( 'attribute groups', 'ggm-commerce' ) : __( 'attributes', 'ggm-commerce' )
				)
			);
		}

		// Build CSV rows.
		$rows = array();
		foreach ( $data as $item ) {
			if ( 'groups' === $this->export_type ) {
				$rows[] = $this->build_group_row( $item );
			} else {
				$rows[] = $this->build_attribute_row( $item );
			}
		}

		// Generate CSV file.
		$type_slug = 'groups' === $this->export_type ? 'attribute-groups' : 'attributes';
		$filename  = 'ggm-' . $type_slug . '-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'     => $this->export_type,
		);
	}

	/**
	 * Get attribute group headers
	 *
	 * @return array CSV headers for attribute groups.
	 */
	private function get_group_headers() {
		return array(
			'name',
			'description',
			'display_order',
			'status',
		);
	}

	/**
	 * Get attribute headers
	 *
	 * @return array CSV headers for attributes.
	 */
	private function get_attribute_headers() {
		return array(
			'name',
			'group_name',
			'attribute_type',
			'options',
			'unit',
			'icon',
			'filterable',
			'display_order',
			'status',
		);
	}

	/**
	 * Get attribute groups for export
	 *
	 * @param array $options Filter options.
	 * @return array Attribute groups.
	 */
	private function get_attribute_groups( $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_attribute_groups
			 WHERE " . implode( ' AND ', $where ) . '
			 ORDER BY display_order ASC, name ASC'
		);
	}

	/**
	 * Get attributes for export
	 *
	 * @param array $options Filter options.
	 * @return array Attributes.
	 */
	private function get_attributes( $options ) {
		global $wpdb;

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

		if ( ! empty( $options['status'] ) ) {
			$where[] = $wpdb->prepare( 'a.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 a.*, g.name as group_name
			 FROM {$wpdb->prefix}ggmc_attributes a
			 LEFT JOIN {$wpdb->prefix}ggmc_attribute_groups g ON a.group_id = g.id
			 WHERE " . implode( ' AND ', $where ) . '
			 ORDER BY g.display_order ASC, a.display_order ASC, a.name ASC'
		);
	}

	/**
	 * Build an attribute group row for CSV export
	 *
	 * @param object $group Attribute group object.
	 * @return array Row data.
	 */
	private function build_group_row( $group ) {
		return array(
			'name'          => $group->name,
			'description'   => $group->description ?? '',
			'display_order' => $group->display_order ?? 0,
			'status'        => $group->status ?? 'active',
		);
	}

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

		// Handle icon - already JSON in database.
		$icon = $attribute->icon ?? '';

		return array(
			'name'           => $attribute->name,
			'group_name'     => $attribute->group_name ?? '',
			'attribute_type' => $attribute->attribute_type ?? 'text',
			'options'        => $options,
			'unit'           => $attribute->unit ?? '',
			'icon'           => $icon,
			'filterable'     => $attribute->filterable ? '1' : '0',
			'display_order'  => $attribute->display_order ?? 0,
			'status'         => $attribute->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 = 'groups' === $this->export_type
			? $this->get_group_headers()
			: $this->get_attribute_headers();

		$example_row = 'groups' === $this->export_type
			? array(
				'name'          => 'Technical Specs',
				'description'   => 'Technical specifications for products',
				'display_order' => '0',
				'status'        => 'active',
			)
			: array(
				'name'           => 'Color',
				'group_name'     => 'Physical Properties',
				'attribute_type' => 'select',
				'options'        => '[{"value":"Red"},{"value":"Blue"},{"value":"Green"}]',
				'unit'           => '',
				'icon'           => '{"type":"lucide","name":"palette"}',
				'filterable'     => '1',
				'display_order'  => '0',
				'status'         => 'active',
			);

		$type_slug = 'groups' === $this->export_type ? 'attribute-groups' : 'attributes';
		$filename  = 'ggm-' . $type_slug . '-template.csv';
		$filepath  = $this->get_export_directory() . $filename;

		$this->write_csv( $filepath, $headers, array( $example_row ) );

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