<?php
namespace EM_Pro\API;

class Utils {

	public static function get_request_data( $request ) {
		$params = is_object( $request ) && method_exists( $request, 'get_params' ) ? $request->get_params() : array();
		$json = is_object( $request ) && method_exists( $request, 'get_json_params' ) ? $request->get_json_params() : array();
		if ( !is_array( $params ) ) $params = array();
		if ( !is_array( $json ) ) $json = array();
		return array_merge( $params, $json );
	}

	public static function normalize_input( $input ) {
		return is_array( $input ) ? $input : array();
	}

	public static function error( $code, $message, $status = 400, $extra = array() ) {
		return new \WP_Error( $code, $message, array_merge( array( 'status' => $status ), $extra ) );
	}

	public static function object_error( $code, $object, $fallback, $status = 400 ) {
		$errors = is_object( $object ) && method_exists( $object, 'get_errors' ) ? $object->get_errors() : array();
		$message = !empty( $errors ) ? implode( ' ', array_map( 'wp_strip_all_tags', (array) $errors ) ) : $fallback;
		return static::error( $code, $message, $status, array( 'errors' => $errors ) );
	}

	public static function is_truthy( $value ) {
		return $value === true || $value === 1 || $value === '1' || $value === 'true';
	}

	public static function collection_args( $params ) {
		$page = !empty( $params['page'] ) ? absint( $params['page'] ) : 1;
		$per_page = !empty( $params['per_page'] ) ? absint( $params['per_page'] ) : ( !empty( $params['limit'] ) ? absint( $params['limit'] ) : 20 );
		$page = max( 1, $page );
		$per_page = max( 1, min( 100, $per_page ) );
		return array(
			'page' => $page,
			'per_page' => $per_page,
			'limit' => $per_page,
			'offset' => ( $page - 1 ) * $per_page,
		);
	}

	public static function pagination( $total, $page, $per_page ) {
		return array(
			'total' => absint( $total ),
			'total_pages' => $per_page ? (int) ceil( absint( $total ) / $per_page ) : 0,
			'page' => absint( $page ),
			'per_page' => absint( $per_page ),
		);
	}

	public static function can_manage_bookings() {
		return current_user_can( 'manage_bookings' ) || current_user_can( 'manage_others_bookings' );
	}

	public static function can_manage_others_bookings() {
		return current_user_can( 'manage_others_bookings' );
	}
}
