<?php

namespace GriffinForms\Admin\Sql;

class Logs extends \GriffinForms\Admin\Sql\Lists
{
    protected function setSearchColumns()
    {
        $this->search_columns = array(
            'log_type',
            'category',
            'item_type',
            'message'
        );
    }

    /**
     * Get counts of logs grouped by log_type.
     *
     * @return array log_type => count
     */
    public function getLogTypeCounts(): array
    {
        global $wpdb;

        $sql = "SELECT log_type, COUNT(*) AS count FROM %i GROUP BY log_type";
        $results = $wpdb->get_results(
            $wpdb->prepare($sql, $this->table),
            ARRAY_A
        );

        $counts = [];
        if ($results) {
            foreach ($results as $row) {
                $counts[$row['log_type']] = (int) $row['count'];
            }
        }

        return $counts;
    }

    /**
     * Get distinct item types present in logs.
     *
     * @return array List of item_type strings
     */
    public function getDistinctItemTypes(): array
    {
        global $wpdb;

        $sql = "SELECT DISTINCT item_type FROM %i ORDER BY item_type ASC";
        $rows = $wpdb->get_col($wpdb->prepare($sql, $this->table));

        if (!is_array($rows)) {
            return array();
        }
        // Normalize to strings and drop empties
        $rows = array_filter(array_map('strval', $rows));
        return array_values($rows);
    }

    protected function dateFromQuery($date_from, &$params)
    {
        $params[] = $date_from;
        return 'date_time >= %s';
    }

    protected function dateToQuery($date_to, &$params)
    {
        $params[] = $date_to;
        return 'date_time <= %s';
    }

    protected function datesQuery($dates, &$params)
    {
        $params[] = $dates['from'];
        $params[] = $dates['to'];
        return 'date_time BETWEEN %s AND %s';
    }

    protected function typeQuery($type, &$params)
    {
        $params[] = $type;
        return 'log_type = %s';
    }

    protected function itemTypeQuery($item_type, &$params)
    {
        $params[] = $item_type;
        return 'item_type = %s';
    }
}