<?php

namespace Licenzo\Services\Logging\Concerns;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use DateTime;

/**
 * Trait ParsesDateTime
 *
 * Parses various datetime formats including relative strings
 */
trait ParsesDateTime
{
    /**
     * Parse datetime value to MySQL format
     *
     * @param string|DateTime|int $value
     * @return string
     */
    protected static function parseDateTime($value): string
    {
        // Already a DateTime object
        if ($value instanceof DateTime) {
            return $value->format('Y-m-d H:i:s');
        }

        // Unix timestamp
        if (is_int($value)) {
            return gmdate('Y-m-d H:i:s', $value);
        }

        // String value
        if (is_string($value)) {
            // Handle relative formats like '+30 days', '-1 week'
            if (str_starts_with($value, '+') || str_starts_with($value, '-')) {
                return gmdate('Y-m-d H:i:s', strtotime($value));
            }

            // Handle 'now'
            if (strtolower($value) === 'now') {
                return gmdate('Y-m-d H:i:s');
            }

            // Try to parse as date string
            $timestamp = strtotime($value);
            if ($timestamp !== false) {
                return gmdate('Y-m-d H:i:s', $timestamp);
            }
        }

        // Fallback to current time
        return gmdate('Y-m-d H:i:s');
    }

    /**
     * Parse date value to MySQL date format
     *
     * @param string|DateTime|int $value
     * @return string
     */
    protected static function parseDate($value): string
    {
        // Already a DateTime object
        if ($value instanceof DateTime) {
            return $value->format('Y-m-d');
        }

        // Unix timestamp
        if (is_int($value)) {
            return gmdate('Y-m-d', $value);
        }

        // String value
        if (is_string($value)) {
            // Handle relative formats
            if (str_starts_with($value, '+') || str_starts_with($value, '-')) {
                return gmdate('Y-m-d', strtotime($value));
            }

            // Try to parse as date string
            $timestamp = strtotime($value);
            if ($timestamp !== false) {
                return gmdate('Y-m-d', $timestamp);
            }
        }

        // Fallback to current date
        return gmdate('Y-m-d');
    }
}

