<?php




function load_jdf_if_rtl() {
    if (is_rtl()) {
        require_once get_template_directory() . '/inc/jdf.php';
    }
}
add_action('after_setup_theme', 'load_jdf_if_rtl');
function smart_date($format = 'Y/m/d', $timestamp = null) {
    if ($timestamp === null) {
        $timestamp = time();
    }

    if (function_exists('jdate') && is_rtl()) {
        return jdate($format, $timestamp);
    } else {
        return date($format, $timestamp);
    }
}




function caffito_get_tehran_now() {

    $cached = get_transient('caffito_tehran_now_ts');
    if ($cached) {
        try {
            $tz  = new DateTimeZone('+03:30');
            $dt  = (new DateTime('@' . (int)$cached))->setTimezone($tz);
            return $dt;
        } catch (Exception $e) {}
    }

    $resp = wp_remote_get('https://worldtimeapi.org/api/timezone/Asia/Tehran', [
        'timeout' => 3,
        'headers' => ['Accept' => 'application/json'],
    ]);

    if (!is_wp_error($resp) && wp_remote_retrieve_response_code($resp) === 200) {
        $body = wp_remote_retrieve_body($resp);
        $data = json_decode($body, true);

        if (!empty($data['datetime'])) {
            try {
                $dt = new DateTime($data['datetime']);
                set_transient('caffito_tehran_now_ts', $dt->getTimestamp(), 30);
                return $dt;
            } catch (Exception $e) {}
        } elseif (!empty($data['unixtime'])) {
            try {
                $tz = new DateTimeZone('+03:30');
                $dt = (new DateTime('@' . (int)$data['unixtime']))->setTimezone($tz);
                set_transient('caffito_tehran_now_ts', $dt->getTimestamp(), 30);
                return $dt;
            } catch (Exception $e) {}
        }
    }

    try {
        $tz = new DateTimeZone('+03:30');
        return new DateTime('now', $tz);
    } catch (Exception $e) {
        return new DateTime();
    }
}
function caffito_tehran_minutes_now() {
    $now = caffito_get_tehran_now();
    return ((int)$now->format('H')) * 60 + (int)$now->format('i');
}


