<?php

namespace Limb_Chatbot\Includes\Repositories;

use Exception;
use Limb_Chatbot\Includes\Data_Objects\Chatbot_User;
use Limb_Chatbot\Includes\Services\Data_Object_Collection;

/**
 * Repository class for managing chatbot users.
 *
 * @since 1.0.0
 */
class Chatbot_User_Repository {

	/**
	 * Creates a new Chatbot_User record.
	 *
	 * @param  int|null  $wp_user_id  WordPress user ID associated with the chatbot user.
	 * @param  string  $ip_address  IP address of the user.
	 * @param  string  $device_uuid  Unique identifier for the user's device.
	 * @param  string|null  $type  Type of chatbot user (e.g., guest, registered).
	 *
	 * @return Chatbot_User The created chatbot user instance.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function create( $wp_user_id, $ip_address, $device_uuid, $type, $status = Chatbot_User::STATUS_ACTIVE ) {
		return Chatbot_User::create( [
			'wp_user_id'  => $wp_user_id,
			'ip'          => $ip_address,
			'device_uuid' => $device_uuid,
			'type'        => $type,
			'status'      => $status
		] );
	}

	/**
	 * Retrieves a collection of chatbot users based on given parameters.
	 *
	 * Supports filtering, search, ordering, and pagination.
	 * Parameters are expected to be already sanitized and validated by the controller.
	 *
	 * @param  array  $params  Query parameters (already sanitized and validated).
	 *
	 * @return Data_Object_Collection Collection of Chatbot_User objects.
	 * @since 1.0.0
	 */
	public function get_items( array $params = [] ): Data_Object_Collection {
		$where = [];

		// Filter by type
		if ( isset( $params['type'] ) ) {
			$where['type'] = $params['type'];
		}

		// Filter by status
		if ( isset( $params['status'] ) ) {
			$where['status'] = $params['status'];
		}

		// Filter by wp_user_id
		if ( isset( $params['wp_user_id'] ) ) {
			$where['wp_user_id'] = $params['wp_user_id'];
		}

		// Filter by uuid
		if ( ! empty( $params['uuid'] ) ) {
			$where['uuid'] = $params['uuid'];
		}

		// Filter by device_uuid
		if ( ! empty( $params['device_uuid'] ) ) {
			$where['device_uuid'] = $params['device_uuid'];
		}

		// Search functionality
		if ( ! empty( $params['search'] ) && ! empty( $params['search_fields'] ) ) {
			$search_term   = $params['search'];
			$search_fields = $params['search_fields'];

			if ( is_array( $search_fields ) && ! empty( $search_fields ) ) {
				// Use the first search field for the query
				// More complex OR conditions would require custom SQL
				$first_field                 = $search_fields[0];
				$where["{$first_field}LIKE"] = "%{$search_term}%";
			}
		}

		// Date range filters
		if ( ! empty( $params['start_date'] ) || ! empty( $params['created_at>='] ) ) {
			$date                  = ! empty( $params['start_date'] ) ? $params['start_date'] : $params['created_at>='];
			$where['created_at>='] = $date;
		}

		if ( ! empty( $params['end_date'] ) || ! empty( $params['created_at<='] ) ) {
			$date                  = ! empty( $params['end_date'] ) ? $params['end_date'] : $params['created_at<='];
			$where['created_at<='] = $date;
		}

		// Handle ordering (already validated by controller)
		$order_by = $params['orderby'] ?? 'created_at';
		$order    = strtoupper( $params['order'] ?? 'DESC' );

		// Handle pagination (already validated by controller)
		$per_page = $params['per_page'] ?? 10;
		$page     = $params['page'] ?? 1;

		// Use Chatbot_User::where() with pagination and ordering
		$collection = Chatbot_User::where( $where, $per_page, $page, $order_by, $order );
		$total      = Chatbot_User::count( $where );
		$collection->set_total( $total );

		return $collection;
	}

	/**
	 * Retrieves a single chatbot user by ID.
	 *
	 * @param  int  $id  Chatbot user ID.
	 *
	 * @return Chatbot_User|null The Chatbot_User object or null if not found.
	 * @since 1.0.0
	 */
	public function get_item( int $id ): ?Chatbot_User {
		return Chatbot_User::find( $id );
	}
}