<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class LatePointAbilityGetAgentRevenue extends LatePointAbstractAgentAbility {

	protected function configure(): void {
		$this->id          = 'latepoint/get-agent-revenue';
		$this->label       = __( 'Get agent revenue', 'latepoint' );
		$this->description = __( 'Returns total revenue generated by an agent for a date range.', 'latepoint' );
		$this->permission  = 'agent__view';
		$this->read_only   = true;
	}

	public function get_input_schema(): array {
		return [
			'type'       => 'object',
			'properties' => [
				'agent_id'  => [
					'type'        => 'integer',
					'description' => __( 'Agent ID.', 'latepoint' ),
				],
				'date_from' => [
					'type'        => 'string',
					'format'      => 'date',
					'description' => __( 'Period start (Y-m-d).', 'latepoint' ),
				],
				'date_to'   => [
					'type'        => 'string',
					'format'      => 'date',
					'description' => __( 'Period end (Y-m-d).', 'latepoint' ),
				],
			],
			'required'   => [ 'agent_id', 'date_from', 'date_to' ],
		];
	}

	public function get_output_schema(): array {
		return [
			'type'       => 'object',
			'properties' => [
				'agent_id' => [ 'type' => 'integer' ],
				'revenue'  => [ 'type' => 'number' ],
				'currency' => [ 'type' => 'string' ],
			],
		];
	}

	public function execute( array $args ) {
		$agent = new OsAgentModel( (int) $args['agent_id'] );
		if ( $agent->is_new_record() ) {
			return new WP_Error( 'not_found', __( 'Agent not found.', 'latepoint' ), [ 'status' => 404 ] );
		}

		$filter           = new \LatePoint\Misc\Filter();
		$filter->agent_id = $agent->id;

		$revenue = OsBookingHelper::get_stat_for_period(
			'price',
			sanitize_text_field( $args['date_from'] ),
			sanitize_text_field( $args['date_to'] ),
			$filter
		);

		return [
			'agent_id' => (int) $agent->id,
			'revenue'  => (float) ( $revenue ?? 0 ),
			'currency' => OsSettingsHelper::get_settings_value( 'currency', 'USD' ),
		];
	}
}
