<?php
//sorry for who ever looks at this before I clean up the code and add comments

//using bootstrap to make the page look better on mobile devices
echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>David\'s Vacation Planner</title><link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"><link rel="stylesheet" type="text/css" href="vp.css?19"></head><body onload="loadfun()"><script type="text/javascript" src="js/jquery-3.6.0.js"></script><script type="text/javascript" src="js/bootstrap.bundle.min.js"></script><main class="container-fluid planner-page">';

if(!isset($_REQUEST['year'])) {
    $year =  date('Y', strtotime('+1 year'));
} else {
    $year = $_REQUEST['year'];
}

$nextyear = $year+1;
$lastyear = $year-1;

$vactaken = array();

if(!empty($_REQUEST['foo'])) {
    $bar = explode('[',$_REQUEST['foo']);
    foreach($bar as $row) {
        $data = preg_split('/\s+/', $row);
        if(isset($data[2], $data[4], $data[5]) && $data[5]=='VNU') {
            $vactaken[$data[2]]=intval($data[4]);
        }
    }
    echo "<input type='hidden' id='imported-history' value='1'>";
}

//add already inputed info to link url so you don't have to reenter it when bouncing between years

$alink ='';

if (isset($_REQUEST['years'])) {
    echo "<input type='hidden' id='iyear' value='{$_REQUEST['years']}'>";
    $alink .= '&years='.$_REQUEST['years'];
} else {
    echo "<input type='hidden' id='iyear' value='0'>";
}

if(isset($_REQUEST['fte'])) {
    $alink .= '&fte='.$_REQUEST['fte'];
}

if(isset($_REQUEST['vco'])) {
    $alink .= '&vco='.$_REQUEST['vco'];
}

if(isset($_REQUEST['lhc'])) {
    $alink .= '&lhc='.$_REQUEST['lhc'];
}

echo '<div id="sticky-alert" class="alert alert-danger" role="alert" style="position: fixed; top: 10px; left: 10px; right: 10px; width: auto; z-index: 1050; display: none;">
  <span id="alert-message"></span>
</div>';


echo '<details class="planner-help alert alert-warning">
  <summary><strong>Instructions, disclaimer, and what\'s new</strong></summary>
  <div class="help-content">
  <strong>New!  Added alerts for planning next years vacation, alerts for too many hours selected and summer/winter block out periods</strong><br>
  <strong>Disclaimer</strong><br>These numbers are best estimates, please double check.  This tool was developed independant of UW Health HR and may contain inaccuracies.  Any issues, please contact dturner@uwhealth.org <a href="viewindex.php">See raw code</a><br>
  <strong>Instructions</strong><br> Enter numbers in the form at the top, click on days you want to take vacation.  Hover your mouse over on the right to see a breakdown of hourse earned/spent.  When you are done, there is a button at the bottom that will show you a list of days you selected.<br>
  <strong>Video Tutorial</strong><br><a href="https://youtu.be/iKZhYzdkFEw">https://youtu.be/iKZhYzdkFEw</a><br>
  
  <br><strong>Important!</strong>  You need to have a beginning balance to support vacation taken during the pay period, but need to keep your ending balance below the max accrual limit (to avoid losing vacation hours).  That is why both are now calculated.
  <br><strong>Other tools</strong><br> <a class="btn btn-secondary" href="rcalc.php" role="button">Rolling hour calculator</a>
</div></details>';
if($year==date('Y', strtotime('+0 year'))) {
    echo '<div class="year-action"><div><strong>Ready to plan ahead?</strong><span>Return to next year after confirming this year\'s ending balance.</span></div><a class="btn btn-outline-primary btn-lg" href="index.php?year='.$nextyear.$alink.'" id="nlink" role="button">Open '.$nextyear.' vacation planner</a></div>';
} else {
    echo '<div class="year-action year-action-primary"><div><strong>Need your starting carryover?</strong><span>Review this year so its ending balance can carry into '.$year.'.</span></div><a class="btn btn-primary btn-lg" href="index.php?year='.$lastyear.$alink.'" id="olink" role="button">Calculate this year\'s vacation ('.$lastyear.')</a></div>';
}

if(isset($_REQUEST['vco'])) {
    $vco = $_REQUEST['vco'];
} else {
    $vco = 0;
}

echo '<section class="planner-settings" aria-labelledby="planner-settings-title">
  <div class="settings-heading">
    <div>
      <p class="eyebrow">Plan for '.$year.'</p>
      <h1 id="planner-settings-title">Vacation planner</h1>
    </div>
    <div class="save-tools" aria-live="polite">
      <span id="save-status" class="save-status">Saved on this device</span>
      <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearSavedPlanner()">Clear saved data</button>
    </div>
  </div>
  <p class="save-note">Your entries are saved automatically in this browser for this year.</p>
  <div class="row planner-field">
  <div class="col-1 col-sm-1 col-lg-3"></div>';
if($year==date('Y', strtotime('+0 year'))) {
    echo '<div class="col-5 col-sm-5 col-lg-3">Vacation Accrued Beginning Balance:</div>';
} else {
    echo '<div class="col-5 col-sm-5 col-lg-3">Vacation Hours Carried Over:</div>';
}
echo'
   <div class="col-5 col-sm-5 col-lg-3"><input type="number" inputmode="decimal" step="0.1" class="form-control" aria-label="Vacation hours carried over" placeholder="Enter vacation hours carried over" value="'.$vco.'" id="CarryOver" onchange="FTErecalc()"></div>
  <div class="col-1 col-sm-1 col-lg-3"></div>
  </div>
';

