import dayjs from 'dayjs';

/**
 * Convert PHP-style date format to dayjs format
 * @param {string} phpFormat - e.g., 'd M, Y'
 * @returns {string} dayjs format
 */
const phpToDayjsFormat = (phpFormat) => {
  const formatMap = {
    d: 'DD',
    j: 'D',
    M: 'MMM',
    m: 'MM',
    Y: 'YYYY',
    y: 'YY',
  };

  return phpFormat.replace(/[dMjmyY]/g, match => formatMap[match] || match);
};

/**
 * Format a date string using a PHP-style format
 * @param {string|Date} date - ISO date string or JS Date
 * @param {string} format - PHP-style format, e.g., 'd M, Y'
 * @returns {string} formatted date
 */
export const formatDate = (date, format = 'd-m-Y') => {
  if (!date) return '';

  const dayjsFormat = phpToDayjsFormat(format);

  return dayjs(date).format(dayjsFormat);
};
