<?php
/**
 * Live Traffic Filter Collection
 *
 * @package VMPFence
 * @subpackage Tools
 * @since 2.1.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class VMPFence_Live_Traffic_Filter_Collection
 *
 * Manages a collection of filters for live traffic queries
 *
 * @since 2.1.0
 */
class VMPFence_Live_Traffic_Filter_Collection {

    /**
     * Array of filter objects
     * @var array
     */
    private $filters = array();

    /**
     * Constructor
     *
     * @since 2.1.0
     */
    public function __construct() {
        $this->filters = array();
    }

    /**
     * Add filter to collection
     *
     * @since 2.1.0
     * @param VMPFence_Live_Traffic_Filter $filter Filter object
     * @return void
     */
    public function addFilter($filter) {
        if ($filter instanceof VMPFence_Live_Traffic_Filter) {
            $this->filters[] = $filter;
        }
    }

    /**
     * Remove filter from collection
     *
     * @since 2.1.0
     * @param VMPFence_Live_Traffic_Filter $filter Filter object to remove
     * @return void
     */
    public function removeFilter($filter) {
        $key = array_search($filter, $this->filters, true);
        if ($key !== false) {
            unset($this->filters[$key]);
            // Re-index array
            $this->filters = array_values($this->filters);
        }
    }

    /**
     * Get all filters
     *
     * @since 2.1.0
     * @return array Array of filter objects
     */
    public function getFilters() {
        return $this->filters;
    }

    /**
     * Set filters (replace all)
     *
     * @since 2.1.0
     * @param array $filters Array of filter objects
     * @return void
     */
    public function setFilters($filters) {
        $this->filters = array();
        foreach ($filters as $filter) {
            if ($filter instanceof VMPFence_Live_Traffic_Filter) {
                $this->filters[] = $filter;
            }
        }
    }

    /**
     * Get count of filters
     *
     * @since 2.1.0
     * @return int Number of filters
     */
    public function count() {
        return count($this->filters);
    }

    /**
     * Convert all filters to SQL WHERE clause
     *
     * Combines multiple filters with AND operator
     *
     * @since 2.1.0
     * @return string Combined SQL WHERE clause
     */
    public function toSQL() {
        if (empty($this->filters)) {
            return '';
        }

        $sqlFragments = array();

        foreach ($this->filters as $filter) {
            $sql = $filter->toSQL();
            if (!empty($sql)) {
                $sqlFragments[] = $sql;
            }
        }

        if (empty($sqlFragments)) {
            return '';
        }

        $result = '(' . implode(' AND ', $sqlFragments) . ')';
        return $result;
    }

    /**
     * Clear all filters
     *
     * @since 2.1.0
     * @return void
     */
    public function clear() {
        $this->filters = array();
    }
}