if(isset($_REQUEST['fte'])) {
    $fte = $_REQUEST['fte'];
} else {
    $fte = 0;
}
echo '<div class="row planner-field">
  <div class="col-1 col-sm-1 col-lg-3"></div>
   <div class="col-5 col-sm-5 col-lg-3">FTE:</div>
   <div class="col-5 col-sm-5 col-lg-3"><input type="number" inputmode="decimal" min="0" max="1" step="0.01" class="form-control" aria-label="FTE" placeholder="Enter FTE" value="'.$fte.'" id="FTE" onchange="VacationEarnedCalc()"></div>
  <div class="col-1 col-sm-1 col-lg-3"></div>
  </div>
';
//options for how many vacation hours you get based on how many years you work per information from uconnect.  Don't display Integrated options until it is possible for it to be applicable to someone

echo '<div class="row planner-field">
  <div class="col-1 col-sm-1 col-lg-3"></div>
   <div class="col-5 col-sm-5 col-lg-3">Years of service:</div>
   <div class="col-5 col-sm-5 col-lg-3"><select id="yearsservice" class="form-select" aria-label="Years of service" onChange="VacationEarnedCalc()">
   <option value="128">0-5 years (Legacy)</option>
   <option value="120">0-5 years (Integrated)</option>
   <option value="156">6-10 years (Legacy)</option>';
if(date('Y', strtotime("$year-01-01"))>=2025) {
    echo '   <option value="120">6-10 years (Integrated)</option>';
}
echo '<option value="172">11-15 years (Legacy)</option>

   <option value="196">16-20 years (Legacy)</option>';
if(date('Y', strtotime("$year-01-01"))>=2030) {

    echo'   <option value="160">11-20 years (Integrated)</option>';
}
echo'   <option value="212">21-25 years (Legacy)</option>';
if(date('Y', strtotime("$year-01-01"))>=2040) {
    echo '<option value="200">21+ years (Integrated)</option>';
}
echo'   <option value="236">26+ years (Legacy)</option>
   <option>Integrated = leave accrual date on/after 12/20/2020</option><option>Legacy = leave accrual date before 12/20/2020</option></select></div>
  <div class="col-1 col-sm-1 col-lg-3"></div>
  </div>
';

echo '<div class="row planner-field">
  <div class="col-1 col-sm-1 col-lg-3"></div>
   <div class="col-5 col-sm-5 col-lg-3">Hours of Vacation Earned per Year:</div>
   <div class="col-5 col-sm-5 col-lg-3"><input type="number" inputmode="decimal" step="0.1" class="form-control" aria-label="Vacation hours earned per year" placeholder="Enter vacation hours earned" value="0"  id="Earned" onchange="FTErecalc()"></div>
  <div class="col-1 col-sm-1 col-lg-3"></div>
  </div>
';
echo '<div class="row planner-field">
  <div class="col-1 col-sm-1 col-lg-3"></div>
   <div class="col-5 col-sm-5 col-lg-3">Maximum Accrual Balance Allowed:</div>
   <div class="col-5 col-sm-5 col-lg-3"><input type="number" inputmode="decimal" step="0.1" class="form-control" aria-label="Maximum accrual balance allowed" placeholder="Max accrual balance" value="0"  id="MaxAcru" onchange="FTErecalc()"></div>
  <div class="col-1 col-sm-1 col-lg-3"></div>
  </div>
';

if(isset($_REQUEST['lhc'])) {
    if($_REQUEST['lhc']=='yes') {
        $lhcyes = 'checked';
        $lhcno = '';
    } else {
        $lhcyes = '';
        $lhcno = 'checked';
    }
} else {
    $lhcyes = '';
    $lhcno = 'checked';
}

echo '<div class="row planner-field">
  <div class="col-1 col-sm-1 col-lg-3"></div>
   <div class="col-5 col-sm-5 col-lg-3">Legal Holiday Cancel:<br><em>Check yes if you cancelled your Legal Holiday</em></div>
   <div class="col-5 col-sm-5 col-lg-3"><input type="radio" value="1"  id="lhcyes" name="lhc" onchange="FTErecalc()" '.$lhcyes.'><label for="lhcyes">Yes Legal Holiday Canceled</label><br>(convert to vacation)<br><input type="radio" value="0"  id="lhcno" name="lhc" onchange="FTErecalc()" '.$lhcno.'><label for="lhcno">No Legal Holiday Cashed Out</label></div>
  <div class="col-1 col-sm-1 col-lg-3"></div>
  </div>
';
echo '<div class="row planner-field weekend-field">
  <div class="col-1 col-sm-1 col-lg-3"></div>
<div class="col-10 col-sm-10 col-lg-6">';
echo '<fieldset><legend>How often is your working weekend?</legend><div class="choice-row frequency-choices"><label><input type="radio" name="every" id="ev2" value="2" onchange="WeekendRecolor()"> Every 2nd weekend</label><label><input type="radio" name="every" id="ev3" value="3" onchange="WeekendRecolor()"> Every 3rd weekend</label></div></fieldset>';
echo '<fieldset id="weekend-reference" class="hidden weekend-reference"><legend>Choose one weekend you work</legend><p class="weekend-help">This gives the planner a starting point for the repeating pattern.</p><div class="weekend-options"><label><input type="radio" name="weekend" id="weekend-last" value="-1" onchange="WeekendRecolor()"><span><strong>Last weekend</strong><small id="weekend-last-dates"></small></span></label><label><input type="radio" name="weekend" id="weekend-current" value="0" onchange="WeekendRecolor()"><span><strong>This / next weekend</strong><small id="weekend-current-dates"></small></span></label><label><input type="radio" name="weekend" id="weekend-after" value="1" onchange="WeekendRecolor()"><span><strong>Weekend after this</strong><small id="weekend-after-dates"></small></span></label></div></fieldset>';
echo '</div><div class="col-1 col-sm-1 col-lg-3"></div></div></section>';

