<?php
/**
 * Bill REST API Endpoints
 *
 * @package Care_API
 */

namespace Care_API\Endpoints;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use Care_API\Services\Database\Bill_Service;
use Care_API\Services\Permission_Service;
use Care_API\Utils\Input_Validator;
use Care_API\Utils\Error_Handler;

/**
 * Bill Endpoints Class
 */
class Bill_Endpoints {

	/**
	 * API namespace
	 *
	 * @var string
	 */
	private const NAMESPACE = 'care/v1';

	/**
	 * Register bill REST routes.
	 */
	public static function register_routes() {
		// Get all bills
		register_rest_route( self::NAMESPACE, '/bills', array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => array( __CLASS__, 'get_bills' ),
			'permission_callback' => array( __CLASS__, 'check_read_permission' ),
			'args'                => array(
				'page' => array(
					'description'       => 'Page number for pagination',
					'type'              => 'integer',
					'default'           => 1,
					'minimum'           => 1,
					'sanitize_callback' => 'absint',
				),
				'per_page' => array(
					'description'       => 'Number of bills per page',
					'type'              => 'integer',
					'default'           => 10,
					'minimum'           => 1,
					'maximum'           => 100,
					'sanitize_callback' => 'absint',
				),
				'status' => array(
					'description' => 'Filter by bill status',
					'type'        => 'string',
					'enum'        => array( 'draft', 'pending', 'paid', 'overdue', 'cancelled' ),
				),
				'patient_id' => array(
					'description'       => 'Filter by patient ID',
					'type'              => 'integer',
					'sanitize_callback' => 'absint',
				),
				'doctor_id' => array(
					'description'       => 'Filter by doctor ID',
					'type'              => 'integer',
					'sanitize_callback' => 'absint',
				),
				'encounter_id' => array(
					'description'       => 'Filter by encounter ID',
					'type'              => 'integer',
					'sanitize_callback' => 'absint',
				),
				'date_from' => array(
					'description' => 'Filter bills from date (YYYY-MM-DD)',
					'type'        => 'string',
					'format'      => 'date',
				),
				'date_to' => array(
					'description' => 'Filter bills to date (YYYY-MM-DD)',
					'type'        => 'string',
					'format'      => 'date',
				),
				'amount_from' => array(
					'description' => 'Filter bills with amount greater than or equal to',
					'type'        => 'number',
					'minimum'     => 0,
				),
				'amount_to' => array(
					'description' => 'Filter bills with amount less than or equal to',
					'type'        => 'number',
					'minimum'     => 0,
				),
			),
		));

