<?php

namespace GriffinForms\Admin\Sql;

class Jobs extends \GriffinForms\Admin\Sql\Format
{
    protected function setTable()
    {
        $this->table = $this->config->getTable('job');
    }

    /**
     * Fetch upcoming jobs for timeline views.
     *
     * @param string $item_type submission|form
     * @param int    $item_id
     * @param array  $args
     * @return array
     */
    public function getJobsForTimeline(string $item_type, int $item_id, array $args = []): array
    {
        $item_type = sanitize_text_field($item_type);
        if ($item_type !== 'submission' && $item_type !== 'form') {
            return [];
        }

        $item_id = (int) $item_id;
        if ($item_id <= 0) {
            return [];
        }

        $statuses = isset($args['statuses']) ? (array) $args['statuses'] : array('pending', 'processing');
        $statuses = array_values(array_filter(array_map('sanitize_text_field', $statuses)));
        if (empty($statuses)) {
            $statuses = array('pending', 'processing');
        }

        $limit = isset($args['limit']) ? (int) $args['limit'] : 20;
        if ($limit <= 0) {
            $limit = 20;
        }

        $offset = isset($args['offset']) ? (int) $args['offset'] : 0;
        if ($offset < 0) {
            $offset = 0;
        }

        $order = isset($args['order']) ? strtolower((string) $args['order']) : 'asc';
        $order = $order === 'desc' ? 'DESC' : 'ASC';

        $time_field = isset($args['time_field']) ? (string) $args['time_field'] : 'available_at';
        $time_field = in_array($time_field, array('available_at', 'created_at'), true) ? $time_field : 'available_at';

        $column = $item_type === 'submission' ? 'submission_id' : 'form_id';

        $placeholders = implode(',', array_fill(0, count($statuses), '%s'));
        $sql = "SELECT * FROM %i WHERE {$column} = %d AND status IN ({$placeholders}) ORDER BY {$time_field} {$order} LIMIT %d OFFSET %d";

        $params = array_merge(array($this->table, $item_id), $statuses, array($limit, $offset));

        global $wpdb;
        $query = $wpdb->prepare($sql, $params);
        $results = $wpdb->get_results($query);

        return is_array($results) ? $results : [];
    }
}

