<?php

/*/
	File:  inc/checkout_ui.phi
	(c) 2004-2018 Windshields To Go USA - All rights reserved.
	Purpose:  Extracted functions to have in common (with 'standard' mode in checkout.php AND 'abridged' mode in nswizard/quote.php)
	Modification History:
		· 03/22/2018 - Nathan - explanted with heavy revisions
		· 04/07/2020 - Nathan - get css_class into the install date selectors
		· mm/dd/yyyy - name - comment
/*/


//-------------------------------------------------------------------------
// InstallDateJavascript: 
//-------------------------------------------------------------------------
function InstallDateJavascript( $rYs, $rYMs, $rYMDs, $FormNameHTML ) {

	?>
	<!-- install date handling -->
	<script type="text/javascript">

		///-------------------------------------------------------------------------
		function YearChange() {
			yearselect = document.getElementById('s_InstallYear'); 
			if( !yearselect ) {
				return; 
			}
			/// check for valid year selected...
			var f = document.forms['<?= $FormNameHTML ?>'];
			var bEmptyMonthDays = false;
			var year = parseInt(String(f.s_InstallYear[f.s_InstallYear.selectedIndex].value));
			if( isNaN(year) ) bEmptyMonthDays = true;
			if( year < 2000 ) bEmptyMonthDays = true;
			if( bEmptyMonthDays ) {
				//alert("bEmptyMonthDays1");
				f.s_InstallMonth.options.length = 0;
				f.s_InstallDate.options.length = 0;
				return true;
			}
			<?
			
				/// print out the month/days array definitions...
				echo "\n";
				foreach( $rYs as $yi => $year ) {
					$YearMonths = $rYMs[intval($year).' Y'];
					echo "\t\t\tvar Y_".intval($yi)." = ".NewJavascriptVarArray( $YearMonths ).";\n";
				}
			
			/// for this year...
			?>
			f.s_InstallMonth.length = 0;
			f.s_InstallMonth.options[0] = new Option('','');
			var MonthsArray = new Array();
			/// determine the right month array & then them dump in...
			<?
				foreach( $rYs as $yi => $year ) {
					echo "if( parseInt(String(f.s_InstallYear[f.s_InstallYear.selectedIndex].value)) == parseInt(String(".$year.")) ) MonthsArray = Y_".intval($yi).";\n";
				}
			?>
			for( var i=0; i<MonthsArray.length; i++ ) {
				f.s_InstallMonth.options[i+1] = new Option(MonthsArray[i], MonthsArray[i]);
			}
			/// select a default and we're done...
			f.s_InstallMonth.options[0].selected = true;
			MonthChange();
			return true;
		}
		
		///-------------------------------------------------------------------------
		function MonthChange() {
			
			var f = document.forms['<?= $FormNameHTML ?>'];
			/// check for valid year selected...
			var bEmptyMonthDays = false;
			var year = parseInt(String(f.s_InstallYear[f.s_InstallYear.selectedIndex].value));
			if( isNaN(year) ) bEmptyMonthDays = true;
			if( year < 2000 ) bEmptyMonthDays = true;
			if( bEmptyMonthDays ) {
				f.s_InstallMonth.options.length = 0;
				f.s_InstallDate.options.length = 0;
				//alert("bEmptyMonthDays2");
				return true;
			}
			/// check for valid month selected...
			var bEmptyDays = false;
			if( f.s_InstallMonth.options.length < 1 ) bEmptyDays = true;
			if( String(f.s_InstallMonth[f.s_InstallMonth.selectedIndex].value)=="" ) bEmptyDays = true;
			if( bEmptyDays ) {
				f.s_InstallDate.options.length = 0;
				//alert("bEmptyDays");
				return true;
			}
			
			<?php
				/// print out the month/days array definitions...
				echo "\n";
				foreach( $rYs as $yi => $year ) {
					$YearMonths = $rYMs[intval($year).' Y'];
					foreach( $YearMonths as $mi => $month ) {
						$YearMonthDays = $rYMDs[$yi][ $month ];
                                                
						echo "\t\t\tvar YM_".intval($yi)."_".$month." = ".NewJavascriptVarArray( $YearMonthDays ).";\n";
					}
				}
			
			/// for this year...
			?>
                                //var YM_2019_November =  new Array('22 - Friday','23 - Saturday','25 - Monday','26 - Tuesday','27 - Wednesday','28 - Thursday','29 - Friday','30 - Saturday');
			f.s_InstallDate.length = 0;
			f.s_InstallDate.options[0] = new Option('','');
			var DaysArray = new Array();
			<?
				/// export the js to determine the right month array...
				echo "\n";
				foreach( $rYs as $yi => $year ) {
					$YearMonths = $rYMs[intval($year).' Y'];
					foreach( $YearMonths as $mi => $month ) {
						$YearMonthDays = $rYMDs[$yi][ $mi ];
						echo "\t\t\tif( parseInt(String(f.s_InstallYear[f.s_InstallYear.selectedIndex].value)) == parseInt(String(".$year.")) && String(f.s_InstallMonth[f.s_InstallMonth.selectedIndex].value) == String(\"".$month."\") ) {\n\t\t\t\tDaysArray = YM_".intval($yi)."_".$month.";\n\t\t\t}\n";
					}
				}
			?>
			if( DaysArray.length < 1 ) {
				alert( "DatesArray not found!\n\nInfo:\n" + String(f.s_InstallYear[f.s_InstallYear.selectedIndex].value) +":"+ String("<?= $year ?>") +":"+ String(f.s_InstallMonth[f.s_InstallMonth.selectedIndex].value) +":"+  String("<?= "YM_".intval($yi)."_".$month ?>") );
			}
			/// dump in the days...
			var DayNum;
			for( var i=0; i<DaysArray.length; i++ ) {
				DayNum = String(DaysArray[i]).substr(0,2);
				f.s_InstallDate.options[i+1] = new Option(DaysArray[i], DayNum);
			}
			f.s_InstallDate.options[0].selected = true;
			return true;
		}

		function CheckEmptyDate(thisCombo) {
			if( thisCombo.options.length > 0 ) return true;
			var f = document.forms['<?= $FormNameHTML ?>'];
			if( f.s_InstallMonth.options.length == 0 ) {
				alert( "Please select a year first. (to the right)   " );
				return true;
			}
			if( f.s_InstallDate.options.length == 0 ) {
				alert( "Please select a month first. (to the left)   " );
				return true;
			}
		}
	
	</script>
	<?php

} // InstallDateJavascript()


