<?php
namespace App\Helpers; // Or a more specific namespace if needed

use Carbon\Carbon;

class DateHelper {
    
    public static function isDatetime($value)
    {
        try {
            Carbon::parse($value);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /*
     * function dateRange adminATL
     * 
     */
    public static function dateRange($dateRange, $reqDateType=""/*start or end*/){
        if($dateRange==""){
            return NULL;
        }

        // init dateTimeStart and dateTimeEnd
        $dateStartArr = trim(explode("-", $dateRange)[0]);
        $dateEndArr = trim(explode("-", $dateRange)[1]);

        if($reqDateType=="start"){
            if(isDateTimeUnlimited($dateStartArr)){
                return;
            }
            $dateStart = new DateTime($dateStartArr);
            return $dateStart->format('Y-m-d H:i:s');
        }else if($reqDateType=="end"){
            if(isDateTimeUnlimited($dateEndArr)){
                return;
            }
            $dateEnd = new DateTime($dateEndArr);
            return $dateEnd->format('Y-m-d H:i:s');
        }else if($reqDateType==""){
            if(!isDateTimeUnlimited($dateStartArr) && !isDateTimeUnlimited($dateEndArr)){
                $dateStart = new DateTime($dateStartArr);
                $dateEnd = new DateTime($dateEndArr);
                $result = $dateStart->format('M jS,Y H:i:s')." - ".$dateEnd->format('M jS,Y H:i:s');
            }else if(isDateTimeUnlimited($dateStartArr) && !isDateTimeUnlimited($dateEndArr)){
                $dateStart = $dateStartArr;
                $dateEnd = new DateTime($dateEndArr);
                $result = $dateStart." - ".$dateEnd->format('M jS,Y H:i:s');
            }else if(!isDateTimeUnlimited($dateStartArr) && isDateTimeUnlimited($dateEndArr)){
                $dateStart = new DateTime($dateStartArr);
                $dateEnd = $dateEndArr;
                $result = $dateStart->format('M jS,Y H:i:s')." - ".$dateEnd;
            }else if(isDateTimeUnlimited($dateStartArr) && isDateTimeUnlimited($dateEndArr)){
                $dateStart = $dateStartArr;
                $dateEnd = $dateEndArr;
                $result = $dateStart." - ".$dateEnd;
            }
            return $result;
        }
        return;
    }// End dateRange


    // app/Helpers/function.php
    public static function formatDate($date) {
        return \Carbon\Carbon::parse($date)->format('d-m-Y');
    }

    /*
    * Convert date from Y-m-d H:i:s to ALT dateRange format.
    */
    public static function dateRangeConv($date){
    if($date=="0000-00-00 00:00:00" || (empty($date) || $date=="")){return $date;}
    if($date=="00/00/0000 00:00"){
        $ret="Unlimited";
    }else{
        $date=date("Y-m-d H:i:s", strtotime($date));
        $ret = date("m/d/Y g:i A", strtotime($date));
    }
    return $ret;
    }
    
    /*
    * Function check datetime range Unlimited
    * This public static function use for check if period is Unlimited. (This's mean had not setting for datetime period enabled)
    */
    public static function isDateTimeUnlimited($dateTimePeriod){
    // Check if $dateTimePeriod strpos Unlimited
    /*    $cntUnlimited = substr_count($dateTimePeriod, "Unlimited");
    if($cntUnlimited==2){
        return true;
    }
    */
    if($dateTimePeriod == "Unlimited"){
        return TRUE;
    }
    return FALSE;
    }
    
    public static function changeDatetimeToDateFormat($datetime){
        if($datetime === "" || $datetime === "0000-00-00 00:00:00"){
            return "Nothing setting yet";
        }
        $cutTime    = explode(" ", $datetime);
        $date       = new \DateTime($datetime);
        if( isset($cutTime[1]) && $cutTime[1] !== ""){
            $result = $date->format('M jS, Y H:i:s');
        }else{
            $result = $date->format('M jS, Y');
        }
        return $result;
    }
    
    public static function setFormToDateTime($date){
    if($date){
        $cutD = explode(' ' , $date);
        $date = $cutD[0];
        if(count(explode("-",$date)) > 1){
            $dateA = explode("-",$date);
        }else if(count(explode("/",$date)) > 1){
            $dateA = explode("/",$date);
        }
    
        $d=$dateA[0];
        $m=$dateA[1];
        $y=$dateA[2];
        if(count(explode("-",$date)) > 1){
                $new_date = $y."/".$m."/".$d;
        }else if(count(explode("/",$date)) > 1){
                $new_date = $y."-".$m."-".$d;
        }
        return $new_date;
    }else{return "";}
    }
    
    public static function setFormToDateWithTime($date){
    if($date){
        $cutD = explode(' ' , $date);
        $date = $cutD[0];
        if(isset($cutD[1])){
            $time = $cutD[1];
        }
        if(count(explode("-",$date)) > 1){
            $dateA = explode("-",$date);
        }else if(count(explode("/",$date)) > 1){
            $dateA = explode("/",$date);
        }       
        $d=$dateA[0];
        $m=$dateA[1];
        $y=$dateA[2];
        if(count(explode("-",$date)) > 1){
            $new_date = $y."/".$m."/".$d;
        }else if(count(explode("/",$date)) > 1){
            $new_date = $y."-".$m."-".$d;
            if(isset($time)){
                $new_date .= " ".$time;
            }
        }
        return $new_date;
    }else{return "";}
    }
    
    public static function GetDateTimeNow(){
    return date('Y-m-d H:i:s');
    }
    
    public static function GetDateNow(){
    return date('Y-m-d');
    }
    
    public static function GetDateTimeHourNow(){
    return date('Y-m-d H:').'00';
    }
    
    public static function dateNotTime($date, $delim="/"){
    if($date){
        $date = explode(" ",$date);
        $date = $date[0];
        $date = explode("-",$date);
        $d = $date[0];
        $m = $date[1];
        $y = $date[2];
        $new_date = $d.$delim.$m.$delim.$y;
        return $new_date;
    }else{return "";}
    }
    
    public static function dateWithTime($date){
    if($date){
        $date = explode(" ",$date);
        $dateAllArr = $date[0];
        $dateArr = explode("-",$dateAllArr);
        if(count($dateArr)==1){ $dateArr = explode("/",$dateAllArr);}
        $d = $dateArr[2];
        $m = $dateArr[1];
        $y = $dateArr[0];
    
        $time = $date[1];
        $return = getShotMonthString($m)."".$d." ' ".$y." &nbsp; ".$time;
        return $return;
    }else{return "";}
    } //
    
    public static function dateFullMonthWithTime($date){
    if($date){
        $date = explode(" ",$date);
        $dateAllArr = $date[0];
        $dateArr = explode("-",$dateAllArr);
        if(count($dateArr)===1){ $dateArr = explode("/",$dateAllArr);}
        $d = $dateArr[2];
        $m = $dateArr[1];
        $y = $dateArr[0];
    
        $time = $date[1];
        $return = getFullMonthString($m)." ".$d.", ".$y." ".$time;
        return $return;
    }else{return "";}
    } //
    //
    
    public static function dateFullMonthWithNoTime($date){
    if($date){
        $date = explode(" ",$date);
        $dateAllArr = $date[0];
        $dateArr = explode("-",$dateAllArr);
        if(count($dateArr)===1){ $dateArr = explode("/",$dateAllArr);}
        $d = $dateArr[2];
        $m = $dateArr[1];
        $y = $dateArr[0];
    
        $time = $date[1];
        $return = getFullMonthString($m)." ".$d.", ".$y;
        return $return;
    }else{return "";}
    } //
    
    public static function cutTime($date){
    return explode(" ", $date)[0];
    }//
    
    public static function dateOnly($date){
    if(empty($date)){return;}
    return explode("-", cutTime($date))[2];
    }//
    
    public static function monOnly($date){
    if(empty($date)){return;}
    return explode("-", cutTime($date))[1];
    }//
    
    public static function yearOnly($date){
    if(empty($date)){return;}
    return explode("-", cutTime($date))[0];
    }//
    
    public static function monthYear($dt, $delim=", "){
    if($dt===""){
        return;
    }
    $dtChk=explode("-", $dt);
    return getFullMonthString($dtChk[1]).$delim.$dtChk[0];
    } //
    
    public static function SetDateFinish($date){
    return date('d/m/Y', strtotime('+1 day', strtotime($date))); 	
    }
    
    public static function SetFinishDateLast7days($date){
    return date('d/m/Y', strtotime('-7 day', strtotime($date))); 
    }
    
    public static function SetFinishDateDaily($date){
    return date('d/m/Y', strtotime('-6 day', strtotime($date))); 
    }
    
    public static function GetSatFriLastWeek(){
    $last_sat = strtotime("last saturday, -1 week"); 
    $last_fri = strtotime("last friday"); 
    $return = date('d/m/Y',$last_sat)."-".date('d/m/Y',$last_fri);
    if($return){ return $return;}
    else{ return FALSE;}
    }
    
    public static function SetFinishDateOneMonthly($date){
    $return = date('d/m/Y', strtotime('-1 month', strtotime($date)))."-".setFormToDateTime($date);
    if($return){ return $return;}
    else{ return FALSE;}
    }
    
    public static function GetfirstDateOneMonthly($date){
    $return = date("m/d/Y", strtotime('01/'.date('m').'/'.date('Y')))."-".setFormToDateTime($date);
    if($return){ return $return;}
    else{ return FALSE;}
    }
    
    public static function GetBetweenDate($fromDate , $toDate){
    //echo $fromDate."--".$toDate;
    $return = array();
    $fromDateTS = strtotime($fromDate);
    $toDateTS = strtotime($toDate);
    
    for ($currentDateTS = $fromDateTS; $currentDateTS <= $toDateTS; $currentDateTS += (60 * 60 * 24)) {
            // use date() and $currentDateTS to format the dates in between
            $currentDateStr = date('Y-m-d', $currentDateTS);
            $return[] = $currentDateStr;
    }
    return $return;
    }
    
    public static function ChkLengthDate($dt){
    if(strlen($dt)<'2'){
            $dt = '0'.$dt;
    }
    return $dt;
    }
    
    public static function getDateInLatestWeekFromToday(){
        // Today
        $today = new DateTime();

        // 6 days before today (so total = 7 days including today)
        $startDate = (clone $today)->modify('-6 days');

        return $startDate->format('Y-m-d');
    }
    
    public static function getDateInLatestMonthFromToday(){
        // Today
        $today = new DateTime();

        // 6 days before today (so total = 7 days including today)
        $startDate = (clone $today)->modify('-1 mont');

        return $startDate->format('Y-m-d');
    }
    
    public static function getShotMonthString($iMonth){ 
        $strMonth=""; 
        if($iMonth=='01')  { $strMonth="JAN"; } 
        elseif($iMonth=='02') { $strMonth="FEB"; } 
        elseif($iMonth=='03') { $strMonth="MAR"; } 
        elseif($iMonth=='04') { $strMonth="APR"; } 
        elseif($iMonth=='05') { $strMonth="MAY"; } 
        elseif($iMonth=='06') { $strMonth="JUN"; } 
        elseif($iMonth=='07') { $strMonth="JUL"; } 
        elseif($iMonth=='08') { $strMonth="AUG"; } 
        elseif($iMonth=='09') { $strMonth="SEP"; } 
        elseif($iMonth=='10') { $strMonth="OCT"; } 
        elseif($iMonth=='11') { $strMonth="NOV"; } 
        elseif($iMonth=='12') { $strMonth="DEC"; } 
        return $strMonth; 
    }
    
    public static function getFullMonthString($iMonth){ 
        $strMonth=""; 
        if($iMonth=='01')  { $strMonth="January"; } 
        elseif($iMonth=='02') { $strMonth="Febuary"; } 
        elseif($iMonth=='03') { $strMonth="March"; } 
        elseif($iMonth=='04') { $strMonth="April"; } 
        elseif($iMonth=='05') { $strMonth="May"; } 
        elseif($iMonth=='06') { $strMonth="Jun"; } 
        elseif($iMonth=='07') { $strMonth="July"; } 
        elseif($iMonth=='08') { $strMonth="August"; } 
        elseif($iMonth=='09') { $strMonth="September"; } 
        elseif($iMonth=='10') { $strMonth="October"; } 
        elseif($iMonth=='11') { $strMonth="November"; } 
        elseif($iMonth=='12') { $strMonth="December"; } 
        return $strMonth; 
    }
    
    // Time format is UNIX timestamp or
    // PHP strtotime compatible strings
    public static function dateDiff($time1, $time2, $precision = 6) {
            // If not numeric then convert texts to unix timestamps
            if (!is_int($time1)) {
              $time1 = strtotime($time1);
            }
            if (!is_int($time2)) {
              $time2 = strtotime($time2);
            }
    
            // If time1 is bigger than time2
            // Then swap time1 and time2
            if ($time1 > $time2) {
              $ttime = $time1;
              $time1 = $time2;
              $time2 = $ttime;
            }
    
            // Set up intervals and diffs arrays
            $intervals = array('year','month','day','hour','minute','second');
            $diffs = array();
    
            // Loop thru all intervals
            foreach ($intervals as $interval) {
              // Set default diff to 0
              $diffs[$interval] = 0;
              // Create temp time from time1 and interval
              $ttime = strtotime("+1 " . $interval, $time1);
              // Loop until temp time is smaller than time2
              while ($time2 >= $ttime) {
                $time1 = $ttime;
                $diffs[$interval]++;
                // Create new temp time from time1 and interval
                $ttime = strtotime("+1 " . $interval, $time1);
              }
            }
    
            $count = 0;
            $times = array();
            // Loop thru all diffs
            foreach ($diffs as $interval => $value) {
              // Break if we have needed precission
              if ($count >= $precision) {
                break;
              }
              // Add value and interval 
              // if value is bigger than 0
              if ($value > 0) {
                // Add s if value is not 1
                if ($value != 1) {
                  $interval .= "s";
                }
                // Add value and interval to times array
                $times[] = $value . " " . $interval;
                $count++;
              }
            }
    
    // Return string with times
    return implode(", ", $times);
    } 
    
    
    //Function convertTimesamp2Datetime
    public static function convertTimesamp2Datetime($timestamp=NULL, $output=''){
      //output type = ['Normal', 'DateOnly', 'TimeOnly', 'DiffTime']
      // Convert the timestamp to a Carbon instance
//      $return = "00000000000000";
      if($timestamp === NULL){
          //
          $return = "No data";
      }else{
        if(DateHelper::isDatetime($timestamp)){
            $timestamp = Carbon::parse($timestamp);
            $dateTime = Carbon::createFromTimestamp($timestamp->timestamp);
        }else{
            $dateTime = Carbon::createFromTimestamp($timestamp);
        }


        // Format the DateTime
        if($output === 'Normal'){
          //$return =  $timestamp; // Outputs: 2021-04-13 10:04:07
          $return =  $dateTime->format($timestamp); // Outputs: 2021-04-13 10:04:07
        }elseif($output === 'DateNoTime'){
          $return =  $dateTime->toDateString();        // Outputs: 2021-04-13
        }elseif($output === 'Time'){
          $return =  $dateTime->toTimeString();        // Outputs: 10:04:07
        }else{
          $return =  $dateTime->diffForHumans();       // Outputs: 2 years ago (depending on the current date)
        }
      }
      return $return;
    }
     
}//end class
