<?php

/** @var PlateAuthorizationController $this */
$now = new DateTimeEx ();

$softMode = paramdeep ( 'plateAuthorizations', 'scheduler', 'softMode' );
$hotelMode = paramdeep ( 'plateAuthorizations', 'scheduler', 'hotelMode' );

$name_surname = array_get ( $_REQUEST, 'name_surname', '' );
$nationality = array_get ( $_REQUEST, 'nationality', 'IT' );
$plate = array_get ( $_REQUEST, 'plate', '' );
$year = array_get ( $_REQUEST, 'year', $now->year );
$month = array_get ( $_REQUEST, 'month', $now->month );
$plateListId = array_get ( $_REQUEST, 'plateListId' );
$plateList = PlateList::load ( $plateListId, false );

$minTime = $plateList->getMinimumDuration ();
$maxTime = $plateList->getMaximumDuration ();

$minTimeDays = intval ( $minTime->format ( '%d' ) );
$maxTimeDays = intval ( $maxTime->format ( '%d' ) );

if ($hotelMode)
{
  $minTimeLabel = $minTimeDays <= 0 ? t ( 'Any' ) : ($minTimeDays == 1 ? ("{$minTimeDays} " . t ( "night" )) : ("{$minTimeDays} " . t ( "nights" )));
  $maxTimeLabel = $maxTimeDays <= 0 ? t ( 'Any' ) : ($maxTimeDays == 1 ? ("{$maxTimeDays} " . t ( "night" )) : ("{$maxTimeDays} " . t ( "nights" )));
}
else
{
  $minTimeLabel = $minTimeDays <= 0 ? t ( 'Any' ) : ($minTimeDays == 1 ? ("{$minTimeDays} " . t ( "day" )) : ("{$minTimeDays} " . t ( "days" )));
  $maxTimeLabel = $maxTimeDays <= 0 ? t ( 'Any' ) : ($maxTimeDays == 1 ? ("{$maxTimeDays} " . t ( "day" )) : ("{$maxTimeDays} " . t ( "days" )));
}

$date = new DateTimeEx ();
$date->setTime ( 0, 0, 0 );
$date->day = 1;
$date->year = $year;
$date->month = $month;

$date_month_prev = clone $date;
$date_month_prev->subFromString ( "1 month" );
$date_month_prev_url = url ( 'plateAuthorization/scheduler', array (
    'plateListId' => $plateListId,
    'month' => $date_month_prev->month,
    'year' => $date_month_prev->year 
) );
$date_month_prev_text = htmlspecialchars ( "<< " ) . ucwords ( DateHelper::getMonthName ( $date_month_prev->month ) ) . " $date_month_prev->year";
$date_month_prev_link = CHtml::link ( $date_month_prev_text, $date_month_prev_url );

$date_month_next = clone $date;
$date_month_next->addFromString ( "1 month" );
$date_month_next_url = url ( 'plateAuthorization/scheduler', array (
    'plateListId' => $plateListId,
    'month' => $date_month_next->month,
    'year' => $date_month_next->year 
) );
$date_month_next_text = ucwords ( DateHelper::getMonthName ( $date_month_next->month ) ) . " $date_month_next->year" . htmlspecialchars ( " >>" );
$date_month_next_link = CHtml::link ( $date_month_next_text, $date_month_next_url );

$columns = rangek ( 1, 7 );

$daysCount = cal_days_in_month ( CAL_GREGORIAN, $date->month, $date->year );

$refDate = clone $date;

$firstDayOfWeekForMonth = $refDate->getDayOfWeek ( true );
if ($firstDayOfWeekForMonth > 1)
{
  $firstDayOfWeekForMonthCorrection = $firstDayOfWeekForMonth - 1;
  $refDate->subFromString ( "{$firstDayOfWeekForMonthCorrection} days" );
}

$additionalWeeksBeforeMonth = intval ( paramdeep ( 'plateAuthorizations', 'scheduler', 'additionalWeeksBeforeMonth' ) );
if ($additionalWeeksBeforeMonth > 0)
{
  $additionalDaysBeforeMonth = $additionalWeeksBeforeMonth * 7;
  $refDate->subFromString ( "{$additionalDaysBeforeMonth} days" );
  $daysCount += $additionalDaysBeforeMonth;
}

$additionalWeeksAfterMonth = intval ( paramdeep ( 'plateAuthorizations', 'scheduler', 'additionalWeeksAfterMonth' ) );
if ($additionalWeeksAfterMonth > 0)
{
  $daysCount += 7 * $additionalWeeksAfterMonth;
}

$foundFirstEntry = false;

?>


<style>
td {
  height: 50px;
  margin: 10px;
  padding: 5px;
  text-align: center;
  vertical-align: middle;
  /*border: solid black 1px;*/
  margin: 10px;
}