$months=array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

$mon = '';

$weekend = 'A';



if($year==date('Y', strtotime('+0 year'))) {
    echo '<details class="planner-help current-year-help alert alert-warning">
      <summary><strong>Current year: balance and history import</strong></summary>
      <div class="help-content">
        <strong>Current Year Selected!</strong><br>
        <p>Important!</p><p>Make sure you are on the current pay period (found in the <strong>Employee Navigator</strong> in the top left of the TCS screen) when you look your vacation accrued. 
         Take the <strong>Vacation Accrued Beginning Balance</strong> from MyTime (on the TCS screen) and enter it into the Vacation carried over section.</p><p><strong>Then enter in any vacation remaining for the year.</strong>  The ending balance for the last pay period of the year (or the beginning balance of the first pay period of the year) should be the vacation you will carry over from this year.</p>
      <br><strong>New feature!  Import vacation from mytime.</strong><br>
      <p>To import your scheduled vacation from mytime, go to your TCS screen, <strong>make sure Pay Period Only is unselected</strong>, click somewhere in the Transaction list frame to gain focus, and select all the text in that frame by typing Command+A(Mac) or Control+A(PC) and copy it(Command+C(Mac) or Control+C(PC)).  Then paste (command+V(Mac) or Control+V(PC) this text into the box below and click submit. This should populate the calendar with your scheduled vacation.  Watch video tutorial <a href="https://youtu.be/mRUrFHMnX60">https://youtu.be/mRUrFHMnX60</a></p>
      <form method="post" action="" id="tlink" class="history-import">
        <label for="foo" class="form-label"><strong>Vacation history from MyTime</strong></label>
        <textarea id="foo" name="foo" class="form-control" rows="6" placeholder="Paste your MyTime transaction list here"></textarea>
        <input type="submit" class="btn btn-primary" value="Import vacation history">
       </form>
      
      
    </div></details>
';
}
//determine first pay period of the year

if(time()>strtotime("$year-01-01")) {
    $dayone = strtotime('today') - date('w') * 86400;
    $dayone = strtotime('last sunday');
    if (end_of_payweek(date('Y-m-d', $dayone))) {
        $dayone = $dayone - 86400 * 7;
    }
} else {
    $dayone = strtotime("$year-01-01") - date('w', strtotime("$year-01-01")) * 86400;
    if (end_of_payweek(date('Y-m-d', $dayone))) {
        $dayone = $dayone - 86400 * 7;
    }
}

//not used?
//$base = date(strtotime('first saturday of 1/1/'.$year));

$legalholidays=array();

$lastyear = $year - 1;

$legalholidays[] = 'gross';
$legalholidays[] = date(strtotime("december 24 $lastyear"));
$legalholidays[] = date(strtotime("december 25 $lastyear"));
$legalholidays[] = date(strtotime("first day of january $year"));
$legalholidays[] = date(strtotime("third monday of january $year"));
$legalholidays[] = date(strtotime("last monday of may $year"));
$legalholidays[] = date(strtotime("july 4 $year"));
$legalholidays[] = date(strtotime("first monday of september $year"));
$legalholidays[] = date(strtotime("fourth thursday of november $year"));
$legalholidays[] = date(strtotime("december 24 $year"));
$legalholidays[] = date(strtotime("december 25 $year"));
$legalholidays[] = date(strtotime("first day of january ".($year+1)));

$dailybalance = array();


$lhutotals = 0;

$week_count = date('W', strtotime($year . '-12-31'));

if ($week_count == '01')
{
    $week_count = date('W', strtotime($year . '-12-24'));
}
echo '<section class="calendar-section" aria-labelledby="calendar-title"><div class="calendar-heading"><div><p class="eyebrow">'.$year.'</p><h2 id="calendar-title">Choose vacation days</h2></div><p class="scroll-hint">Swipe sideways to see the full calendar and balances.</p></div>';
echo '<div class="calendar-scroll" role="region" aria-label="Vacation calendar" tabindex="0">';
echo '<table class="table table-bordered" id="vp">';

echo '<thead><tr><th scope="col">Month</th><th scope="col">Sun</th><th scope="col">Mon</th><th scope="col">Tue</th><th scope="col">Wed</th><th scope="col">Thu</th><th scope="col">Fri</th><th scope="col">Sat</th><th scope="col">Beginning / ending balance</th></tr></thead><tbody>';

$i = 0;
while (1){
    $buildweek = strtotime(date('Y-m-d',$dayone). "+ $i week");
    if(($buildweek+86400*6)>=strtotime(($year+1).'-01-01')&&end_of_payweek(date('Y-m-d',$buildweek))) {
        echo '<tr><td colspan="9">Next Year\'s ('.($year+1).') First Pay Period<input type="hidden" id="lastweekid" value="'.$i.'"></td></tr>';
        buildweek2($buildweek,$i,$vactaken);
        break;
    }
    buildweek2($buildweek,$i,$vactaken);
    $i++;
}


echo '</tbody></table></div></section>';

function buildweek2($weekstart,$week,$vactaken) {
    $lastday = 0;
    $hours = 0;
    $thours = 0;
    echo '<tr>';
    $start = $weekstart;
    $end = strtotime(date('Y-m-d',$start).' + 6 days');
    if($GLOBALS['mon']!=date('M',$end))  {
        if(date('d',$start)==1||$GLOBALS['mon']=='') {
            echo '<td><strong>' . date('M', $end) . '</strong></td>';
        } else {
            echo '<td>'.$GLOBALS['mon'].'/<strong>' . date('M', $end) . '</strong></td>';
        }
        $GLOBALS['mon']=date('M',$end);
    } else {
        echo '<td>'.$GLOBALS['mon'].'</td>';
    }
    $lhutp = 0;
    for($i=0;$i<7;$i++) {
        if($lastday == date('d',$start+$i*86400)) {
            $start += 3600;
        } else {
            $lastday = date('d',$start+$i*86400);
        }
        $dateid=date($start+$i*86400);
        $datevac = date('m/d/Y',$start+$i*86400);
        //hack for day light savings
        if($lastday == date('d',$start+$i*86400)) {

        } else {
            $lastday = date('d',$start+$i*86400);
        }
        if(isset($vactaken[$datevac]) && $vactaken[$datevac]) {
            $hours = $vactaken[$datevac];
            $thours += $hours;
        } else {
            $hours = 0;
        }

        //if($dateid==date(strtotime("april 30 {$GLOBALS['year']}"))) {
        //    echo "<input type=hidden id=april30 value=$week>";
        //    $lhucomesg=1;
        //}
        if(date('m',$dateid)%2) {
            $class='class="table-light"';
        } else {
            $class='class="table-secondary"';
        }
        if(array_search(date($start+$i*86400),$GLOBALS['legalholidays'])==TRUE) {
            $class= 'class="lhu"';
            $GLOBALS['lhutotals']+=8;
            $lhutp+=8;
        }
        echo '<td '.$class.' id="'.date($start+$i*86400).'" data-date="'.date('Y-m-d',$start+$i*86400).'">'.date('d',$start+$i*86400).'<br>';
        if($hours) {
            echo "<input type=checkbox aria-label='Select vacation for $datevac' id='d" . date($start + $i * 86400) . "' onchange='ShowHours(this.id,$start,$week)' checked><br>";
            echo "<div id=rd$dateid>";
        } else {
            echo "<input type=checkbox aria-label='Select vacation for $datevac' id='d" . date($start + $i * 86400) . "' onchange='ShowHours(this.id,$start,$week)'><br>";
            echo "<div id=rd$dateid class=hidden>";
        }
        foreach(array(4,8,9,10,12) as $hour) {
            if($hour == $hours) {
                echo "<label class='hour-choice'><input type=radio value=$hour name=r$dateid id=rd$dateid-$hour aria-label='$hour vacation hours on $datevac' onchange='UpdateWeekVach($start,$week)' checked><span>$hour</span></label>";
            } else {
                echo "<label class='hour-choice'><input type=radio value=$hour name=r$dateid id=rd$dateid-$hour aria-label='$hour vacation hours on $datevac' onchange='UpdateWeekVach($start,$week)'><span>$hour</span></label>";
            }
        }
        echo "</div>";

        echo '</td>';

        if($i==6) {
            if($week%2) {
                echo "<td><button type='button' id=w" . intval($week) . " class='btn btn-primary' data-bs-toggle='tooltip' data-bs-placement='left' data-bs-html='true' data-bs-original-title='---'>---</button>";
            } else {
                echo "<td>";
            }
            echo "<input type=hidden id=wlhu".intval($week)." value=".$GLOBALS['lhutotals'].">";
            echo "<input type=hidden id=wlhutp".intval($week)." value=".$lhutp.">";
            echo "<input type=hidden id=vach".intval($week)." value=$thours>";
            echo "<input type=hidden id=weekstart".intval($week)." value=".date('Y-m-d',$weekstart).">";
            echo "</td>";
        }
    }

    if (end_of_payweek(date("Y-m-d",$start))) {

        //

    }
    echo '</tr>';
}








echo '<div class="planner-actions" id="link"></div>';


echo '<section class="vacation-report" id="vacation-report" aria-labelledby="report-title">
  <div class="report-heading"><h2 id="report-title">Vacation report</h2><button type="button" class="btn btn-outline-primary" onclick="printVacationReport()">Print report</button></div>
  <p id="report-period"></p>
  <dl id="report-summary"></dl>
  <p class="report-note">All amounts are in hours. Balance is the ending balance for each two-week pay period. Figures are estimates; verify with your official records.</p>
  <div class="report-table-scroll"><table class="report-table">
    <thead><tr><th scope="col">Two-week pay period</th><th scope="col">Vacation taken</th><th scope="col">Vacation earned</th><th scope="col" class="report-holiday">Holiday converted</th><th scope="col">Balance</th></tr></thead>
    <tbody id="report-rows"></tbody>
  </table></div>
  <p class="report-note">Calculations retain full precision; all hour amounts are displayed to two decimal places. * Balance exceeds the maximum accrual allowed.</p>
</section>';
echo "</main>";
echo '<script src="js/vacation-report.js?2"></script>';


echo '<script>

var plannerYear = ' . json_encode((string)$year) . ';
var plannerStorageKey = "vacationPlanner:v2:" + plannerYear;
var plannerSaveTimer = null;
var reportPayPeriodsPerYear = ' . json_encode(floor($week_count / 2)) . ';
var reportPeriods = [];
var restoringPlanner = false;

function setSaveStatus(message, isError) {
    var status = document.getElementById("save-status");
    if (!status) return;
    status.textContent = message;
    status.classList.toggle("save-error", Boolean(isError));
}

function getSavedPlannerState() {
    try {
        var stored = localStorage.getItem(plannerStorageKey);
        return stored ? JSON.parse(stored) : null;
    } catch (error) {
        setSaveStatus("Saving is unavailable in this browser", true);
        return null;
    }
}

function savePlannerState() {
    if (restoringPlanner) return;

    var fieldIds = ["CarryOver", "FTE", "Earned", "MaxAcru", "foo"];
    var fields = {};
    fieldIds.forEach(function (id) {
        var field = document.getElementById(id);
        if (field) fields[id] = field.value;
    });

    var yearsService = document.getElementById("yearsservice");
    var checkedRadioIds = Array.prototype.map.call(
        document.querySelectorAll("input[type=radio]:checked"),
        function (radio) { return radio.id; }
    );
    var selectedDayIds = Array.prototype.map.call(
        document.querySelectorAll("#vp input[type=checkbox]:checked"),
        function (checkbox) { return checkbox.id; }
    );
    var weekTotals = {};
    Array.prototype.forEach.call(document.querySelectorAll("input[id^=vach]"), function (input) {
        weekTotals[input.id] = input.value;
    });

    var state = {
        version: 2,
        fields: fields,
        yearsServiceIndex: yearsService ? yearsService.selectedIndex : 0,
        checkedRadioIds: checkedRadioIds,
        selectedDayIds: selectedDayIds,
        weekTotals: weekTotals,
        savedAt: new Date().toISOString()
    };

    try {
        localStorage.setItem(plannerStorageKey, JSON.stringify(state));
        setSaveStatus("Saved on this device at " + new Date(state.savedAt).toLocaleTimeString([], {hour: "numeric", minute: "2-digit"}), false);
    } catch (error) {
        setSaveStatus("Could not save on this device", true);
    }
}

function queuePlannerSave() {
    if (restoringPlanner) return;
    window.clearTimeout(plannerSaveTimer);
    setSaveStatus("Saving…", false);
    plannerSaveTimer = window.setTimeout(savePlannerState, 180);
}

function restorePlannerState() {
    var state = getSavedPlannerState();
    if (!state || state.version !== 2) return false;

    restoringPlanner = true;
    var query = new URLSearchParams(window.location.search);
    var fieldQueryNames = {CarryOver: "vco", FTE: "fte"};

    Object.keys(state.fields || {}).forEach(function (id) {
        var field = document.getElementById(id);
        var queryName = fieldQueryNames[id];
        if (field && (!queryName || !query.has(queryName))) field.value = state.fields[id];
    });

    var yearsService = document.getElementById("yearsservice");
    if (yearsService && !query.has("years") && Number.isInteger(state.yearsServiceIndex)) {
        yearsService.selectedIndex = state.yearsServiceIndex;
    }

    var importedHistory = Boolean(document.getElementById("imported-history"));
    if (!importedHistory) {
        Array.prototype.forEach.call(document.querySelectorAll("#vp input[type=checkbox], #vp input[type=radio]"), function (input) {
            input.checked = false;
        });
        Array.prototype.forEach.call(document.querySelectorAll("#vp div[id^=rd]"), function (choices) {
            choices.classList.add("hidden");
        });
    }

    (state.checkedRadioIds || []).forEach(function (id) {
        var radio = document.getElementById(id);
        if (!radio) return;
        if (radio.name === "lhc" && query.has("lhc")) return;
        if (importedHistory && radio.name.indexOf("r") === 0) return;
        radio.checked = true;
    });

    if (!importedHistory) {
        (state.selectedDayIds || []).forEach(function (id) {
            var checkbox = document.getElementById(id);
            if (!checkbox) return;
            checkbox.checked = true;
            var choices = document.getElementById("r" + id);
            if (choices) choices.classList.remove("hidden");
        });
        Object.keys(state.weekTotals || {}).forEach(function (id) {
            var total = document.getElementById(id);
            if (total) total.value = state.weekTotals[id];
        });
    }

    restoringPlanner = false;
    if (state.savedAt) {
        setSaveStatus("Saved on this device at " + new Date(state.savedAt).toLocaleTimeString([], {hour: "numeric", minute: "2-digit"}), false);
    }
    return true;
}

function bindPlannerAutosave() {
    Array.prototype.forEach.call(document.querySelectorAll("input, select, textarea"), function (field) {
        field.addEventListener("input", queuePlannerSave);
        field.addEventListener("change", queuePlannerSave);
    });
    var importForm = document.getElementById("tlink");
    if (importForm) importForm.addEventListener("submit", savePlannerState);
}

function clearSavedPlanner() {
    if (!window.confirm("Clear the saved entries and selected vacation days for " + plannerYear + " on this device?")) return;
    try {
        localStorage.removeItem(plannerStorageKey);
    } catch (error) {
        setSaveStatus("Could not clear saved data", true);
        return;
    }
    window.location.reload();
}

function FTErecalc() {
  reportPeriods = [];
  console.log("recalc");
  var vco = parseFloat(document.getElementById("CarryOver").value);
  var fte = parseFloat(document.getElementById("FTE").value);
  var ear = parseFloat(document.getElementById("Earned").value);
  var maxacru = parseFloat(document.getElementById("MaxAcru").value);
  var used = 0;
  var lastehours = vco;
  
  for(i=1;i<56;i=i+2) {
      var j = i-1;
      var k = i-2;
      if(k<0){k=0};
      var l = i-3;
      if(l<0){l=0};
      var id = "w"+i;
      var ttid = "wtt"+i;
      var lhuid = "wlhu"+i;
      var lhutp1 = "wlhutp"+j;
      var lhutp0 = "wlhutp"+i;
      var vachid1="vach"+i;
      var vachid0="vach"+j;

      if(document.getElementById(vachid1)) {
    

        if(document.getElementById("lhcyes").checked) {
      var lhu = parseFloat(document.getElementById(lhuid).value);
      var lhutp = (parseFloat(document.getElementById(lhutp1).value)+parseFloat(document.getElementById(lhutp0).value));
      } else {
            var lhu = 0;
            var lhutp = 0;
      }
      var vach1 = parseFloat(document.getElementById(vachid1).value);
      var vach0 = parseFloat(document.getElementById(vachid0).value);
      used = used + vach1 + vach0;
      vacationearned = Math.floor(((j+2)/2 * (ear / 26))*10)/10; 
      var bhours = lastehours;
      var ehours = Math.floor(parseFloat( vco + lhu * fte + (j+2)/2 * (ear / ' . floor($week_count / 2) . ') -used)*10)/10;
      lastehours = ehours;
      if(ehours>maxacru) {
                  document.getElementById(id).className = "btn btn-danger";
                          document.getElementById(id).innerHTML = maxacru+"<br>Hours Maxed!<br>("+ehours+")";
      } else {
      document.getElementById(id).innerHTML = bhours +" / "+ ehours;
      if(ehours>=0) {
            document.getElementById(id).className = "btn btn-primary";
      } else {
            document.getElementById(id).className = "btn btn-danger";
      }
      }
      var usedthispp = vach1 + vach0;
      var reportBalance = vco + lhu * fte + (j + 2) / 2 * (ear / reportPayPeriodsPerYear) - used;
      reportPeriods.push({
          start: document.getElementById("weekstart" + j).value,
          taken: usedthispp,
          earned: ear / reportPayPeriodsPerYear,
          holiday: lhutp * fte,
          balance: reportBalance,
          overMaximum: reportBalance > maxacru,
          nextYear: i === Number(document.getElementById("lastweekid").value)
      });
      if(usedthispp > bhours) {
            document.getElementById(id).innerHTML = document.getElementById(id).innerHTML+"<br>Beginning Balance insufficent for vacation taken!";
            document.getElementById(id).className = "btn btn-danger";
      }

      //      document.getElementById(id).innerHTML = Math.floor(parseFloat( vco + lhco + lhu * fte + (j+2)/2 * (ear / ' . floor($week_count / 2) . ') -used)*10)/10;
      //      document.getElementById(ttid).innerHTML = "vacation used this period:"+(vach1 + vach0)+"<br>"+"vacation used:"+used+"<br>"+"vacation earned this period:"+Math.floor(ear / ' . floor($week_count / 2) . '*10)/10+"<br>"+"vacation earned:"+vacationearned+"<br>"+"legal holiday earned this period:"+(lhutp*fte)+"<br>"+"legal holiday earned:"+(lhu*fte)+"<br>";
      //document.getElementById(ttid).innerHTML = "vacation used this period:"+(vach1 + vach0)+"<br>"+"vacation used:"+used+"<br>"+"vacation earned this period:"+Math.floor(ear / ' . floor($week_count / 2) . '*10)/10+"<br>"+"vacation earned:"+vacationearned+"<br>"+"legal holiday earned this period:"+(lhutp*fte)+"<br>"+"legal holiday earned:"+(lhu*fte)+"<br>";
              if(document.getElementById("lhcyes").checked) {
      var tt = "vacation used this period:"+(vach1 + vach0)+"<br>"+"vacation used:"+used+"<br>"+"vacation earned this period:"+Math.floor(ear / ' . floor($week_count / 2) . '*10)/10+"<br>"+"vacation earned:"+vacationearned+"<br>"+"legal holiday earned this period:"+Math.floor(lhutp*fte*10)/10+"<br>"+"legal holiday earned:"+Math.floor(lhu*fte*10)/10;
      } else {
               var tt = "vacation used this period:"+(vach1 + vach0)+"<br>"+"vacation used:"+used+"<br>"+"vacation earned this period:"+Math.floor(ear / ' . floor($week_count / 2) . '*10)/10+"<br>"+"vacation earned:"+vacationearned+"<br>";

      }
        document.getElementById(id).setAttribute("data-bs-original-title", tt);

    }
      checkVacationConditions();
  }
  
   var vsel = "";
    var radios = document.getElementsByTagName("input");
    for (i = 0; i < radios.length; i++) {
        if (radios[i].type === "radio" && radios[i].checked) {
            vsel = vsel+"&"+radios[i].id;
        }
    }
    
    var link = "vpd.php?year="+encodeURIComponent(plannerYear)+"&vco="+vco+"&fte="+fte+vsel;
    var selectedDays = document.querySelectorAll("#vp input[type=checkbox]:checked").length;
    var selectedHours = 0;
    Array.prototype.forEach.call(document.querySelectorAll("input[id^=vach]"), function (weekTotal) {
        selectedHours += parseFloat(weekTotal.value) || 0;
    });
    var selectionText = selectedDays === 0
        ? "No vacation days selected yet"
        : selectedDays + (selectedDays === 1 ? " day" : " days") + " · " + selectedHours + " hours";
    document.getElementById("link").innerHTML = "<div class=\'selection-summary\'><div class=\'selection-copy\'><span class=\'selection-label\'>Your vacation plan</span><strong>" + selectionText + "</strong></div><a class=\'btn btn-primary selection-button\' href=\'" + link + "\' role=\'button\'><span>Review selected vacation</span><span class=\'selection-arrow\' aria-hidden=\'true\'>→</span></a></div>";
    renderVacationReport();
    updatelink();
    queuePlannerSave();
}

function addCalendarDays(date, numberOfDays) {
    var result = new Date(date.getTime());
    result.setDate(result.getDate() + numberOfDays);
    return result;
}

function getThisOrNextWeekendSaturday() {
    var today = new Date();
    today.setHours(12, 0, 0, 0);
    var day = today.getDay();
    var daysUntilSaturday = day === 0 ? -1 : (6 - day + 7) % 7;
    return addCalendarDays(today, daysUntilSaturday);
}

function getReferenceWeekend(offset) {
    return addCalendarDays(getThisOrNextWeekendSaturday(), offset * 7);
}

function formatWeekend(saturday) {
    var sunday = addCalendarDays(saturday, 1);
    var formatter = new Intl.DateTimeFormat(undefined, {month: "short", day: "numeric"});
    return formatter.format(saturday) + " – " + formatter.format(sunday);
}

function initializeWeekendChoices() {
    [
        {id: "weekend-last-dates", offset: -1},
        {id: "weekend-current-dates", offset: 0},
        {id: "weekend-after-dates", offset: 1}
    ].forEach(function (choice) {
        var label = document.getElementById(choice.id);
        if (label) label.textContent = formatWeekend(getReferenceWeekend(choice.offset));
    });
}

function ShowWeekend() {
    var frequencySelected = document.querySelector("input[name=every]:checked");
    document.getElementById("weekend-reference").classList.toggle("hidden", !frequencySelected);
}

function WeekendRecolor() {
    ShowWeekend();

    Array.prototype.forEach.call(document.querySelectorAll("#vp td.red"), function (cell) {
        cell.classList.remove("red");
    });

    var frequency = document.querySelector("input[name=every]:checked");
    var reference = document.querySelector("input[name=weekend]:checked");
    if (!frequency || !reference) {
        queuePlannerSave();
        return;
    }

    var every = parseInt(frequency.value, 10);
    var anchorSaturday = getReferenceWeekend(parseInt(reference.value, 10));
    var millisecondsPerWeek = 7 * 24 * 60 * 60 * 1000;

    Array.prototype.forEach.call(document.querySelectorAll("#vp td[data-date]"), function (cell) {
        var parts = cell.getAttribute("data-date").split("-");
        var date = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10), 12);
        if (date.getDay() !== 0 && date.getDay() !== 6) return;

        var saturday = date.getDay() === 0 ? addCalendarDays(date, -1) : date;
        var weeksFromAnchor = Math.round((saturday.getTime() - anchorSaturday.getTime()) / millisecondsPerWeek);
        if (((weeksFromAnchor % every) + every) % every === 0) {
            cell.classList.add("red");
        }
    });

    queuePlannerSave();
}

