<?php
// includes/jalali_simple.php - تبدیل تاریخ میلادی به شمسی با الگوریتم استاندارد

function gregorianToJalali($g_y, $g_m, $g_d) {
    $g_days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    $j_days_in_month = array(31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29);

    $gy = $g_y - 1600;
    $gm = $g_m - 1;
    $gd = $g_d - 1;

    $g_day_no = 365 * $gy + (int)(($gy + 3) / 4) - (int)(($gy + 99) / 100) + (int)(($gy + 399) / 400);

    for ($i = 0; $i < $gm; ++$i) {
        $g_day_no += $g_days_in_month[$i];
    }

    if ($gm > 1 && (($gy % 4 == 0 && $gy % 100 != 0) || ($gy % 400 == 0))) {
        $g_day_no++;
    }

    $g_day_no += $gd;

    $j_day_no = $g_day_no - 79;

    $j_np = (int)($j_day_no / 12053);
    $j_day_no %= 12053;

    $jy = 979 + 33 * $j_np + 4 * (int)($j_day_no / 1461);
    $j_day_no %= 1461;

    if ($j_day_no >= 366) {
        $jy += (int)(($j_day_no - 1) / 365);
        $j_day_no = ($j_day_no - 1) % 365;
    }

    for ($i = 0; $i < 11 && $j_day_no >= $j_days_in_month[$i]; ++$i) {
        $j_day_no -= $j_days_in_month[$i];
    }

    $jm = $i + 1;
    $jd = $j_day_no + 1;

    return array($jy, $jm, $jd);
}

function toJalali($date, $format = 'Y/m/d') {
    if (empty($date)) return '-';

    $dateParts = explode(' ', trim($date));
    $dateStr = $dateParts[0];
    $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) return $dateStr;

    list($jy, $jm, $jd) = 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;
}
?>