.div_base {
  text-align: center;
  vertical-align: middle;
  width: 100%;
  height: 100%;
  border-radius: 10px;
}

.div_content {
  text-align: center;
  vertical-align: middle;
}

.result_good {
  font-style: italic;
  font-weight: bold;
  color: green !important;
}

.result_bad {
  font-style: italic;
  font-weight: bold;
  color: red !important;
}

.field-error {
  border: 1px solid red !important;
}

.div_highlighted {
  border: solid blue 2px !important;
}

.selected_date {
  border: solid red 1px !important;
}

.hotel_image {
  width: 20px;
  height: 20px;
}

.submit_button {
  margin: 5px;
  padding: 5px;
  width: 100px;
  height: 30px;
  border-radius: 7px;
  border: solid gray 1px;
  background-color: lightgray;
}

.box {
  border: solid gray 1px;
  border-radius: 10px;
  margin: 10px;
  padding: 10px;
}
</style>

<h1><?php echo t('Scheduler');?></h1>
<div class="box">
  <h4><?php echo t('Limit').': '.$plateList->maxsize . " " . ($plateList->maxsize > 1 ? t('plate authorizations') : t('plate authorization') ); ?></h4>
  <h4><?php echo t('Minimum duration').': '.$minTimeLabel; ?></h4>
  <h4><?php echo t('Maximum duration').': '.$maxTimeLabel; ?></h4>
</div>

<!-- <form  method="post" oncontextmenu="return false;" id="data_form"> -->
<form method="post" id="data_form">
  
  <?php
  echo CHtml::hiddenField ( 'action', 'doit' );
  echo CHtml::hiddenField ( 'hotelMode', $hotelMode ? '1' : '0' );
  echo CHtml::hiddenField ( 'plateListId', $plateListId );
  echo CHtml::hiddenField ( 'minimum_days', $minTimeDays, array (
      'id' => 'minimum_days' 
  ) );
  echo CHtml::hiddenField ( 'maximum_days', $maxTimeDays, array (
      'id' => 'maximum_days' 
  ) );
  ?>
  
  <div class="box">
    <span style="display: inline-block;"> <label for="start_date"><?php echo t('Start date'); ?></label>
      <input type="text" style="text-align: center;" readonly="readonly"
      name="start_date" id="start_date" value="">
    </span> <span style="display: inline-block;"><label for="end_date"><?php echo t('End date'); ?></label>
      <input type="text" style="text-align: center;" readonly="readonly"
      name="end_date" id="end_date" value=""> </span> <span
      style="display: inline-block;"><label for="days_count"><?php echo t($hotelMode ? 'Number of nights':'Number of days'); ?></label>
      <input type="text" style="text-align: center;" readonly="readonly"
      name="days_count" id="days_count" value=""> </span> <span
      style="display: inline-block;"><label for="result_label"><?php echo t('Result'); ?></label>
      <input type="text" style="text-align: center;" readonly="readonly"
      name="result_label" id="result_label" value="" data-ok="0"> </span>
    <span style="display: inline-block;"><label for="reset_button"><?php echo t('Reset'); ?></label><a
      id="reset_button" class="icon-refresh" href="#"></a> </span><br> <span
      style="display: inline-block;"> <label for="name_surname"><?php echo t('Person'); ?></label>
      <input type="text" style="text-align: center;" name="name_surname"
      class="touppercase" id="name_surname"
      value=<?php echo "\"$name_surname\""; ?>>
    </span> <span style="display: inline-block;"> <label for="plate"><?php echo t('Plate'); ?></label>
      <input type="text" style="text-align: center;" name="plate"
      class="touppercase" id="plate" value=<?php echo "\"$plate\""; ?>>
    </span> <span style="display: inline-block;"> <label
      for="nationality"><?php echo t('Nationality'); ?></label>
      <?php echo CHtml::dropDownList('nationality', 'IT', CountryList::localized()); ?>
    </span> <input type="submit" class="submit_button"
      id="submit_button"
      value="<?php echo t('Create plate authorization'); ?>">

  </div>

  <div class="box">    
    <?php
    
    echo ("<table width=\"100%\"><tr><td align=\"left\"><h5><a href=\"$date_month_prev_url\">$date_month_prev_text</a></h5></td><td align=\"center\"><h4>" . (ucwords ( DateHelper::getMonthName ( $date->month ) ) . " $date->year") . "</h4></td><td align=\"right\"><h5><a href=\"$date_month_next_url\">$date_month_next_text</a></h5></td></tr></table>\n");
    
    ?>
    
  <table style="width: 100%">
<?php