///-------------------------------------------------------------------------
function InstallDateJavascript_String( $rYs, $rYMs, $rYMDs ) {

	// capture and return the output buffer
	ob_start();
	InstallDateJavascript( $rYs, $rYMs, $rYMDs );
	$content = ob_get_clean();
	return $content;

} // InstallDateJavascript_String()


//-------------------------------------------------------------------------
// [N:2018-03-22] should rename from HTML_* ..was going to ob_()
// [N:2020-04-07] implement css_class which was already in the caller: account/quote/quote.php
//-------------------------------------------------------------------------
function HTML_InstallYearSelection( $rYs, $SelectedYear, $css_class="normal" ) {

	echo "\t<select id=\"s_InstallYear\" name=\"s_InstallYear\" class=\"".$css_class."\" onChange=\"return YearChange();\" style=\"width: 5.25em;\">\n\t\t<option value=\"\"></option>\n";
	foreach( $rYs as $yi => $SelectedYear ) {
		echo "\t\t<option value=\"".$SelectedYear."\"".($frm['s_InstallYear']==$SelectedYear ? " SELECTED" : "").">".$SelectedYear."</option>\n";
	}
	echo "\t</select>\n";
	
} // HTML_InstallYearSelection()


///-------------------------------------------------------------------------
function HTML_InstallMonthSelection( $SelectedMonth, $css_class="normal" ) {

	echo "\t<select id=\"s_InstallMonth\" name=\"s_InstallMonth\" class=\"".$css_class."\" onChange=\"return MonthChange();\" onMouseUp=\"return CheckEmptyDate(this);\" style=\"width: 6rem;\">\n";
	if( $SelectedMonth ) {
		echo "\t\t<option value=\"" . $SelectedMonth . "\" selected>" . $SelectedMonth . "</option>\n";
	} else {
		echo "\t\t<option value=\"\" selected></option>\n";
	}
	?>								
		<option value="January">January</option>
		<option value="February">February</option>
		<option value="March">March</option>
		<option value="April">April</option>
		<option value="May">May</option>
		<option value="June">June</option>
		<option value="July">July</option>
		<option value="August">August</option>
		<option value="September">September</option>
		<option value="October">October</option>
		<option value="November">November</option>
		<option value="December">December</option>
	</select>
	<?

} // HTML_InstallMonthSelection()