function syncVacationSelectedStyles() {
    Array.prototype.forEach.call(document.querySelectorAll("#vp input[type=checkbox]"), function (checkbox) {
        var cell = checkbox.closest("td");
        if (cell) cell.classList.toggle("vacation-selected", checkbox.checked);
    });
}

function ShowHours(chk,weekstart,week) {
var targetElement = "r"+chk;
  var checkbox = document.getElementById(chk);
  var cell = checkbox.closest("td");
  if (cell) cell.classList.toggle("vacation-selected", checkbox.checked);
  if (checkbox.checked){
     document.getElementById(targetElement).classList.remove("hidden");

     document.getElementById(targetElement+"-12").checked = true;
     UpdateWeekVach(weekstart,week);

  }
  else{
     document.getElementById(targetElement).classList.add("hidden");
     document.getElementById(targetElement+"-12").checked = false;
     document.getElementById(targetElement+"-10").checked = false;
     document.getElementById(targetElement+"-9").checked = false;
     document.getElementById(targetElement+"-8").checked = false;
     document.getElementById(targetElement+"-4").checked = false;
     UpdateWeekVach(weekstart,week);


  }
}

function UpdateWeekVach(weekstart,week) {
    weekstart = weekstart - 86400;
    var total=0;
    for(var i=1;i<8;i++) {
        var day = weekstart + i * 86400;
        if(document.getElementById("rd"+day+"-12").checked == true) {
            total = total + 12;
                    } else if (document.getElementById("rd"+day+"-10").checked == true) {
                        total = total + 10;

                    } else if (document.getElementById("rd"+day+"-9").checked == true) {
                        total = total + 9;

        } else if (document.getElementById("rd"+day+"-8").checked == true) {
            total = total + 8;
        } else if (document.getElementById("rd"+day+"-4").checked == true) {
            total = total + 4;
        }
    }
    document.getElementById("vach"+week).value = total;
    FTErecalc();
}

