<?php
// includes/jdatetime.php - کتابخانه تبدیل تاریخ

class JDateTime {
    
    public static function gregorianToJalali($gy, $gm, $gd) {
        $g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
        $j_d_m = [0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30];
        
        $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];
        $days = $days - 226899;
        $jz = (int)($days / 12053);
        $days %= 12053;
        $jy = (int)(($days - 1) / 365) + (1 + $jz * 4);
        $days = ($days - 1) % 365;
        $jm = 1;
        for ($i = 0; $i < 12; $i++) {
            if ($days < $j_d_m[$i]) break;
            $days -= $j_d_m[$i];
            $jm++;
        }
        $jd = $days + 1;
        
        return [$jy, $jm, $jd];
    }
    
    public static function toJalali($date, $format = 'Y/m/d') {
        if (empty($date)) return '-';
        
        // حذف زمان
        $dateParts = explode(' ', trim($date));
        $dateStr = $dateParts[0];
        $timeStr = isset($dateParts[1]) ? $dateParts[1] : '';
        
        // تجزیه تاریخ میلادی
        $parts = explode('-', $dateStr);
        if (count($parts) != 3) return $dateStr;
        
        $gy = (int)$parts[0];
        $gm = (int)$parts[1];
        $gd = (int)$parts[2];
        
        if ($gy < 1900 || $gy > 2100 || $gm < 1 || $gm > 12 || $gd < 1 || $gd > 31) {
            return $dateStr;
        }
        
        list($jy, $jm, $jd) = self::gregorianToJalali($gy, $gm, $gd);
        
        // ساخت خروجی
        $output = '';
        for ($i = 0; $i < strlen($format); $i++) {
            $char = $format[$i];
            if ($char == 'Y') $output .= $jy;
            elseif ($char == 'y') $output .= substr($jy, -2);
            elseif ($char == 'm') $output .= str_pad($jm, 2, '0', STR_PAD_LEFT);
            elseif ($char == 'n') $output .= $jm;
            elseif ($char == 'd') $output .= str_pad($jd, 2, '0', STR_PAD_LEFT);
            elseif ($char == 'j') $output .= $jd;
            else $output .= $char;
        }
        return $output;
    }
}
?>