<?php

declare(strict_types=1);

namespace App\Services;

use App\Contracts\Services\DateTimeServiceInterface;
use Carbon\Carbon;
use DateTimeZone;

final class DateTimeService implements DateTimeServiceInterface
{
    /**
     * Get current datetime in UTC
     */
    public function now(): Carbon
    {
        return Carbon::now('UTC');
    }

    /**
     * Parse datetime string to Carbon instance in UTC
     */
    public function parse(string $datetime, ?string $timezone = null): Carbon
    {
        $parsed = Carbon::parse($datetime, $timezone ?? 'UTC');

        return $parsed->setTimezone('UTC');
    }

    /**
     * Convert UTC datetime to user's timezone
     */
    public function toUserTimezone(Carbon $datetime, string $userTimezone): Carbon
    {
        return $datetime->copy()->setTimezone($userTimezone);
    }

    /**
     * Convert from user's timezone to UTC for storage
     */
    public function toUtc(Carbon $datetime, string $userTimezone): Carbon
    {
        return Carbon::parse($datetime, $userTimezone)->setTimezone('UTC');
    }

    /**
     * Format datetime for display in user's timezone
     */
    public function formatForUser(
        Carbon $datetime,
        string $userTimezone,
        string $format = 'Y-m-d H:i:s'
    ): string {
        return $this->toUserTimezone($datetime, $userTimezone)->format($format);
    }

    /**
     * Validate timezone string
     */
    public function isValidTimezone(string $timezone): bool
    {
        return in_array($timezone, DateTimeZone::listIdentifiers(), true);
    }

    /**
     * Get list of all available timezones
     *
     * @return array<string, string>
     */
    public function getTimezones(): array
    {
        $timezones = [];

        foreach (DateTimeZone::listIdentifiers() as $timezone) {
            $timezones[$timezone] = str_replace('_', ' ', $timezone);
        }

        return $timezones;
    }
}