function VacationEarnedCalc() {
    var e = document.getElementById("yearsservice");
    var hours = parseInt(e.options[e.selectedIndex].value);
    document.getElementById("Earned").value = hours * parseFloat(document.getElementById("FTE").value);
    if (parseFloat(document.getElementById("FTE").value) > 0.74) {
            document.getElementById("MaxAcru").value = (hours * 1.5).toFixed(1);
    } else {
            document.getElementById("MaxAcru").value = (hours * 1.5 * 0.74).toFixed(1);
    }
    
    FTErecalc();
}


function updatelink() {
        
          var fte = parseFloat(document.getElementById("FTE").value);
          var link = "?";
                  var years = document.getElementById("yearsservice").selectedIndex;
          link = link + "years="+years;
        if(fte>0) {
            link = link + "&fte=" + fte;
        }
        if(document.getElementById("lhcyes").checked) {
            link = link + "&lhc=yes";
        } else {
            link = link + "&lhc=no";
        }
        
        if(document.getElementById("nlink")) {
            var eweek = document.getElementById("lastweekid").value;
            var bhours = document.getElementById("w"+eweek).innerHTML.split("/")[0];
            plink = link + "&year='.$nextyear.'&vco="+bhours;
            document.getElementById("nlink").setAttribute("href",plink);
        }
        
        if (document.getElementById("olink")) {
                                plink = link + "&year='.$lastyear.'";
                    document.getElementById("olink").setAttribute("href",plink);
        }
    
                if (document.getElementById("tlink")) {
                                plink = link + "&year='.$year.'";
                    document.getElementById("tlink").setAttribute("action",plink);
        }
        
}

