<?php
/**
 * BookiFlex NotificationLog Extension
 *
 * @package    BookiFlex
 * @subpackage NotificationLog
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Extensions\NotificationLog\Admin\QueryFilter;

use InvalidArgumentException;

defined('ABSPATH') || exit;

class NotificationLogQueryFilter
{
    private const ALLOWED_ORDER_BY = [
        'send_time',
        'event',
        'stakeholder',
        'status',
        'attempt',
        'created_at',
    ];

    public function __construct(
        public ?string $reservationNumber = null,
        public ?string $status = null,
        public ?string $stakeholder = null,
        public string $orderBy = 'send_time',
        public string $order = 'DESC',
        public int $limit = 20,
        public int $offset = 0,
    ) {
        $this->order = strtoupper($this->order);
        if (!in_array($this->order, ['ASC', 'DESC'], true)) {
            throw new InvalidArgumentException(
                sprintf('Order must be ASC or DESC, got: %s', $order)
            );
        }

        if (!in_array($this->orderBy, self::ALLOWED_ORDER_BY, true)) {
            $this->orderBy = 'send_time';
        }

        if ($this->limit < 0) {
            $this->limit = 0;
        }

        if ($this->offset < 0) {
            $this->offset = 0;
        }

        if ($this->reservationNumber !== null) {
            $this->reservationNumber = trim($this->reservationNumber);
            if ($this->reservationNumber === '') {
                $this->reservationNumber = null;
            }
        }

        if ($this->status !== null) {
            $this->status = trim($this->status);
            if ($this->status === '') {
                $this->status = null;
            }
        }

        if ($this->stakeholder !== null) {
            $this->stakeholder = trim($this->stakeholder);
            if ($this->stakeholder === '') {
                $this->stakeholder = null;
            }
        }
    }
}