echo ("<thead>");
echo ("<tr>");
$thIndex = 0;
foreach ( $columns as $dayIndex )
{
  if ($thIndex > 0 && $hotelMode)
    echo ("<th></th>");
  echo ("<th>" . DateHelper::getDayName ( $dayIndex ) . "</th>");
  $thIndex ++;
}

echo ("</tr>");
echo ("</thead>");

echo ("<tbody>");
$index = 0;
while ( $daysCount > 0 )
{
  echo ("<tr>");
  $tdIndex = 0;
  foreach ( $columns as $dayIndex )
  {
    if ($tdIndex > 0 && $hotelMode)
      echo ("<td>" . CHtml::image ( url ( '/images/hotel.png' ), 'H', array (
          'class' => 'hotel_image' 
      ) ) . "</td>");
    if ($dayIndex == $refDate->getDayOfWeek ( true ))
    {
      if (! $foundFirstEntry)
        $foundFirstEntry = true;
      
      $currentMonth = $refDate->year == $year && $refDate->month == $month;
      
      $dayInfo = query ( "
          SELECT 
          COUNT(*) AS cnt0,
          SUM(CASE WHEN DATE(a.datainizio)<>:day AND DATE(a.datafine)<>:day THEN 1 ELSE 0 END) AS cnt1,
          SUM(CASE WHEN DATE(a.datainizio)=:day THEN 1 ELSE 0 END) AS cnt2,
          SUM(CASE WHEN DATE(a.datafine)=:day THEN 1 ELSE 0 END) AS cnt3
          FROM whitelisttable w 
          INNER JOIN abbonamentotable a 
          ON w.abbonamentoid=a.id 
          WHERE w.list_code=:lst 
          AND 
          DATE(a.datainizio)<=:day
          AND
          :day<=DATE(a.datafine)
          AND
          enabled=1
          ", array (
          ':lst' => $plateList->code,
          ':day' => $refDate->toDateString () 
      ), true, true );
      
      $cnt0 = doubleval ( $dayInfo->cnt0 );
      $cnt1 = doubleval ( $dayInfo->cnt1 );
      $cnt2 = doubleval ( $dayInfo->cnt2 );
      $cnt3 = doubleval ( $dayInfo->cnt3 );
      
      if ($softMode)
        $count = floor ( $cnt1 + ($cnt2 / 2.0) + ($cnt3 / 2.0) );
      else
        $count = floor ( $cnt0 );
      
      $count = minmax ( 0.0, $count, $plateList->maxsize );
      $colorHtml = color_gradient_from_red_to_green ( ($count / $plateList->maxsize) * 100.0, true );
      
      $index ++;
      $ref_id = $index; // str_replace ( "-", "", $refDate->toDateString () );
      
      $freeslots = $plateList->maxsize - $count;
      $percUsed = floor ( $count / $plateList->maxsize * 100.0 );
      
      $percUsedLabel = "{$percUsed} %";
      
      $percUsedTip = t ( "Used {0} of {1}", array (
          '{0}' => $count,
          '{1}' => $plateList->maxsize 
      ) );
      
      $percUsedHtml = "(<span class=\"raise_highlight\" title=\"{$percUsedTip}\">{$percUsedLabel}</span>)";
      
      echo ("<td id=\"td_{$ref_id}\">");
      echo ("<div class=\"div_base raise_highlight\"
          style=\"border: solid {$colorHtml} 2px; background-color: {$colorHtml};\" 
          id=\"div_{$ref_id}\" 
          data-refdate=\"{$refDate->toDateString()}\"
          data-freeslots=\"{$freeslots}\"
          data-index=\"{$index}\"
          >");
      echo ("<span class=\"raise_highlight\" style=\"position: relative; top: 10px;\">");
      if ($currentMonth)
        echo ("<b class=\"raise_highlight\">");
      echo ("{$refDate->format("d / m")} {$percUsedHtml}");
      if ($currentMonth)
        echo ("</b>");
      echo ("<div class=\"raise_highlight\" style=\"color: blue; font-weight: bold; font-size: 20pt; display: none;\" id=\"selected_{$ref_id}\">*</div>");
      // echo('<br><span class="icon-search"></span>');
      echo ("</span>");
      echo ("</div>");
      echo ("</td>");
    }
    else
    {
      echo ("<td>");
      echo ("-");
      echo ("</td>");
    }
    if ($foundFirstEntry)
    {
      $refDate = $refDate->addFromString ( "1 day" );
      $daysCount --;
    }
    $tdIndex ++;
  }
  echo ("</tr>");
}
echo ("</tbody>");

?>
</table>

</form>

</div>

<!-- end of page -->

<!-- scripts starts here -->

<script type="text/javascript">

$('.raise_highlight').on({
  mouseenter: function () {
    $(this).closest('div[id^="div_"]').addClass('div_highlighted');
  },
  mouseout: function () {
    $(this).closest('div[id^="div_"]').removeClass('div_highlighted');
  }
});