function loadfun() {
    initializeWeekendChoices();
    if(document.getElementById("iyear")) {
        var iyear = document.getElementById("iyear").value;
        document.getElementById("yearsservice").options[iyear].selected=true;
    }
    var restored = restorePlannerState();
    var query = new URLSearchParams(window.location.search);
    if (!restored || query.has("fte") || query.has("years")) {
        VacationEarnedCalc();
    } else {
        FTErecalc();
    }
    syncVacationSelectedStyles();
    if (document.getElementById("ev2").checked || document.getElementById("ev3").checked) {
        WeekendRecolor();
    } else {
        ShowWeekend();
    }
    bindPlannerAutosave();
    queuePlannerSave();
}



</script>';

?>
    <script>
        function checkVacationConditions() {
            var fte = parseFloat(document.getElementById("FTE").value);
            var earnedHours = parseFloat(document.getElementById("Earned").value);
            var totalHoursAllowed = earnedHours + (64 * fte);  // Total hours allowed = earned vacation + legal holidays (assuming 64 is a constant value for legal holidays)
            var selectedVacationHours = 0;
            var memorialDayExcess = 0;
            var christmasExcess = 0;

            // Set the date ranges for Memorial Day and Christmas holidays
            var memorialDayStart = new Date('<?php echo date("Y-m-d", strtotime("last monday of May $year -7 days")); ?>');
            var laborDay = new Date('<?php echo date("Y-m-d", strtotime("first monday of September $year")); ?>');
            var christmasStart = new Date('<?php echo date("Y-m-d", strtotime("December 24 $year - 7 days")); ?>');
            var newYearsEnd = new Date('<?php echo date("Y-m-d", strtotime("January 2 ".($year + 1)." + 6 days")); ?>');

            // Loop through the weeks and calculate the total selected vacation hours and holiday excess
            for (var i = 0; i <= 56; i ++) {

                var weekElement = document.getElementById("weekstart" + i);  // Retrieve the element by its ID

                if (weekElement && weekElement.value) {  // Check if the element exists and has a value
                    var weekStart = new Date(weekElement.value);
                    var weekHours = parseFloat(document.getElementById("vach" + i).value) || 0;  // Retrieve vacation hours for the week

                    selectedVacationHours += weekHours;  // Add to total vacation hours

                    // Check if the week falls between Memorial Day and Labor Day
                    if (weekStart >= memorialDayStart && weekStart <= laborDay) {
                        memorialDayExcess += weekHours;
                    }

                    // Check if the week falls between Christmas and New Year's
                    if (weekStart >= christmasStart && weekStart <= newYearsEnd) {
                        christmasExcess += weekHours;
                    }
                }
            }

            console.log((memorialDayExcess + ' ' + christmasExcess + ' ' + selectedVacationHours));

            // Check if the current year is next year
            var isNextYear = <?php echo ($year == date('Y', strtotime('+1 year'))) ? 'true' : 'false'; ?>;

            // Initialize a flag to track if any alert is triggered
            var alertTriggered = false;

            // If it's next year, check for vacation condition violations
            if (isNextYear) {
                // Condition 1: More vacation hours selected than allowed
                if (selectedVacationHours > totalHoursAllowed) {
                    showStickyAlert("You've selected more vacation hours than allowed (Earned in a year + Legal Holidays).");
                    console.log("exceeded allowed");
                    alertTriggered = true; // Alert has been triggered
                }

                // Condition 2: More than 2 weeks of vacation between Memorial Day and Labor Day
                if (memorialDayExcess > (fte * 80)) {  // Assuming 80 hours = 2 weeks
                    showStickyAlert("You've selected more than 2 weeks of vacation during the summer block out (between Memorial Day and Labor Day).");
                    console.log("exceeded summer");
                    alertTriggered = true; // Alert has been triggered
                }

                // Condition 3: More than 2 days of vacation between Christmas and New Year's
                if (christmasExcess > 24) {  // Assuming 24 hours = 2 days
                    showStickyAlert("You've selected more than 2 days of vacation during the winter block out (between Christmas and New Year's).");
                    console.log("exceeded Christmas");
                    alertTriggered = true; // Alert has been triggered
                }
            }

            // Hide the alert if no conditions were violated
            if (!alertTriggered) {
                hideStickyAlert();
            }
        }

        function showStickyAlert(message) {
            var alertDiv = document.getElementById("sticky-alert");
            document.getElementById("alert-message").innerText = message;
            alertDiv.style.display = 'block'; // Show alert
        }

        function hideStickyAlert() {
            var alertDiv = document.getElementById("sticky-alert");
            alertDiv.style.display = 'none'; // Hide alert
        }
    </script>
<?php
echo "<script>
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle=\"tooltip\"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>";



function end_of_payweek($sunday) {
    $earlier = new DateTime("2021-08-29");
    $later = new DateTime("$sunday");
    $diff = $later->diff($earlier)->format("%a");
    if($diff%14==0) {
        return 0;
    } else {
        return 1;
    }
}


echo "</body></html>";
1