///-------------------------------------------------------------------------
function HTML_InstallDaySelection( $SelectedDay, $css_class="normal" ) {

	echo "\t<select id=\"s_InstallDate\" name=\"s_InstallDate\" class=\"".$css_class."\" onMouseUp=\"return CheckEmptyDate(this);\" style=\"width: 6em;\">\n";
	if( $SelectedDay ) {
		echo "\t\t<option value=\"" . $SelectedDay . "\" selected>" . $SelectedDay . "</option>\n";
	} else {
		echo "\t\t<option value=\"\" selected></option>\n";
	}
	?>
		<option value="01">01 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</option>
		<option value="02">02</option>
		<option value="03">03</option>
		<option value="04">04</option>
		<option value="05">05</option>
		<option value="06">06</option>
		<option value="07">07</option>
		<option value="08">08</option>
		<option value="09">09</option>
		<option value="10">10</option>
		<option value="11">11</option>
		<option value="12">12</option>
		<option value="13">13</option>
		<option value="14">14</option>
		<option value="15">15</option>
		<option value="16">16</option>
		<option value="17">17</option>
		<option value="18">18</option>
		<option value="19">19</option>
		<option value="20">20</option>
		<option value="21">21</option>
		<option value="22">22</option>
		<option value="23">23</option>
		<option value="24">24</option>
		<option value="25">25</option>
		<option value="26">26</option>
		<option value="27">27</option>
		<option value="28">28</option>
		<option value="29">29</option>
		<option value="30">30</option>
		<option value="31">31</option>
	</select>
	<?php
	
} // HTML_InstallDaySelection()


///-------------------------------------------------------------------------
function HTML_InstallTimeSelection( $SelectedTime, $css_class="normal" ) {

	echo "\t<select name=\"s_InstallTime\" class=\"".$css_class."\">\n";
	?>
		<option value="9 to 1"<? if( $SelectedTime=="9 to 1" ) echo " SELECTED"; ?>>9am to 1pm</option>
		<option value="1 to 5"<? if( $SelectedTime=="1 to 5" ) echo " SELECTED"; ?>>1pm to 5pm</option>
	</select>
	<?php

} // HTML_InstallTimeSelection()


//-------------------------------------------------------------------------
// NewJavascriptVarArray: Prints out javascript content for a new array.
//-------------------------------------------------------------------------
function NewJavascriptVarArray( &$rValues ) {

	$valuesText = "";
	if( isset($rValues) ) {
		foreach( $rValues as $K => $V ) {
			$valuesText .= "'".$V."',";
		}
		if( strlen($valuesText)>1 ) $valuesText = substr($valuesText, 0, strlen($valuesText)-1);
	}
	return " new Array(".$valuesText.")";

} // NewJavascriptVarArray


