<?php

// Prevent direct script access
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

// Set timezone early and ensure it's a valid string
$default_timezone = 'Asia/Tehran';
@date_default_timezone_set($default_timezone);

// --- Date & Time Helper Functions ---

/**
 * Converts a Gregorian timestamp string (or null for current time) to Jalali date and time string.
 */
function to_jalali_datetime(?string $timestamp_str = null): string
{
    $timestamp = time(); // Default to now
    if ($timestamp_str !== null) {
        $parsed_timestamp = strtotime($timestamp_str);
        if ($parsed_timestamp === false) {
            if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Warning: Invalid timestamp string '{$timestamp_str}' passed to to_jalali_datetime.\n", FILE_APPEND); }
             return 'تاریخ نامعتبر';
        }
        $timestamp = $parsed_timestamp;
    }

    // Use bundled jdate function if available (more reliable)
    if (function_exists('jdate')) {
        try {
            $timezone = 'Asia/Tehran'; // Explicitly set timezone for jdate
            // Use 'en' digits internally for consistency, convert to fa later if needed
            return jdate('Y/m/d ساعت H:i', $timestamp, '', $timezone, 'en');
        } catch (Exception $e) {
            if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error using jdate function: " . $e->getMessage() . "\n", FILE_APPEND); }
            // Fallback to manual conversion if jdate fails
        }
    }

    // --- Manual fallback conversion ---
    // Ensure gregorian_to_jalali is defined before calling
     if (!function_exists('gregorian_to_jalali')) {
         if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error: gregorian_to_jalali function not found for fallback.\n", FILE_APPEND); }
         return 'خطا در تبدیل تاریخ';
     }

    list($j_y, $j_m, $j_d) = gregorian_to_jalali(date('Y', $timestamp), date('m', $timestamp), date('d', $timestamp));
    $date_str = sprintf('%04d/%02d/%02d', $j_y, $j_m, $j_d);
    $time_str = date('H:i', $timestamp);

    // Combine English digits first
    $final_str_en = $date_str . ' ساعت ' . $time_str;

    // Convert result to Persian digits just before returning
    $persian_digits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    $english_digits = range(0, 9);
    return str_replace($english_digits, $persian_digits, $final_str_en);
}


/**
 * Converts a Gregorian date to Jalali date (corrected implementation).
 * Source: https://jdf.scr.ir (or similar standard conversion logic)
 */
if (!function_exists('gregorian_to_jalali')) {
    function gregorian_to_jalali($gy, $gm, $gd, $mod = '') {
         $g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
         $gy = (int)$gy; // Ensure integer type
         $gm = (int)$gm;
         $gd = (int)$gd;
         $gy2 = ($gm > 2) ? ($gy + 1) : $gy;
         $days = 355666 + (365 * $gy) + ((int)(($gy2 + 3) / 4)) - ((int)(($gy2 + 99) / 100)) + ((int)(($gy2 + 399) / 400)) + $gd + $g_d_m[$gm - 1];
         $jy = -1595 + (33 * ((int)($days / 12053)));
         $days %= 12053;
         $jy += 4 * ((int)($days / 1461));
         $days %= 1461;

         // --- Corrected logic for leap year check within conversion ---
         $leap = 0;
         if ($days > 365) {
             $jy += (int)(($days - 1) / 365);
             $days = ($days - 1) % 365;
             $leap = ($days == 0); // Check if it ended exactly on the leap day
         }
         

         if (!$leap && $days === 365) {
              $days = 0;
              $jy++;
         }
         // -----------------------------------------------------------

         $jm = ($days < 186) ? 1 + (int)($days / 31) : 7 + (int)(($days - 186) / 30);
         $jd = 1 + (($days < 186) ? ($days % 31) : (($days - 186) % 30));
         return ($mod == '') ? [$jy, $jm, $jd] : $jy . $mod . $jm . $mod . $jd;
    }
} // <-- Added missing closing brace for if (!function_exists('gregorian_to_jalali'))

/**
 * Fallback jdate function (corrected).
 */
if (!function_exists('jdate')) {
    function jdate($format, $timestamp = null, $none = '', $time_zone = 'Asia/Tehran', $tr_num = 'fa') {
        $timestamp = ($timestamp === null) ? time() : (is_numeric($timestamp) ? (int)$timestamp : strtotime($timestamp)); // Ensure timestamp is int or false
        if($timestamp === false) { return ''; } // Handle invalid input timestamp

        $original_tz = @date_default_timezone_get(); // Get current setting safely
        $tz_to_set = ($time_zone && is_string($time_zone)) ? $time_zone : 'Asia/Tehran'; // Default if null or invalid
        @date_default_timezone_set($tz_to_set);

        // Get Gregorian date parts for conversion
        $gy = (int)date('Y', $timestamp);
        $gm = (int)date('m', $timestamp);
        $gd = (int)date('d', $timestamp);
        // Other parts needed for format replacement
        $H = date('H', $timestamp);
        $i = date('i', $timestamp);
        $s = date('s', $timestamp);
        $L = date('L', $timestamp); // Gregorian leap year status

        // Restore original timezone
        if ($original_tz && is_string($original_tz)) {
             @date_default_timezone_set($original_tz);
        }

        // Convert to Jalali
        list($j_y, $j_m, $j_d) = gregorian_to_jalali($gy, $gm, $gd);

        // Basic replacements
        $replacements = [
            'Y' => $j_y,
            'm' => sprintf('%02d', $j_m),
            'd' => sprintf('%02d', $j_d),
            'H' => $H,
            'i' => $i,
            's' => $s,
            'y' => substr((string)$j_y, -2), // Get last two digits of Jalali year
             // Approximate Jalali leap year status (more accurate check is complex)
            'L' => in_array($j_y % 33, [1, 5, 9, 13, 17, 22, 26, 30]) ? 1 : 0
        ];

        $output = strtr((string)$format, $replacements); // Ensure format is string

        // Convert digits if requested
        if ($tr_num === 'fa') {
            $persian_digits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
            $english_digits = range(0, 9);
            $output = str_replace($english_digits, $persian_digits, $output);
        }

        return $output;
    }
} // <-- Correct closing brace location for if (!function_exists('jdate'))

?>