<?php

namespace App\Libraries;

/**
 * Single source of truth for Egypt (Africa/Cairo) wall-clock time across the booking site.
 * DST and rule changes are applied via PHP's IANA timezone database — no manual +1 hour hacks.
 */
class EgyptTime
{
    public const TZ_ID = 'Africa/Cairo';

    public static function timezone(): \DateTimeZone
    {
        static $tz = null;

        return $tz ??= new \DateTimeZone(self::TZ_ID);
    }

    /** Ensure date(), strtotime(), and CI time helpers use Egypt. */
    public static function ensurePhpDefault(): void
    {
        date_default_timezone_set(self::TZ_ID);
    }

    /**
     * @param string $time "now", "2026-05-21 09:26", "+1 day", etc.
     */
    public static function parse(string $time = 'now'): \DateTime
    {
        return new \DateTime($time, self::timezone());
    }

    public static function nowSql(): string
    {
        return self::parse('now')->format('Y-m-d H:i:s');
    }

    public static function today(): string
    {
        return self::parse('now')->format('Y-m-d');
    }

    /**
     * Normalize a calendar date or datetime string to Y-m-d in Egypt.
     */
    public static function toDateString(string $dateOrDatetime): string
    {
        return self::parse($dateOrDatetime)->format('Y-m-d');
    }

    /**
     * Admin form / flatpickr value: store the wall-clock time the user entered (Cairo).
     */
    public static function wallClock(?string $value): ?string
    {
        if ($value === null || trim($value) === '') {
            return null;
        }

        $value = trim($value);
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
            $value .= ' 00:00:00';
        } elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {
            $value .= ':00';
        }

        try {
            return self::parse($value)->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return $value;
        }
    }

    public static function addMinutesSql(int $minutes, string $from = 'now'): string
    {
        $copy = clone self::parse($from);
        $copy->modify('+' . $minutes . ' minutes');

        return $copy->format('Y-m-d H:i:s');
    }

    /** MySQL session offset e.g. +02:00 or +03:00 when DST applies. */
    public static function mysqlOffset(): string
    {
        return self::parse('now')->format('P');
    }

    public static function syncMysqlTimezone(): void
    {
        try {
            $db = \Config\Database::connect();
            $offset = self::mysqlOffset();
            $db->query("SET time_zone = '{$offset}'");
        } catch (\Throwable $e) {
            // ignore
        }
    }
}