//-------------------------------------------------------------------------
// days_in_month: Returns the number of days in the month.
//-------------------------------------------------------------------------
function days_in_month( $month, $year ) {

	switch( $month ) {
		case 2: return is_leap_year($year) ? 29 : 28;
		case 4: case 6: case 9: case 11: return 30;
		default: return 31;
	}

} // days_in_month()


//-------------------------------------------------------------------------
// is_leap_year:  Just returns true if the specified year is a leap year.
//-------------------------------------------------------------------------
function is_leap_year( $year ) {

	return ($year % 4 == 0) ? 1 : 0;

} // is_leap_year()


//-------------------------------------------------------------------------
// Generate_YearsMonthsDays_Arrays: Create a 3-level indexed array that drills down to all the date/weekdays in the specified range.
//-------------------------------------------------------------------------
function Generate_YearsMonthsDays_Arrays( $DateStart, $DateFinish, &$Years, &$YearMonths, &$YearMonthDays, $bIsW2G=false ) {
        
	global $g_Config, $g_oAffiliate, $gblMySqlHost, $gblMySqlUser, $gblMySqlPass;     
        
	// load closed day settings
	$SQL = "SELECT day_monday, day_tuesday, day_wednesday, day_thursday, day_friday, day_saturday, day_sunday FROM `affiliate` WHERE aff = '{$g_oAffiliate->aff}' LIMIT 1";
	$hData = mysql_query($SQL);
	$closedDays = mysql_fetch_object($hData);
        
	// load ranges allowed
	$SQL = "SELECT closed_range_start, closed_range_end FROM `affiliate` WHERE aff = '{$g_oAffiliate->aff}' LIMIT 1";
	$data = mysql_query($SQL);
	$ranges = mysql_fetch_object($data);
        
	// load specific closed dates
	$SQL = "SELECT calendar_days_closed, closed_range_end FROM `affiliate` WHERE aff = '{$g_oAffiliate->aff}' LIMIT 1";
	$data = mysql_query($SQL);
	$calendarDays = mysql_fetch_object($data);
	
	 
// 	 if($_SERVER['REMOTE_ADDR']=='27.57.173.88'){
// 	    echo "<pre>";
// 	    print_r($g_oAffiliate);
// 	 }
	
	
	// load Restriction Zip & delay days By Mukund
	$openingCodes = explode(':', isset($_GET['opening']) ? trim($_GET['opening']) : '');
	$userOpening = isset($openingCodes[0]) ? $openingCodes[0] : '';

	$SQL = "SELECT zipRestrict, delayDays, opening FROM `nsAffiliatePricing` WHERE affiliate = '{$g_oAffiliate->ID}' ";
	$data = mysql_query($SQL);
    
    $userZip = isset($_GET['zip']) ? trim($_GET['zip']) : '';
    $matchedDelay = null;
    $defaultDelay = null; // fallback delay from the default (no-zip) rule matching this opening type

    if ($data && mysql_num_rows($data) > 0 && $userZip !== '') {
    
        while ($row = mysql_fetch_object($data)) {

            // only consider rules for this quote's opening type (WS/!WS), or rules with no opening set
            if ($row->opening !== '' && $row->opening !== $userOpening) {
                continue;
            }
	 
            if (empty($row->zipRestrict)) {
                // No specific zip list -- this is the default/catch-all rule for this opening type.
                // Remember its delay so we can fall back to it if no zip-specific rule matches below.
                if ($defaultDelay === null && $row->delayDays !== null && $row->delayDays !== '') {
                    $defaultDelay = $row->delayDays;
                }
                continue;
            }
    
            $zipArray = array_map('trim', explode(',', $row->zipRestrict));
            
            
            if (in_array($userZip, $zipArray, true)) {
                $matchedDelay = $row->delayDays;
                break; // stop at first zip-specific match
            }
        }

        // No zip-specific rule matched this ZIP -- fall back to the default rule's delay, if one is set
        if ($matchedDelay === null && $defaultDelay !== null) {
            $matchedDelay = $defaultDelay;
        }
    }

        
	/* [NL:2018-03-22] 
		configurable for universal hard-code noinstall blocked dates
		(later, convert to db loader w/ 'is_universal option)
	*/
	$noinstall_dates = array(
		// !note1: always use the time of (0,0,1,...)
		// !note2: enter date portion as: (0, 0, 1, MM, DD, YYYY)
		/* [N:2020-06-10] disabled in favor of existing per-aff scheduling
		mktime(0,0,1,'12','25',date('Y')),
		mktime(0,0,1,'07','04',date('Y')),
		// note: should NOT use date('Y') on non-universal holidays that shift (specify each year)
		mktime(0,0,1,'11','22',date('Y')),
		*/
	);
	if( isset($g_oAffiliate) && ($g_oAffiliate->isW2G || $g_oAffiliate->isJoined) ) {
		$noinstall_dates = array(
			// !note1: always use the time of (0,0,1,...)
			// !note2: enter date portion as: (0, 0, 1, MM, DD, YYYY)
			/* [N:2020-06-10] disabled in favor of existing per-aff scheduling
			mktime(0,0,1,'12','25',date('Y')),
			mktime(0,0,1,'07','04',date('Y')),
		// note: should NOT use date('Y') on non-universal holidays that shift (specify each year)
			mktime(0,0,1,'11','22',date('Y')),
			mktime(0,0,1,'09','03',date('Y')),
			mktime(0,0,1,'06','12',date('Y')),
			mktime(0,0,1,'06','11',date('Y')),
			*/
		);
	}
	
	// for maths below
	$endDate = strtotime(date('Y-12-31'));
	$startDate = strtotime(date('Y-01-01'));

	// Monday
	if( $closedDays->day_monday === 'Y' ) {
		for($i = strtotime('Monday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i)) {
			$noinstall_dates[] = mktime(0,0,1, date('m', $i) ,date('d', $i), date('Y', $i));
		}  
	}

	// Tuesday
	if( $closedDays->day_tuesday === 'Y' ) {
		for($i = strtotime('Tuesday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i)) {
			$noinstall_dates[] = mktime(0,0,1, date('m', $i) ,date('d', $i), date('Y', $i));
		}  
	}

	// Wednesday
	if( $closedDays->day_wednesday === 'Y' ) {
		for($i = strtotime('Wednesday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i)) {
			$noinstall_dates[] = mktime(0,0,1, date('m', $i) ,date('d', $i), date('Y', $i));
		}  
	}

	// Thursday
	if( $closedDays->day_thursday === 'Y' ) {
		for($i = strtotime('Thursday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i)) {
			$noinstall_dates[] = mktime(0,0,1, date('m', $i) ,date('d', $i), date('Y', $i));
		}  
	}

	// Friday
	if( $closedDays->day_friday === 'Y' ) {
		for($i = strtotime('Friday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i)) {
			$noinstall_dates[] = mktime(0,0,1, date('m', $i) ,date('d', $i), date('Y', $i));
		}  
	}

	// Saturday
	if( $closedDays->day_saturday === 'Y' ) {
		for($i = strtotime('Saturday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i)) {
			$noinstall_dates[] = mktime(0,0,1, date('m', $i) ,date('d', $i), date('Y', $i));
		}  
	}

	// Sunday
	if( $closedDays->day_sunday === 'Y' ) {            
		for($i = strtotime('Sunday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i)) {                    
			$noinstall_dates[] = mktime(0,0,1, date('m', $i) ,date('d', $i), date('Y', $i));
		}  
	}

	// check ranges
	if( !empty($ranges->closed_range_start) && !empty($ranges->closed_range_end) ) {
		$startDate = new DateTime($ranges->closed_range_start);
		$endDate = new DateTime($ranges->closed_range_end);
		$period = new DatePeriod(
			$startDate,
			new DateInterval('P1D'),
			$endDate
		);
		foreach ($period as $value) {
			$noinstall_dates[] = mktime(0,0,1, $value->format('m') ,$value->format('d'), $value->format('Y'));	
		}
		$noinstall_dates[] = mktime(0,0,1, $startDate->format('m') ,$startDate->format('d'), $startDate->format('Y')); 
		$noinstall_dates[] = mktime(0,0,1, $endDate->format('m') ,$endDate->format('d'), $endDate->format('Y')); 
	}

	// check specific closed dates
	if( !empty($calendarDays->calendar_days_closed) ) {
		$calendarDates = json_decode($calendarDays->calendar_days_closed, true);
		foreach($calendarDates as $date => $closed) {
			if ($closed) {
				$datetime = new DateTime($date);
				$noinstall_dates[] = mktime(0,0,1, $datetime->format('m') ,$datetime->format('d'), $datetime->format('Y')); 
			}
		}
	}
		    
		    
	
	

	/// pre-initz = where we are in time...
	$StartYear = date( 'Y', $DateStart );
	$StartMonth = date( 'F', $DateStart );
	$StartDay = date( 'd', $DateStart );
	
	/// same variables being checked w/i the looping below...
	$NormalizedStartingDate = date( 'Y-m-d', $DateStart );
	list( $start_y, $start_m, $start_d ) = split( '-', $NormalizedStartingDate );
	$NormalizedStartingDate = mktime( 0, 0, 1, $start_m, $start_d, $start_y ); // early this morning
	$BlockTomorrowSaturday = mktime( 0, 0, 1, $start_m, $start_d + 1, $start_y );
	$CurrentDate = mktime( 0, 0, 1, intval(date('m')), intval(date('d')), intval(date('Y')) );
	$CurrentTimeString = date( 'H:i:s:u' );
	list( $CurrentHour, $CurrentMins, $CurrentSecs, $CurrentMilliseconds ) = split( ':', $CurrentTimeString); // only using $CurrentHour
	$CurrentHour = intval($CurrentHour);

	/// reset initializations...
	$Years = array();
	$YearMonths = array();
	$YearMonthDays = array();
	$bypassed = array();

	/// iterate through years from start date to finish date...
	$start_year = intval(date('Y', $DateStart));
	$finish_year = intval(date('Y', $DateFinish));
	for( $iYear=$start_year; $iYear<=$finish_year; $iYear++ ) {
		
		/// put this year in...
		$Years[$iYear.' Y'] = $iYear;
		$YearMonthDays[$iYear." Y"] = array();
		
		/// next do the MONTH dimension...
		$start_month = ($iYear==$start_year) ? intval(date('n', $DateStart)) : 1;
		$finish_month = ($iYear==$finish_year) ? intval(date('n', $DateFinish)) : 12;
		for( $iMonth=$start_month; $iMonth<=$finish_month; $iMonth++ ) {
			
			// put this month in...
			$YearMonths[$iYear.' Y'][$iMonth.' M'] = date('F', mktime(0,0,1,$iMonth,1,$iYear));
			$YearMonthDays[$iYear." Y"][$iMonth] = array();
			
			/// now do the DAY dimension... (while bypassing dates with availability restrictions)
			$start_day = 1;
			if( $iYear==$StartYear && $YearMonths[$iYear.' Y'][$iMonth.' M']==$StartMonth ) {
				$start_day = $StartDay;
			}
			
			$todayd = new DateTime('today');// midnight today

			$final_day = days_in_month($iMonth, $iYear);
			for( $iDay=$start_day; $iDay<=$final_day; $iDay++ ) {
				
				// this is the date we're checking
				$LoopDate = mktime(0,0,1,$iMonth,$iDay,$iYear);
				//echo "<!-- Generate: check = (".date('Y-m-d',$LoopDate)." (".$LoopDate."), start = ".date('Y-m-d',$NormalizedStartingDate).", today = ".date('Y-m-d h:i:s').") -->\n";
				
				// (double-check hack) be sure we don't start too early
				if( $LoopDate < $NormalizedStartingDate ) {
					$bypassed[date('Y-m-d',$LoopDate)] = "0: too soon";
					continue;
				}

				// don't list universal blackout days 
				foreach( $noinstall_dates as $blockdate ) {
					if( $blockdate == $LoopDate ) {
						$bypassed[date('Y-m-d',$LoopDate)] = "1: blocked";
						continue 2; // double-jump!
					}
				}
				
			    // Only restrict By Zip with delay for isW2G and Joined with new Code By Mukund
                if( isset($g_oAffiliate) && ($g_oAffiliate->isW2G || $g_oAffiliate->isJoined) ) {
                    
                    // Use the delay logic if found
                    if (!is_null($matchedDelay)) {
                        //echo "ZIP {$userZip} found. Add {$matchedDelay} days delay.";
                        // Loop 0 .. ($delay - 1) so $delay counts days starting from today
                        for ($i = 0; $i < $matchedDelay; $i++) {
            
                            $targetDate = clone $todayd;
                            $targetDate->modify("+{$i} days"); // today + $i
            
                            if (date('Y-m-d', $LoopDate) === $targetDate->format('Y-m-d')) {
                                $bypassed[date('Y-m-d', $LoopDate)] = "Restrict dates: {$i} days (counting from today)";
                                continue 2; // skip this $LoopDate in outer loop
                            }
                        }
                    } else {
                        // nothing to bypass
                        // echo "No restriction for ZIP {$userZip}.";
                    }
                }
				
				
				// Only restrict By Zip with delay for isW2G and Joined By Mukund
				// if( isset($g_oAffiliate) && ($g_oAffiliate->isW2G || $g_oAffiliate->isJoined) ) {
			
    // 				// Zip restrict with delay
    //                 if (!empty($zips_restrict->zips_restrict_sameday)) {
                    
    //                     $zipArray = array_map('trim', explode(',', $zips_restrict->zips_restrict_sameday));
                    
    //                     if (in_array($_GET['zip'], $zipArray, true)) {
                    
    //                         // Normalize $delay to a non-negative integer
    //                         $delay = (int) $delay;
    //                         if ($delay <= 0) {
    //                             // nothing to bypass
    //                         } else {
    //                             // Loop 0 .. ($delay - 1) so $delay counts days starting from today
    //                             for ($i = 0; $i < $delay; $i++) {
                    
    //                                 $targetDate = clone $todayd;
    //                                 $targetDate->modify("+{$i} days"); // today + $i
                    
    //                                 if (date('Y-m-d', $LoopDate) === $targetDate->format('Y-m-d')) {
    //                                   // echo $targetDate->format('Y-m-d') . "<br>";
    //                                     $bypassed[date('Y-m-d', $LoopDate)] = "Restrict dates: {$i} days (counting from today)";
    //                                     continue 2; // skip this $LoopDate in outer loop
    //                                 }
    //                             }
    //                         }
    //                     }
    //                 }
				// }
            
				
				/*/ DISABLED never install on Sundays
				if( strtoupper(date('l',$LoopDate)) == "SUNDAY" ) {
					$bypassed[date('Y-m-d',$LoopDate)] = "2: Sunday";
					continue;
				}*/
				
				///[NL:2020-10-01] only do these when requested (for isW2G)
				if( $bIsW2G ) {
				
					// !W2G-ONLY don't allow "tomorrow" Saturday selection too late on a Friday
					if( $LoopDate == $BlockTomorrowSaturday ) {
						if( (strtoupper(date('l',$CurrentDate)) == "FRIDAY") && $CurrentHour >= 15 ) {
							//echo "<!-- Generate: (bailout) at #04 -->\n";
							$bypassed[date('Y-m-d',$LoopDate)] = "3: tomorrow Saturday (late)";
							continue;
						}
					}
				
					// !W2G-ONLY special "today" checkings
					if( $LoopDate == $CurrentDate ){
						// don't allow "today" scheduling on Saturdays
						if( strtoupper(date('l', $CurrentDate)) == "SATURDAY" ) {
							$bypassed[date('Y-m-d',$LoopDate)] = "4a: today Saturday";
							continue;
						}
						// don't allow "today" scheduling after 16:00 hours
						if( $CurrentHour >= 16 ) {
							$bypassed[date('Y-m-d',$LoopDate)] = "4b: today late";
							continue;
						}
					}
				}
				
				// passed all conditions, allow this date
				$YearMonthDays[$iYear . ' Y'][$YearMonths[$iYear . ' Y'][$iMonth . ' M']][$iDay . ' D'] = date( 'd', $LoopDate ) . ' - ' . date( 'l', $LoopDate );
			}

			// If every day in this month got filtered out (e.g. a delay consumed the
			// only remaining days), don't leave it in the month list as an empty/dead option.
			$monthNameForCleanup = $YearMonths[$iYear.' Y'][$iMonth.' M'];
			if( empty($YearMonthDays[$iYear.' Y'][$monthNameForCleanup]) ) {
				unset($YearMonths[$iYear.' Y'][$iMonth.' M']);
			}
				
		}
	}
	//echo "<pre>"; var_dump($bypassed);
	return true;
	
} // Generate_YearsMonthsDays_Arrays()

				

//-------------------------------------------------------------------------
// PaymentSelection: ui for the payment type selector
// Usage: PaymentSelection( $g_oAffiliate->isW2G || $isReferral, $g_oAffiliate->paymentOptions, $_REQUEST['c_type'] )
// Note: relies on err() display function in /inc/includes/functions/mymarket.inc.php
//-------------------------------------------------------------------------
function PaymentSelection( $bIsW2G, $bIsReferral, $AffPaymentOptions, $SelectedPayment ) {

	// aff payment option codes
	$allopts = array(
		"cash",
		"net30",
		"check",
		"visa",
		"mc",
		"amex",
		"discover",
		"novus",
		"paypal",
		"insurance"
	);
	
	// w2g availability
	$optsw2g = array(
		"cash"      => false, 
		"net30"     => false,
		"check"     => false,
		"visa"      => true,
		"mc"        => true,
		"amex"      => true,
		"discover"  => true,
		"novus"     => true,
		"paypal"    => false,
	);

	// option values
	$optvalues = array( 
		"cash"      => "CASH", 
		"net30"     => "OnAccount",
		"check"     => "CHECK",
		"visa"      => "Visa",
		"mc"        => "MasterCard",
		"amex"      => "Amex",
		"discover"  => "Discover",
		"novus"     => "Novus",
		"paypal"    => "PayPal",
		"insurance"    => "Insurance",
	);
	
	// option text to display
	$optinfos = array( 
		"cash"      => "Cash (paid upon delivery / service)", 
		"net30"     => "On Account",
		"check"     => "Personal Check (paid upon delivery / service)",
		"visa"      => "Visa",
		"mc"        => "Master Card",
		"amex"      => "American Express",
		"discover"  => "Discover",
		"novus"     => "Novus",
		"paypal"    => "PayPal",
		"insurance" => "Bill my Insurance",
	);
	
	// build it
	$html = "<select name=\"c_type\" class=\"normal\" style=\"width: 13em; max-width: 15em;\">\n";
	$html .= "\t\t<option value=\"\"".(empty($SelectedPayment) ? " SELECTED" : "")."></option>\n";
	foreach( $allopts as $opt ) {
		if( ($bIsW2G || $bIsReferral) && !$optsw2g[$opt] ) {
			continue;
		} elseif( !$AffPaymentOptions[$opt] ) {
			continue;
		}
		$html .= "<option value=\"".$optvalues[$opt]."\"".($SelectedPayment == $optvalues[$opt] ? " SELECTED" : "").">".$optinfos[$opt]." &nbsp;</option>\n";
	}
	$html .= "</select>";
	return $html;

} // PaymentSelection()