function checkChangedValues()
{
  var date_start = $('#start_date').val();
  var date_end = $('#end_date').val();

  if( date_start != '' && date_end != '' )
  {
    var first_date = $('div[data-refdate^='+date_start+']');
    var first_index = first_date.data('index');

    var last_date = $('div[data-refdate^='+date_end+']');
    var last_index = last_date.data('index');

    var daysCountValue = last_index - first_index;
    if( daysCountValue < 0 )
      daysCountValue = daysCountValue * -1;
    daysCountValue++;

    var hotelMode = $('#hotelMode').val();
    if(hotelMode == '1' && daysCountValue > 0)
      daysCountValue--;
    
    $('#days_count').val(daysCountValue);

    var mintime = $('#minimum_days').val();
    var mintimeLabel = mintime <= 0 ? '*' : mintime;    

    var maxtime = $('#maximum_days').val();
    var maxtimeLabel = maxtime <= 0 ? '*' : maxtime;

    var daysCountOk = (
        (
            (mintime <= 0)
            ||
            (mintime > 0 && mintime <= daysCountValue)
          )
          &&
          (
              (maxtime <= 0)
              ||
              (maxtime > 0 && daysCountValue <= maxtime)
            )
            );

    if(!daysCountOk)
      $('#days_count').addClass('field-error');
    else
      $('#days_count').removeClass('field-error');
    
    var plate = $('#plate').val();
    var plateOk = plate != '';

    if(!plateOk)
      $('#plate').addClass('field-error');
    else
      $('#plate').removeClass('field-error');
   
    $('div[id^=selected_]').hide();
    var freeslotsOk = true;
    for(var i=first_index;i<=last_index;i++)
    {
      $('#selected_'+i).show();
      var freeslots = $('#div_'+i).data('freeslots');
      if(freeslots <= 0)
        freeslotsOk = false;
    }
    
    if(daysCountOk && freeslotsOk && plateOk)
    {
      var okLabel = '<?php echo t('Valid selection'); ?>';
      $('#result_label').val(okLabel);
      $('#result_label').addClass('result_good');
      $('#result_label').removeClass('result_bad');
      $('#result_label').data('ok', '1');
      $('#submit_button').prop("disabled",false);
    }
    else
    {
      var noLabel = '<?php echo t('Invalid selection'); ?>';
      $('#result_label').val(noLabel);
      $('#result_label').removeClass('result_good');
      $('#result_label').addClass('result_bad');
      $('#result_label').data('ok', '0');
      $('#submit_button').prop("disabled",true);
    }
  } else $('#submit_button').prop("disabled",true);
}

$("input[name='plate']").change(function() {
  checkChangedValues();
});

// reset
$('#reset_button').click(function() {
  $('#plate').removeClass('field-error');
  $('#days_count').removeClass('field-error');
  $('#start_date').val('');
  $('#end_date').val('');
  $('#days_count').val('');
  $('#result_label').val('');
  $('#result_label').removeClass('result_good');
  $('#result_label').removeClass('result_bad');
  $('#result_label').data('ok', '0');
  $('#submit_button').prop("disabled",true);
  $('div[id^=selected_]').hide();
});

$('div[id^="div_"]').click(function() {

  var date_ref = $(this).data('refdate');

  if($('#start_date').val() == '')
    $('#start_date').val(date_ref);
  else if($('#end_date').val() == '')
    $('#end_date').val(date_ref);
  
  var date_start = $('#start_date').val();
  var date_end = $('#end_date').val();

  if(date_start != '' && date_end != '' )
  {
    if( date_start > date_end )
    {
      $('#start_date').val(date_end);
      $('#end_date').val(date_start);
    }
  }

  checkChangedValues();
});


$('#start_date').on({
  mouseenter: function () {
    var date_start = $(this).val();
    $('div[data-refdate^='+date_start+']').addClass('div_highlighted');    
  },
  mouseout: function () {
    var date_start = $(this).val();
    $('div[data-refdate^='+date_start+']').removeClass('div_highlighted');    
  }
});

$('#end_date').on({
  mouseenter: function () {
    var date_end = $(this).val();
    $('div[data-refdate^='+date_end+']').addClass('div_highlighted');    
  },
  mouseout: function () {
    var date_end = $(this).val();
    $('div[data-refdate^='+date_end+']').removeClass('div_highlighted');    
  }
});

$('#submit_button').on({
  click: function () {
    var plate = $('#plate').val();
    if($('#result_label').data('ok') == '1' && plate != '')
    {
      return true;
    }  
    else
    {
      return false;
    }
  },
});

$('#submit_button').prop("disabled",true);

$('#data_form').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});
    
</script>
