<?php
/**
 * Route handler for analytics summaries and exports.
 *
 * @package    100Prints
 */

class Hundred_Prints_Route_Analytics {

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route( '100prints/v1', '/analytics', [
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => [ $this, 'get_analytics' ],
				'permission_callback' => [ $this, 'permission_check' ],
			],
		] );
	}

	/**
	 * Permission check callback.
	 */
	public function permission_check( $request ) {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Fetch or export analytics logs.
	 */
	public function get_analytics( $request ) {
		$format = $request->get_param( 'format' );
		$analytics_service = new Hundred_Prints_Analytics_Service();

		if ( $format === 'csv' ) {
			$csv_data = $this->generate_csv_string( $analytics_service );
			return rest_ensure_response( [ 'csv_data' => $csv_data ] );
		}

		$data = [
			'total_generations'   => $analytics_service->get_total_generations(),
			'generations_30_days' => $analytics_service->get_generations_last_30_days(),
			'success_rate'        => $analytics_service->get_success_rate(),
			'daily_counts'        => $analytics_service->get_daily_counts_30_days(),
			'template_breakdown'  => $analytics_service->get_template_breakdown(),
		];

		return rest_ensure_response( $data );
	}

	/**
	 * Generate generation logs as a CSV string.
	 */
	private function generate_csv_string( $analytics_service ) {
		$logs = $analytics_service->get_all_activity_logs();
		$output = fopen( 'php://temp', 'r+' );
		fputcsv( $output, [ 'ID', 'Date', 'Template ID', 'Template Name', 'Page ID', 'Format', 'Status', 'User ID' ] );

		if ( ! empty( $logs ) ) {
			foreach ( $logs as $log ) {
				fputcsv( $output, [
					$log->id,
					$log->created_at,
					$log->template_id,
					$log->template_name,
					$log->page_id,
					$log->format,
					$log->status,
					$log->user_id,
				] );
			}
		}
		
		rewind( $output );
		$csv_string = stream_get_contents( $output );
		fclose( $output );
		
		return $csv_string;
	}
}
