<?php
/**
 * Copyright (C) 2023  Jaap Jansma (jaap.jansma@civicoop.org)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

class CRM_Dataprocessor_Utils_Date {

  /**
   * Returns the date values from a submitted date.
   *
   * @param array $submittedValues
   * @return array|null
   */
  public static function getDateFilterFromSubmittedValues(array $submittedValues):? array {
    $relative = CRM_Utils_Array::value("relative", $submittedValues);
    $from = CRM_Utils_Array::value("from", $submittedValues);
    $to = CRM_Utils_Array::value("to", $submittedValues);
    $fromTime = CRM_Utils_Array::value("from_time", $submittedValues);
    $toTime = CRM_Utils_Array::value("to_time", $submittedValues);
    if (!$toTime) {
      $toTime = '235959';
    }

    if ($relative == 'null') {
      return null;
    } else {
      [$from, $to] = CRM_Utils_Date::getFromTo($relative, $from, $to, $fromTime, $toTime);
    }
    if ($from) {
      $from = substr($from, 0, 8);
    }
    if ($to) {
      $to = substr($to, 0, 8);
    }
    if ($from && $to) {
      return [
        'op' => 'BETWEEN',
        'value' => array($from, $to),
      ];
    } elseif ($from) {
      return [
        'op' => '>=',
        'value' => $from,
      ];
    } elseif ($to) {
      return [
        'op' => '<=',
        'value' => $to,
      ];
    }
    return NULL;
  }

}