		// Create new bill
		register_rest_route( self::NAMESPACE, '/bills', array(
			'methods'             => WP_REST_Server::CREATABLE,
			'callback'            => array( __CLASS__, 'create_bill' ),
			'permission_callback' => array( __CLASS__, 'check_create_permission' ),
			'args'                => array(
				'patient_id' => array(
					'description'       => 'Patient ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
				'doctor_id' => array(
					'description'       => 'Doctor ID',
					'type'              => 'integer',
					'sanitize_callback' => 'absint',
				),
				'encounter_id' => array(
					'description'       => 'Related encounter ID',
					'type'              => 'integer',
					'sanitize_callback' => 'absint',
				),
				'bill_date' => array(
					'description' => 'Bill date (YYYY-MM-DD)',
					'type'        => 'string',
					'required'    => true,
					'format'      => 'date',
				),
				'due_date' => array(
					'description' => 'Due date (YYYY-MM-DD)',
					'type'        => 'string',
					'format'      => 'date',
				),
				'items' => array(
					'description' => 'Array of bill items',
					'type'        => 'array',
					'required'    => true,
					'items'       => array(
						'type' => 'object',
					),
					'minItems' => 1,
				),
				'discount_percentage' => array(
					'description' => 'Discount percentage',
					'type'        => 'number',
					'minimum'     => 0,
					'maximum'     => 100,
					'default'     => 0,
				),
				'tax_percentage' => array(
					'description' => 'Tax percentage',
					'type'        => 'number',
					'minimum'     => 0,
					'maximum'     => 100,
					'default'     => 0,
				),
				'notes' => array(
					'description'       => 'Bill notes',
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				),
				'payment_terms' => array(
					'description'       => 'Payment terms',
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				),
			),
		));

		// Get specific bill
		register_rest_route( self::NAMESPACE, '/bills/(?P<id>\d+)', array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => array( __CLASS__, 'get_bill' ),
			'permission_callback' => array( __CLASS__, 'check_read_permission' ),
			'args'                => array(
				'id' => array(
					'description'       => 'Bill ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
			),
		));

		// Update bill
		register_rest_route( self::NAMESPACE, '/bills/(?P<id>\d+)', array(
			'methods'             => WP_REST_Server::EDITABLE,
			'callback'            => array( __CLASS__, 'update_bill' ),
			'permission_callback' => array( __CLASS__, 'check_update_permission' ),
			'args'                => array(
				'id' => array(
					'description'       => 'Bill ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
				'due_date' => array(
					'description' => 'Due date (YYYY-MM-DD)',
					'type'        => 'string',
					'format'      => 'date',
				),
				'items' => array(
					'description' => 'Array of bill items',
					'type'        => 'array',
					'items'       => array(
						'type' => 'object',
					),
				),
				'discount_percentage' => array(
					'description' => 'Discount percentage',
					'type'        => 'number',
					'minimum'     => 0,
					'maximum'     => 100,
				),
				'tax_percentage' => array(
					'description' => 'Tax percentage',
					'type'        => 'number',
					'minimum'     => 0,
					'maximum'     => 100,
				),
				'notes' => array(
					'description'       => 'Bill notes',
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				),
				'payment_terms' => array(
					'description'       => 'Payment terms',
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				),
				'status' => array(
					'description' => 'Bill status',
					'type'        => 'string',
					'enum'        => array( 'draft', 'pending', 'paid', 'overdue', 'cancelled' ),
				),
			),
		));

		// Delete bill
		register_rest_route( self::NAMESPACE, '/bills/(?P<id>\d+)', array(
			'methods'             => WP_REST_Server::DELETABLE,
			'callback'            => array( __CLASS__, 'delete_bill' ),
			'permission_callback' => array( __CLASS__, 'check_delete_permission' ),
			'args'                => array(
				'id' => array(
					'description'       => 'Bill ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
				'force' => array(
					'description' => 'Force delete (bypass soft delete)',
					'type'        => 'boolean',
					'default'     => false,
				),
			),
		));

		// Finalize bill (convert from draft to pending)
		register_rest_route( self::NAMESPACE, '/bills/(?P<id>\d+)/finalize', array(
			'methods'             => WP_REST_Server::CREATABLE,
			'callback'            => array( __CLASS__, 'finalize_bill' ),
			'permission_callback' => array( __CLASS__, 'check_update_permission' ),
			'args'                => array(
				'id' => array(
					'description'       => 'Bill ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
				'send_to_patient' => array(
					'description' => 'Send bill notification to patient',
					'type'        => 'boolean',
					'default'     => true,
				),
			),
		));

		// Process payment
		register_rest_route( self::NAMESPACE, '/bills/(?P<id>\d+)/payments', array(
			'methods'             => WP_REST_Server::CREATABLE,
			'callback'            => array( __CLASS__, 'process_payment' ),
			'permission_callback' => array( __CLASS__, 'check_payment_permission' ),
			'args'                => array(
				'id' => array(
					'description'       => 'Bill ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
				'amount' => array(
					'description' => 'Payment amount',
					'type'        => 'number',
					'required'    => true,
					'minimum'     => 0.01,
				),
				'payment_method' => array(
					'description' => 'Payment method',
					'type'        => 'string',
					'required'    => true,
					'enum'        => array( 'cash', 'credit_card', 'debit_card', 'bank_transfer', 'check', 'insurance' ),
				),
				'payment_date' => array(
					'description' => 'Payment date (YYYY-MM-DD)',
					'type'        => 'string',
					'format'      => 'date',
				),
				'transaction_reference' => array(
					'description'       => 'Transaction reference number',
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				),
				'notes' => array(
					'description'       => 'Payment notes',
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				),
			),
		));

		// Get bill payments
		register_rest_route( self::NAMESPACE, '/bills/(?P<id>\d+)/payments', array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => array( __CLASS__, 'get_bill_payments' ),
			'permission_callback' => array( __CLASS__, 'check_read_permission' ),
			'args'                => array(
				'id' => array(
					'description'       => 'Bill ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
			),
		));

		// Get patient bills
		register_rest_route( self::NAMESPACE, '/bills/patient/(?P<patient_id>\d+)', array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => array( __CLASS__, 'get_patient_bills' ),
			'permission_callback' => array( __CLASS__, 'check_read_permission' ),
			'args'                => array(
				'patient_id' => array(
					'description'       => 'Patient ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
				'status' => array(
					'description' => 'Filter by status',
					'type'        => 'string',
					'enum'        => array( 'draft', 'pending', 'paid', 'overdue', 'cancelled' ),
				),
				'limit' => array(
					'description'       => 'Number of records to return',
					'type'              => 'integer',
					'default'           => 20,
					'minimum'           => 1,
					'maximum'           => 100,
					'sanitize_callback' => 'absint',
				),
			),
		));

		// Get overdue bills
		register_rest_route( self::NAMESPACE, '/bills/overdue', array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => array( __CLASS__, 'get_overdue_bills' ),
			'permission_callback' => array( __CLASS__, 'check_read_permission' ),
			'args'                => array(
				'days_overdue' => array(
					'description'       => 'Minimum days overdue',
					'type'              => 'integer',
					'default'           => 1,
					'minimum'           => 1,
					'sanitize_callback' => 'absint',
				),
				'limit' => array(
					'description'       => 'Number of records to return',
					'type'              => 'integer',
					'default'           => 50,
					'minimum'           => 1,
					'maximum'           => 200,
					'sanitize_callback' => 'absint',
				),
			),
		));

		// Send bill reminder
		register_rest_route( self::NAMESPACE, '/bills/(?P<id>\d+)/remind', array(
			'methods'             => WP_REST_Server::CREATABLE,
			'callback'            => array( __CLASS__, 'send_bill_reminder' ),
			'permission_callback' => array( __CLASS__, 'check_update_permission' ),
			'args'                => array(
				'id' => array(
					'description'       => 'Bill ID',
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				),
				'reminder_type' => array(
					'description' => 'Type of reminder',
					'type'        => 'string',
					'enum'        => array( 'email', 'sms', 'phone', 'letter' ),
					'default'     => 'email',
				),
				'custom_message' => array(
					'description'       => 'Custom reminder message',
					'type'              => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				),
			),
		));

		// Search bills
		register_rest_route( self::NAMESPACE, '/bills/search', array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => array( __CLASS__, 'search_bills' ),
			'permission_callback' => array( __CLASS__, 'check_read_permission' ),
			'args'                => array(
				'q' => array(
					'description'       => 'Search query',
					'type'              => 'string',
					'required'          => true,
					'sanitize_callback' => 'sanitize_text_field',
				),
				'fields' => array(
					'description' => 'Fields to search in',
					'type'        => 'array',
					'items'       => array(
						'type' => 'string',
						'enum' => array( 'patient_name', 'bill_number', 'notes' ),
					),
					'default' => array( 'patient_name', 'bill_number' ),
				),
				'limit' => array(
					'description'       => 'Maximum results to return',
					'type'              => 'integer',
					'default'           => 10,
					'minimum'           => 1,
					'maximum'           => 50,
					'sanitize_callback' => 'absint',
				),
			),
		));

		// Get bill statistics
		register_rest_route( self::NAMESPACE, '/bills/stats', array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => array( __CLASS__, 'get_bill_statistics' ),
			'permission_callback' => array( __CLASS__, 'check_read_permission' ),
			'args'                => array(
				'period' => array(
					'description' => 'Statistics period',
					'type'        => 'string',
					'enum'        => array( 'week', 'month', 'quarter', 'year' ),
					'default'     => 'month',
				),
				'doctor_id' => array(
					'description'       => 'Filter by doctor ID',
					'type'              => 'integer',
					'sanitize_callback' => 'absint',
				),
			),
		));

		// Bulk operations
		register_rest_route( self::NAMESPACE, '/bills/bulk', array(
			'methods'             => WP_REST_Server::CREATABLE,
			'callback'            => array( __CLASS__, 'bulk_operations' ),
			'permission_callback' => array( __CLASS__, 'check_update_permission' ),
			'args'                => array(
				'action' => array(
					'description' => 'Bulk action to perform',
					'type'        => 'string',
					'required'    => true,
					'enum'        => array( 'finalize', 'cancel', 'send_reminder' ),
				),
				'bill_ids' => array(
					'description' => 'Array of bill IDs',
					'type'        => 'array',
					'required'    => true,
					'items'       => array(
						'type' => 'integer',
					),
					'minItems' => 1,
				),
				'options' => array(
					'description' => 'Additional options for the bulk action',
					'type'        => 'object',
				),
			),
		));
	}

	/**
	 * Get bills list.
	 */
	public static function get_bills( WP_REST_Request $request ) {
		try {
			$page     = $request->get_param( 'page' );
			$per_page = $request->get_param( 'per_page' );
			$offset   = ( $page - 1 ) * $per_page;

			$args = array(
				'limit'  => $per_page,
				'offset' => $offset,
			);

			// Add filters
			$filters = array( 
				'status', 'patient_id', 'doctor_id', 'encounter_id', 
				'date_from', 'date_to', 'amount_from', 'amount_to' 
			);
			foreach ( $filters as $filter ) {
				$value = $request->get_param( $filter );
				if ( $value ) {
					$args[$filter] = $value;
				}
			}

			$result = Bill_Service::get_bills( $args );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			$total_bills = Bill_Service::get_bills_count( $args );
			$total_pages = ceil( $total_bills / $per_page );

			$response = new WP_REST_Response( array(
				'success' => true,
				'data'    => $result,
				'meta'    => array(
					'total'       => $total_bills,
					'pages'       => $total_pages,
					'current'     => $page,
					'per_page'    => $per_page,
				),
			), 200 );

			return $response;

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Create new bill.
	 */
	public static function create_bill( WP_REST_Request $request ) {
		try {
			$bill_data = array(
				'patient_id'          => $request->get_param( 'patient_id' ),
				'doctor_id'           => $request->get_param( 'doctor_id' ),
				'encounter_id'        => $request->get_param( 'encounter_id' ),
				'bill_date'           => $request->get_param( 'bill_date' ),
				'due_date'            => $request->get_param( 'due_date' ),
				'items'               => $request->get_param( 'items' ),
				'discount_percentage' => $request->get_param( 'discount_percentage' ),
				'tax_percentage'      => $request->get_param( 'tax_percentage' ),
				'notes'               => $request->get_param( 'notes' ),
				'payment_terms'       => $request->get_param( 'payment_terms' ),
			);

			// Validate input data
			$validation_result = Input_Validator::validate_bill_data( $bill_data );
			if ( is_wp_error( $validation_result ) ) {
				return Error_Handler::handle_service_error( $validation_result );
			}

			$result = Bill_Service::create_bill( $bill_data );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'message' => 'Bill created successfully',
				'data'    => $result,
			), 201 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Get specific bill.
	 */
	public static function get_bill( WP_REST_Request $request ) {
		try {
			$bill_id = $request->get_param( 'id' );
			$result  = Bill_Service::get_bill( $bill_id );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Update bill.
	 */
	public static function update_bill( WP_REST_Request $request ) {
		try {
			$bill_id     = $request->get_param( 'id' );
			$update_data = array();

			// Only include parameters that were actually sent
			$params = array(
				'due_date', 'items', 'discount_percentage', 'tax_percentage',
				'notes', 'payment_terms', 'status'
			);

			foreach ( $params as $param ) {
				if ( $request->has_param( $param ) ) {
					$update_data[$param] = $request->get_param( $param );
				}
			}

			if ( empty( $update_data ) ) {
				return new WP_REST_Response( array(
					'success' => false,
					'message' => 'No data provided for update',
				), 400 );
			}

			// Validate input data
			$validation_result = Input_Validator::validate_bill_data( $update_data, true );
			if ( is_wp_error( $validation_result ) ) {
				return Error_Handler::handle_service_error( $validation_result );
			}

			$result = Bill_Service::update_bill( $bill_id, $update_data );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'message' => 'Bill updated successfully',
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Delete bill.
	 */
	public static function delete_bill( WP_REST_Request $request ) {
		try {
			$bill_id = $request->get_param( 'id' );
			$force   = $request->get_param( 'force' );

			$result = Bill_Service::delete_bill( $bill_id, $force );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'message' => $force ? 'Bill permanently deleted' : 'Bill cancelled successfully',
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Finalize bill.
	 */
	public static function finalize_bill( WP_REST_Request $request ) {
		try {
			$bill_id          = $request->get_param( 'id' );
			$send_to_patient  = $request->get_param( 'send_to_patient' );

			$result = Bill_Service::finalize_bill( $bill_id, $send_to_patient );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'message' => 'Bill finalized successfully',
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Process payment.
	 */
	public static function process_payment( WP_REST_Request $request ) {
		try {
			$bill_id      = $request->get_param( 'id' );
			$payment_data = array(
				'amount'                 => $request->get_param( 'amount' ),
				'payment_method'         => $request->get_param( 'payment_method' ),
				'payment_date'           => $request->get_param( 'payment_date' ),
				'transaction_reference'  => $request->get_param( 'transaction_reference' ),
				'notes'                  => $request->get_param( 'notes' ),
			);

			$result = Bill_Service::process_payment( $bill_id, $payment_data );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'message' => 'Payment processed successfully',
				'data'    => $result,
			), 201 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Get bill payments.
	 */
	public static function get_bill_payments( WP_REST_Request $request ) {
		try {
			$bill_id = $request->get_param( 'id' );
			$result  = Bill_Service::get_bill_payments( $bill_id );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Get patient bills.
	 */
	public static function get_patient_bills( WP_REST_Request $request ) {
		try {
			$patient_id = $request->get_param( 'patient_id' );
			$status     = $request->get_param( 'status' );
			$limit      = $request->get_param( 'limit' );

			$result = Bill_Service::get_patient_bills( $patient_id, $status, $limit );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Get overdue bills.
	 */
	public static function get_overdue_bills( WP_REST_Request $request ) {
		try {
			$days_overdue = $request->get_param( 'days_overdue' );
			$limit        = $request->get_param( 'limit' );

			$result = Bill_Service::get_overdue_bills( $days_overdue, $limit );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'data'    => $result,
				'meta'    => array(
					'days_overdue' => $days_overdue,
					'results'      => count( $result ),
				),
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Send bill reminder.
	 */
	public static function send_bill_reminder( WP_REST_Request $request ) {
		try {
			$bill_id        = $request->get_param( 'id' );
			$reminder_type  = $request->get_param( 'reminder_type' );
			$custom_message = $request->get_param( 'custom_message' );

			$result = Bill_Service::send_bill_reminder( $bill_id, $reminder_type, $custom_message );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'message' => 'Bill reminder sent successfully',
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Search bills.
	 */
	public static function search_bills( WP_REST_Request $request ) {
		try {
			$query  = $request->get_param( 'q' );
			$fields = $request->get_param( 'fields' );
			$limit  = $request->get_param( 'limit' );

			$result = Bill_Service::search_bills( $query, $fields, $limit );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'data'    => $result,
				'meta'    => array(
					'query'   => $query,
					'fields'  => $fields,
					'results' => count( $result ),
				),
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Get bill statistics.
	 */
	public static function get_bill_statistics( WP_REST_Request $request ) {
		try {
			$period    = $request->get_param( 'period' );
			$doctor_id = $request->get_param( 'doctor_id' );

			$result = Bill_Service::get_billing_statistics( $period, $doctor_id );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Handle bulk operations.
	 */
	public static function bulk_operations( WP_REST_Request $request ) {
		try {
			$action   = $request->get_param( 'action' );
			$bill_ids = $request->get_param( 'bill_ids' );
			$options  = $request->get_param( 'options' );

			$result = Bill_Service::bulk_update_bills( $bill_ids, $action, $options );

			if ( is_wp_error( $result ) ) {
				return Error_Handler::handle_service_error( $result );
			}

			return new WP_REST_Response( array(
				'success' => true,
				'message' => sprintf( 'Bulk operation "%s" completed successfully', $action ),
				'data'    => $result,
			), 200 );

		} catch ( Exception $e ) {
			return Error_Handler::handle_exception( $e );
		}
	}

	/**
	 * Check read permission.
	 */
	public static function check_read_permission( WP_REST_Request $request ) {
		return Permission_Service::can_read_bills();
	}

	/**
	 * Check create permission.
	 */
	public static function check_create_permission( WP_REST_Request $request ) {
		return Permission_Service::can_manage_bills();
	}

	/**
	 * Check update permission.
	 */
	public static function check_update_permission( WP_REST_Request $request ) {
		$bill_id = $request->get_param( 'id' );
		return Permission_Service::can_edit_bill( $bill_id );
	}

	/**
	 * Check delete permission.
	 */
	public static function check_delete_permission( WP_REST_Request $request ) {
		$bill_id = $request->get_param( 'id' );
		return Permission_Service::can_delete_bill( $bill_id );
	}

	/**
	 * Check payment permission.
	 */
	public static function check_payment_permission( WP_REST_Request $request ) {
		return Permission_Service::can_process_payments();
	}
}