<?php
namespace Dreamfox\DeliveryDate\Helpers;

use DateTime;

class DateHelper
{

  public static function toJsDate($dateString) {
    $pattern = array(
          //day
          'd', //day of the month
          'j', //3 letter name of the day
          'l', //full name of the day
          'z', //day of the year
          //month
          'F', //Month name full
          'M', //Month name short
          'n', //numeric month no leading zeros
          'm', //numeric month leading zeros
          //year
          'Y', //full numeric year
          'y' //numeric year: 2 digit
        );
    $replace = array(
      'dd', 'd', 'DD', 'o',
      'MM', 'M', 'm', 'mm',
      'yy', 'y'
    );
    foreach ($pattern as &$p) {
      $p = '/' . $p . '/';
    }
    return preg_replace($pattern, $replace, $dateString);
  }

  public static function getJsDateFormat($dateText)
  {
    return self::toJsDate($dateText);
  }

  public static function createDateRange($first, $last, $step = '+1 day', $format = 'Y-m-d') {
    $dates    = array();
    $timezone = function_exists( 'wp_timezone' ) ? wp_timezone() : new \DateTimeZone( 'UTC' );

    $current = date_create( $first, $timezone );
    $lastDt  = date_create( $last, $timezone );
    if ( ! $current || ! $lastDt ) {
      return $dates;
    }

    while ( $current <= $lastDt ) {
      $dates[] = $current->format( $format );
      $current->modify( $step );
    }
    return $dates;
  }

  public static function toDateYmd($dateText)
  {
    if ( empty( $dateText ) ) {
      return '';
    }

    // d/m/Y  →  Y-m-d
    $parts = explode( '/', $dateText );
    if ( count( $parts ) === 3 && isset( $parts[0], $parts[1], $parts[2] ) ) {
      return sprintf( '%s-%s-%s', $parts[2], $parts[1], $parts[0] );
    }

    // Already Y-m-d
    if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $dateText ) ) {
      return $dateText;
    }

    // d-m-Y  →  Y-m-d
    $parts = explode( '-', $dateText );
    if ( count( $parts ) === 3 && strlen( $parts[0] ) <= 2 ) {
      return sprintf( '%s-%s-%s', $parts[2], $parts[1], $parts[0] );
    }

    // Fallback: let PHP parse it
    $dt = date_create( $dateText );
    return $dt ? $dt->format( 'Y-m-d' ) : $dateText;
  }

  public static function toJsDateObject($year, $month, $day)
  {
    return sprintf('new Date(%s, %s, %s)', $year, $month, $day);
  }
}