<?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 );
	}

	/**
	 * Deletes one submission by ID and action ID.
	 *
	 * @param int $action_id Action ID.
	 * @param int $id        Submission ID.
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	public function delete( int $action_id, int $id ): bool {
		return Action_Submission::delete(
			[
				'id'        => $id,
				'action_id' => $action_id,
			]
		);
	}

	/**
	 * Batch deletes submissions by IDs and action ID.
	 *
	 * @param int   $action_id Action ID.
	 * @param int[] $ids       Submission IDs.
	 *
	 * @return bool
	 * @since 1.0.0
	 */
	public function batch_delete( int $action_id, array $ids ): bool {
		if ( empty( $ids ) ) {
			return false;
		}

		return Action_Submission::delete(
			[
				'id'        => $ids,
				'action_id' => $action_id,
			]
		);
	}
}
