<?php
/**
 * TitanCart Reports REST Controller
 *
 * Registers all /wp-json/titancart/v1/reports/* endpoints.
 *
 * @package TitanCart\REST\Reports
 */

namespace TitanCart\REST\Reports;

use TitanCart\Modules\Reports\ReportService;
use TitanCart\Services\SettingsService;

defined( 'ABSPATH' ) || exit;

class ReportsController {

	protected string $namespace = 'titancart/v1';
	protected ReportService $reports;

	public function __construct() {
		$this->reports = new ReportService();
	}

	public function register_routes(): void {
		register_rest_route( $this->namespace, '/reports/dashboard', [
			'methods'             => 'GET',
			'callback'            => [ $this, 'getDashboard' ],
			'permission_callback' => [ $this, 'adminOnly_basic' ],
			'args'                => $this->periodArgs(),
		] );

	}

	// ─────────────────────────────────────────────────────────
	// Handlers
	// ─────────────────────────────────────────────────────────

	public function getDashboard( \WP_REST_Request $req ): \WP_REST_Response {
		$period    = $req->get_param( 'period' )    ?? 'this_month';
		$date_from = $req->get_param( 'date_from' ) ?? null;
		$date_to   = $req->get_param( 'date_to' )   ?? null;

		// ── 60-second transient cache per period to avoid hammering DB ──
		$cache_key = 'titancart_dash_' . md5( $period . $date_from . $date_to );
		$cached    = get_transient( $cache_key );
		if ( false !== $cached && is_array( $cached ) ) {
			return new \WP_REST_Response( $cached );
		}

		$range    = $this->reports->resolvePeriod( $period, $date_from, $date_to );
		$from     = substr( $range['from'], 0, 10 );
		$to       = substr( $range['to'], 0, 10 );

		$stats    = $this->reports->getDashboardStats( $period, $date_from, $date_to );
		$chart    = $this->reports->getSalesChart( $from, $to );
		$top      = $this->reports->getTopProducts( $from, $to, 5 );
		$recent   = $this->reports->getRecentOrders( 10 );
		$stock    = $this->reports->getLowStockProducts( SettingsService::int( 'general', 'catalog_low_stock_threshold', 0 ) );
		$statuses = $this->reports->getOrderStatusCounts();

		$response = [
			'stats'          => $stats,
			'chart'          => $chart,
			'top_products'   => $top,
			'recent_orders'  => $recent,
			'low_stock'      => $stock,
			'order_statuses' => $statuses,
		];

		set_transient( $cache_key, $response, 60 );

		return new \WP_REST_Response( $response );
	}


	// ─────────────────────────────────────────────────────────
	// Permission & arg helpers
	// ─────────────────────────────────────────────────────────


	/** Lite baseline — the /reports/dashboard "simple sales number" overview. */
	public function adminOnly_basic(): bool {
		return current_user_can( 'manage_options' );
	}

	protected function periodArgs(): array {
		return array_merge( $this->dateRangeArgs(), [
			'period' => [ 'type' => 'string', 'default' => 'this_month',
				'enum' => [ 'today','yesterday','this_week','last_week','this_month','last_month','this_year','last_year','custom' ] ],
		] );
	}


	protected function dateRangeArgs(): array {
		return [
			'date_from' => [ 'type' => 'string', 'format' => 'date' ],
			'date_to'   => [ 'type' => 'string', 'format' => 'date' ],
		];
	}
}
