<?php
/*
Theme Designed By: Meysam Hosseinkhani
Email: Meysam98@Gmail.com
Demo Website: dinakala.i-design.ir
Author Website: i-design.ir
*/

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) )
    exit;

// dina_jalali_to_gregorian
function dina_jalali_to_gregorian( $jy, $jm, $jd ) {
    $g_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    $j_days_in_month = [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29];

    $jy = (int) $jy - 979;
    $jm = (int) $jm - 1;
    $jd = (int) $jd - 1;

    $j_day_no = 365 * $jy + (int)($jy / 33) * 8 + (int)(($jy % 33 + 3) / 4);
    for ( $i = 0; $i < $jm; ++$i ) {
        $j_day_no += $j_days_in_month[$i];
    }
    $j_day_no += $jd;

    $g_day_no = $j_day_no + 79;

    $gy = 1600 + 400 * (int)($g_day_no / 146097);
    $g_day_no = $g_day_no % 146097;

    $leap = true;
    if ( $g_day_no >= 36525 ) {
        $g_day_no--;
        $gy += 100 * (int)($g_day_no / 36524);
        $g_day_no = $g_day_no % 36524;

        if ( $g_day_no >= 365 ) {
            $g_day_no++;
        } else {
            $leap = false;
        }
    }

    $gy += 4 * (int)($g_day_no / 1461);
    $g_day_no %= 1461;

    if ( $g_day_no >= 366 ) {
        $leap = false;
        $g_day_no--;
        $gy += (int)($g_day_no / 365);
        $g_day_no = $g_day_no % 365;
    }

    for ( $i = 0; $g_day_no >= $g_days_in_month[$i] + ( $i == 1 && $leap ); $i++ ) {
        $g_day_no -= $g_days_in_month[$i] + ( $i == 1 && $leap ? 1 : 0 );
    }

    $gm = $i + 1;
    $gd = $g_day_no + 1;

    return [ $gy, $gm, $gd ];
}

// dina_jalali_date_to_gregorian_string
function dina_jalali_date_to_gregorian_string( $jalali_date ) {
    $separator = strpos( $jalali_date, '/' ) !== false ? '/' : '-';

    list( $jy, $jm, $jd ) = explode( $separator, $jalali_date );

    list( $gy, $gm, $gd ) = dina_jalali_to_gregorian( (int)$jy, (int)$jm, (int)$jd );

    return sprintf( '%04d-%02d-%02d', $gy, $gm, $gd );
}

// dina_is_jalali_date
function dina_is_jalali_date( $date_string ) {
    $pattern = '/^1[34][0-9]{2}[\/\-][01][0-9][\/\-][0-3][0-9]$/';
    return preg_match($pattern, $date_string) === 1;
}