<?php

namespace App\Helpers;

use App\Models\Holiday;
use DateTime;

class DateHelper {
    public static function traducirFecha($fecha) {
        $meses = [
            'Jan' => 'Ene', 'Feb' => 'Feb', 'Mar' => 'Mar', 'Apr' => 'Abr', 'May' => 'May', 'Jun' => 'Jun',
            'Jul' => 'Jul', 'Aug' => 'Ago', 'Sep' => 'Sep', 'Oct' => 'Oct', 'Nov' => 'Nov', 'Dec' => 'Dic'
        ];

        $fecha_en = date('d M, Y - h:i A', strtotime($fecha));
        return str_replace(array_keys($meses), array_values($meses), $fecha_en);
    }

    public static function getPeruHolidays($year)
    {

        return Holiday::allDatesForYear($year);
    }

    public static function getValidEntryDate()
    {
        $now = new DateTime();
        $year = $now->format('Y');
        $holidays = self::getPeruHolidays($year);

        while (
            in_array($now->format('Y-m-d'), $holidays) ||
            in_array($now->format('N'), ['6', '7']) // 6=sábado, 7=domingo
        ) {
            $now->modify('+1 day');
            $now->setTime(0, 0, 0);
        }

        return $now->format('Y-m-d H:i:s');
    }

    public static function countBusinessDays($startDate, $endDate)
    {
        $startYear = (int)$startDate->format('Y');
        $endYear = (int)$endDate->format('Y');

        $holidays = [];

        for ($year = $startYear; $year <= $endYear; $year++) {
            $holidays = array_merge($holidays, self::getPeruHolidays($year));
        }

        $holidays = array_unique($holidays);

        $current = clone $startDate;
        $businessDays = 0;

        while ($current <= $endDate) {
            $isWeekend = in_array($current->format('N'), ['6', '7']);
            $isHoliday = in_array($current->format('Y-m-d'), $holidays);

            if (!$isWeekend && !$isHoliday) {
                $businessDays++;
            }

            $current->modify('+1 day');
        }

        return $businessDays;
    }

    public static function adjustToBusinessDate($date): DateTime
    {
        if (!$date instanceof DateTime) {
            $date = new DateTime($date);
        }

        $year = (int)$date->format('Y');
        $holidays = array_merge(
            self::getPeruHolidays($year),
            self::getPeruHolidays($year + 1)
        );

        $wasAdjusted = false;

        while (
            in_array($date->format('Y-m-d'), $holidays) ||
            in_array($date->format('N'), ['6', '7'])
        ) {
            $date->modify('+1 day');
            $wasAdjusted = true;
        }

        if ($wasAdjusted) {
            $date->setTime(0, 0, 0);
        }

        return $date;
    }

}
