<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class AVIN_Exporter {
	private $repository;
	private $wc_metrics;

	public function __construct( AVIN_Views_Repository $repository, AVIN_WooCommerce_Metrics $wc_metrics ) {
		$this->repository = $repository;
		$this->wc_metrics = $wc_metrics;
	}

	public function export_csv() {
		if ( ! current_user_can( $this->capability() ) ) {
			wp_die( esc_html__( 'You do not have permission to export Apex View Insights data.', 'apex-view-insights' ) );
		}

		check_admin_referer( 'avin_export_csv' );

		$rows        = $this->repository->export_rows( 1000 );
		$product_ids = array();
		foreach ( $rows as $row ) {
			if ( 'product' === $row['post_type'] ) {
				$product_ids[] = absint( $row['object_id'] );
			}
		}
		$sales_30 = $this->wc_metrics->sales_for_products( $product_ids, 30 );

		nocache_headers();
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=apex-view-insights-' . gmdate( 'Y-m-d' ) . '.csv' );

		$out = fopen( 'php://output', 'w' );
		fputcsv(
			$out,
			array(
				'object_id',
				'title',
				'post_type',
				'total_views',
				'today_views',
				'views_7_days',
				'views_30_days',
				'units_sold_30_days',
				'revenue_30_days',
				'conversion_rate_30_days',
			)
		);

		foreach ( $rows as $row ) {
			$object_id = absint( $row['object_id'] );
			$metrics   = $this->repository->object_metrics( array( $object_id ) );
			$views_30  = isset( $metrics[ $object_id ] ) ? absint( $metrics[ $object_id ]['30'] ) : 0;
			$sales     = isset( $sales_30[ $object_id ] ) ? $sales_30[ $object_id ] : array(
				'units'   => 0,
				'revenue' => 0,
			);
			$rate      = $views_30 > 0 ? round( ( $sales['units'] / $views_30 ) * 100, 2 ) : 0;

			fputcsv(
				$out,
				array(
					$object_id,
					wp_strip_all_tags( $row['post_title'] ),
					$row['post_type'],
					absint( $row['total_views'] ),
					isset( $metrics[ $object_id ] ) ? absint( $metrics[ $object_id ]['today'] ) : 0,
					isset( $metrics[ $object_id ] ) ? absint( $metrics[ $object_id ]['7'] ) : 0,
					$views_30,
					absint( $sales['units'] ),
					(float) $sales['revenue'],
					$rate,
				)
			);
		}

		exit;
	}

	private function capability() {
		return class_exists( 'WooCommerce' ) ? 'manage_woocommerce' : 'manage_options';
	}
}
