<?php

namespace Limb_Chatbot\Includes\Repositories;

use Limb_Chatbot\Includes\Data_Objects\Action_Submission;
use Limb_Chatbot\Includes\Services\Data_Object_Collection;

/**
 * Repository class for managing Action_Submission records.
 *
 * Provides methods for retrieving action submissions with search and pagination support.
 *
 * @package Limb_Chatbot\Includes\Repositories
 * @since 1.0.0
 */
class Action_Submission_Repository {

	/**
	 * Retrieves a collection of submissions based on given parameters.
	 *
	 * Supports pagination, ordering, and search.
	 * Search: Status, error message, or submission data
	 *
	 * @param int   $action_id The action ID to filter by
	 * @param array $params    Parameters for filtering, pagination, and search
	 *
	 * @return Data_Object_Collection Collection of Action_Submission objects.
	 * @since 1.0.0
	 */
	public function get_items( int $action_id, array $params ): Data_Object_Collection {
		// Sanitize and validate input parameters
		$per_page = isset( $params['per_page'] ) ? absint( $params['per_page'] ) : 10;
		$order_by = isset( $params['orderby'] ) ? sanitize_key( $params['orderby'] ) : 'created_at';
		$page     = isset( $params['page'] ) ? absint( $params['page'] ) : 1;
		$order    = isset( $params['order'] ) ? strtoupper( sanitize_key( $params['order'] ) ) : 'DESC';
		// Validate order direction
		if ( ! in_array( $order, [ 'ASC', 'DESC' ], true ) ) {
			$order = 'DESC';
		}

		// Build base where clause
		$where = [ 'action_id' => $action_id ];

		if ( isset( $params['starting_from'] ) ) {
			$where['created_at>='] = $params['starting_from'];
		}


		// Handle search with priority
		if ( ! empty( $params['search'] ) && ! empty( $params['search_fields'] ) ) {
			foreach ( $params['search_fields'] as $field ) {
				$where["{$field}LIKE"] = "%{$params['search']}%";
			}
		}

		return Action_Submission::where( $where, $per_page, $page, $order_by, $order );
	}
}
