<?php

namespace GriffinForms\Admin\Sql;

class Files extends \GriffinForms\Admin\Sql\Lists
{
    protected function setSearchColumns()
    {
        $this->search_columns = array(
            'url',
            'mime'
        );
    }

    /**
     * Return an array of unique MIME types stored in the files table.
     *
     * @return array
     */
    public function getUniqueMimeTypes()
    {
        global $wpdb;
        $table = $this->table;
        $query = $wpdb->prepare(
            "SELECT DISTINCT mime FROM %i WHERE mime IS NOT NULL AND mime <> '' ORDER BY mime ASC",
            $table
        );
        $results = $wpdb->get_col($query);
        if (!is_array($results)) {
            return array();
        }
        return array_map('sanitize_text_field', $results);
    }

    /**
     * Return an associative array of unique statuses and their record counts.
     *
     * @return array status => count
     */
    public function getUniqueStatusesWithCount()
    {
        global $wpdb;
        $table = $this->table;
        $query = $wpdb->prepare(
            "SELECT status, COUNT(*) as count FROM %i WHERE status IS NOT NULL AND status <> '' GROUP BY status ORDER BY status ASC",
            $table
        );
        $results = $wpdb->get_results($query, ARRAY_A);
        if (!is_array($results)) {
            return array();
        }

        $output = array();
        foreach ($results as $row) {
            $status = sanitize_text_field($row['status']);
            $count  = (int) $row['count'];
            $output[$status] = $count;
        }

        return $output;
    }

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

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

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

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

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

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

    protected function sizeMinQuery($type, &$params)
    {
        $params[] = $type;
        return 'size_bytes > %d';
    }
}