<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OrdaSoft Joomla CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/

class AdminViewRent{

  static function showRentItems($option, & $item_for_rent, & $items_for_return_or_edit, & $history_items, &  $userlist, $show_fields,&$user_array) {  
    global $user, $db, $task, $os_cck_configuration;

    // Load mooTools
    $db = new os_cckDb();
    //JHtml::_('behavior.framework', true);
    $doc = JFactory::getDocument();
    
         
    $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />" .
     cck_lang_text('COM_OS_CCK_RENT_SHOW') . "</div>";
    $app = JFactory::getApplication();
    $app->JComponentTitle = $html;
    // $doc->addStyleSheet(JURI::root() . "components/com_os_cck/assets/css/jquerOs-ui.min.css");
    // $doc->addStyleSheet(JURI::root() . "components/com_os_cck/assets/css/admin_style.css");
    
    // $doc->addScript(JURI::root() . "components/com_os_cck/assets/js/jquerOs-ui.min.js");

    //timepicker
    includeJavaScriptCCK("components/com_os_cck/assets/js/jquery.cck_timepicker.js");
    includeStylesCCK('components/com_os_cck/assets/css/jquery.cck_timepicker.css');

    $eiid = $_REQUEST['eiid'];
    $eiid_fordate = $eiid[0];
    $date_NA = available_dates_cck($eiid_fordate);
    
    $minutes_for_day = available_times_cck($eiid_fordate, "d-m-Y");
    $minutes_for_day_rent_to = available_times_cck($eiid_fordate, "d-m-Y", true, 1);

    //$minutes_for_day to json
    if(isset($minutes_for_day)){  
      $minutes_for_day = json_encode($minutes_for_day);
    }else{
      $minutes_for_day = '{}';
    }

    if(isset($minutes_for_day_rent_to)){  
      $minutes_for_day_rent_to = json_encode($minutes_for_day_rent_to);
    }else{
      $minutes_for_day_rent_to = '{}';
    }

    $date_value = date("d-m-Y");
    $form_name = 'adminForm';
    $form_id = 'adminForm' ;
    $table = new os_cckViewTable($form_name, $form_id, '', 'index.php', '');
 
    if ( ($task == "add_rent" ) ) { 
      $what_check = 'fields_and_instance' ;
      $table->create_button(cck_lang_text('COM_OS_CCK_TOOLBAR_ADMIN_SAVE'), 'add_rent_confirm', '', 'fa-save', '', $what_check);
    }else if ( ($task == "edit_rent" ) ) { 
      $what_check = 'fields_and_instance' ;
      $table->create_button(cck_lang_text('COM_OS_CCK_TOOLBAR_ADMIN_SAVE'), 'save_rent', '', 'fa-save', '', $what_check);
    } else if ( ($task == "rent_return" ) ) { 
      $what_check = 'instance' ;
      $table->create_button(cck_lang_text('COM_OS_CCK_TOOLBAR_ADMIN_SAVE'), 'rent_return_confirm', '', 'fa-save', '', $what_check);
    } 

    $table->create_button(cck_lang_text('COM_OS_CCK_CANCEL'), 'cancel', '', 'fa-close');

    $table_html = '';
    ob_start();

?>

    <?php if($os_cck_configuration->get('rent_type') == 2){ ?>
      <script type="text/javascript">

        jQuerOs(document).ready(function() {
            jQuerOs("#rent_from, #rent_until").change(function(event) {
            date_from = jQuerOs("#rent_from").val();
            date_until = jQuerOs("#rent_until").val();

              //get unavailable time rent_from_
              unavailable_time = [];
              minutes_for_day = JSON.parse('<?php echo $minutes_for_day;?>');

              if(minutes_for_day[date_from] !== undefined){
                unavailable_time = minutes_for_day[date_from];
                
              }

              //get unavailable time rent_until_
              unavailable_time_rent_to = [];
              minutes_for_day_rent_to = JSON.parse('<?php echo $minutes_for_day_rent_to;?>');
              if(minutes_for_day_rent_to[date_until] !== undefined){
                 unavailable_time_rent_to = minutes_for_day_rent_to[date_until];
              }
              //rent_from timepicker
          jQuerOs("#time_from").timepicker('remove');
              jQuerOs("#time_from").timepicker(
                  { 
                    'timeFormat' : "H:i:s",
                    //'disableTimeRanges' : unavailable_time,
                    'forceRoundTime': true,
                    'step': 30
                  }
              );


            //rent_until timepicker

              jQuerOs("#time_until").timepicker('remove');
              jQuerOs("#time_until").timepicker(
                  { 
                    'timeFormat' : "H:i:s",
                    //'disableTimeRanges' : unavailable_time_rent_to,
                    'forceRoundTime': true,
                    'step': 30
                  }
              );
  });

          jQuerOs("#rent_from, #time_from").change(function(event) {
             var date = jQuerOs('#rent_from').val();
             var time = jQuerOs('#time_from').val();

             jQuerOs("[name = rent_from]").val(date+" "+time);
          });

          jQuerOs("#rent_until, #time_until").change(function(event) {
             var date = jQuerOs('#rent_until').val();
             var time = jQuerOs('#time_until').val();

             jQuerOs("[name = rent_until]").val(date+" "+time);
          });

      });

      </script>

    <?php }else{ ?>

        <script type="text/javascript">

      jQuerOs(document).ready(function() {

        jQuerOs("#rent_from").change(function(event) {
           var date = jQuerOs('#rent_from').val();
           jQuerOs("[name = rent_from]").val(date);
        });

        jQuerOs("#rent_until").change(function(event) {
           var date = jQuerOs('#rent_until').val();
           jQuerOs("[name = rent_until]").val(date);
        });

    });

    </script>

    <?php }; ?>


    <script type="text/javascript">
      var unavailableDates = Array();
      jQuerOs(document).ready(function() {
        var k=0;
        <?php if(!empty($date_NA)){
          foreach ($date_NA as $N_A){ ?>
            unavailableDates[k]= '<?php echo $N_A; ?>';
            k++;
          <?php } ?>
        <?php } ?>

        function unavailableFrom(date) {
          dmy = date.getFullYear() + "-" + ('0'+(date.getMonth() + 1)).slice(-2) +
            "-" + ('0'+date.getDate()).slice(-2);
          if (jQuerOs.inArray(dmy, unavailableDates) == -1) {
            return [true, ""];
          } else {
            return [false, "", "Unavailable"];
          }
        }

         function unavailableUntil(date) {
          dmy = date.getFullYear() + "-" + ('0'+(date.getMonth() + 1)).slice(-2) +
            "-" + ('0'+(date.getDate()-("<?php  if($os_cck_configuration->get('rent_type')==0 ) echo 1;?>"))).slice(-2);
          if (jQuerOs.inArray(dmy, unavailableDates) == -1) {
            return [true, ""];
          } else {
            return [false, "", "Unavailable"];
          }
        }

        jQuerOs( "#rent_from" ).datepicker({
          <?php 
          if($task == "add_rent") echo 'minDate: "+0", beforeShowDay: unavailableFrom,';
          ?>
          dateFormat: "<?php echo transforDateFromPhpToJqueryCCK('d-m-Y');?>"
          
        });

        jQuerOs( "#rent_until" ).datepicker({
          <?php 
          if($task == "add_rent") echo 'minDate: "+0", beforeShowDay: unavailableUntil,';
          ?>
          dateFormat: "<?php echo transforDateFromPhpToJqueryCCK('d-m-Y');?>"
          
        });


      });
    </script>
    
    <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
        <div id="error_massage"></div>
  
<!--    <form action="index.php" method="post" name="adminForm" id="adminForm">-->

<?php
      if ( ($task == "edit_rent"  or $task == "add_rent" or $task == "rent_return") ) { 
        if ( $task == "edit_rent" ) { 
          echo "<h2>Edit Rent:</h2>";
        }elseif ( $task == "add_rent" ) { 
          echo "<h2>Move Instance to Rent:</h2>";
        }elseif ( $task == "rent_return" ) { 
          echo "<h2>Return Instance from Rent:</h2>";
        }
      }
      if ( ($task == "edit_rent"  or $task == "add_rent") ) { 
?>

        <table cellpadding="4" cellspacing="0" border="0" width="100%">
          <tr>
            <td align="left" nowrap="nowrap">
              <?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_TO') . ':'; ?>
            </td>
          </tr>
          <tr>
            <td align="left" nowrap="nowrap">
              <?php echo $userlist; ?>
            </td>
          </tr>
          <tr>
            <td align="left" nowrap="nowrap">
              <?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_USER') . '*:'; ?>
            </td>
          </tr>
          <tr>
            <td align="left">
              <input type="text" name="user_name" class="inputbox required"/>
            </td>
          </tr>
          <tr>
            <td align="left" nowrap="nowrap">
                <?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_EMAIL') . '*:'; ?>
            </td>
          </tr>
          <tr>
            <td>
                <input type="text" name="user_email" class="inputbox required"/>
            </td>
          </tr>
          <tr>
            <td align="left" nowrap="nowrap">
              <?php echo "Rent from*:"; ?>
            </td>
          </tr>
          <tr>
            <td align="left" nowrap="nowrap">
                <input type="text" class="required" id="rent_from" name="" value="<?php echo $date_value?>">
            </td>
          </tr>

          <?php if($os_cck_configuration->get('rent_type') == 2): ?>
            <tr>
              <td align="left" nowrap="nowrap">
                <input type="text" class="required" id="time_from" name="" placeholder="Time from">
              </td>
            </tr>
          <?php endif;?>

            <input type="hidden" name="rent_from" value="<?php echo $date_value?>">
          <tr>
            <td align="left" nowrap="nowrap">
              <?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_TIME'); ?>
            </td>
          </tr>
          <tr>
            <td align="left" nowrap="nowrap">
                <input type="text" class="required" id="rent_until" name="" value="<?php echo $date_value?>">
            </td>
          </tr>

            <?php if($os_cck_configuration->get('rent_type') == 2): ?>
              <tr>
                <td align="left" nowrap="nowrap">
                  <input type="text" class="required" id="time_until" name="" placeholder="Time until">
                </td>
              </tr>
            <?php endif;?>

          <input type="hidden" name="rent_until" value="<?php echo $date_value?>">
        </table>
        <?php
      }
      ?>

<?php
      if ( ($task == "edit_rent"  or $task == "add_rent" or $task == "rent_return") ) { 
     
        $instances_array = array();
        if ( $task == "edit_rent" ) { 
          echo "<h2>Select Instance for edit Rent:</h2>";
          $instances_array = $items_for_return_or_edit;
        }elseif ( $task == "add_rent" ) { 
          echo "<h2>Select Instance for move to Rent:</h2>";
          $instances_array = $item_for_rent;
        }elseif ( $task == "rent_return" ) { 
          echo "<h2>Select Instance for return from Rent:</h2>";
          $instances_array = $items_for_return_or_edit;
        }
?>
      <table cellpadding="4" cellspacing="0" border="0" width="100%" class="adminlist admin-one-order">
        <tr>
          <th width="5%" align="left">
          </th>
          <th width="5%">#</th>
          <th align="center" class="title" width="5%" nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_ID');?></th>
          <?php
          foreach($show_fields as $value){
            foreach($value as $field){
              ?>
              <th align="center" class="title" width="15%"
                nowrap="nowrap"><?php echo $field->field_name;?></th>
              <?php
            }
          }
          ?>
          <th align="center" class="title" width="15%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_ENTITY');?></th>
          <th align="center" class="title" width="15%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_FROM'); ?></th>
          <th align="center" class="title" width="20%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_UNTIL'); ?></th>
          <th align="center" class="title" width="20%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_RETURN'); ?></th>
          <th align="center" class="title" width="15%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_TO'); ?></th>
        </tr>
        <?php
            if(isset($instances_array)){
                $count = count($instances_array);
            }else{
                $count = 0;
            }
          for ($i = 0; $i < $count; $i++) {
            $row = & $instances_array[$i];
            ?>
            <tr <?php echo ($row->rent_return)? 'style="color:#0C6B00";' : 'style="color:#630712"'?> class="row<?php echo $i % 2; ?>">
              <td width="20" align="left">
                <?php if ($row->checked_out && $row->checked_out != $user->id) { ?>
                  &nbsp;
                <?php
                } else {
                  echo
                  '<input id="cb'.$i.'" type="checkbox" value="'.$row->rent_id.'" name="return_id[]">';
                }
                ?>
              </td>
              <td align="center"><?php echo ($i+1); ?></td>
              <td align="center"><?php echo $row->eiid; ?></td>
  <!-- **************************************************************** -->
              <?php
              foreach($show_fields as $key => $value){
                  foreach($value as $field){
                    // $html = '';
                    if($row->fk_eid != $key){
                      echo'<td></td>';
                      continue;
                    }
                    if($field->field_type == 'categoryfield'){
                      echo "<td align='center'>$row->category</td>";
                      continue;
                    }
                    ?>
                    <td align="center">
                      <?php
                      $entityInstance = new os_cckEntityInstance($db->_db);
                      $entityInstance->load($row->eiid);
                      $value = $entityInstance->getFieldValue($field);
                      ?>
                      <div style="margin-right:15px";>
                          <span class="col_box" style="display:block;
                          <?php echo ($field->field_type=='imagefield'
                                      && isset($field->options['width'])
                                      && isset($field->options['height']))? 'width:'.$field->options['width'].'px; height:'.$field->options['height'].'px;':'';?>" >
                              <?php
                                  // ob_start();
                                    require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                                    // $html .= ob_get_contents();
                                  // ob_end_clean();
                                  // echo $html;
                              ?>
                          </span>
                      </div>
                    </td>
                    <?php
                  }
                }
                ?>
  <!-- **************************************************************** -->

              <td align="center"><?php echo $row->entity; ?></td>
              <td align="center"><?php if( $task != "add_rent" ) echo $row->rent_from ?></td>
              <td align="center"><?php if( $task != "add_rent" ) echo $row->rent_until ?></td>
              <td align="center"><?php if( $task != "add_rent" ) echo ($row->rent_return)?$row->rent_return : '<b>In Rent</b>'?></td>
              <td align="center"><?php if( $task != "add_rent" ) echo ($row->user_name || $row->user_email)?
                                            $row->user_name . ":  " . $row->user_email:'' ?>
              </td>
          </tr>
        <?php
        }//end for
        ?>
      </table>
    <?php
      }
    ?>


      <h2>Rent History:</h2>
      <table cellpadding="4" cellspacing="0" border="0" width="100%" class="adminlist">
        <tr>
          <th width="5%">#</th>
          <th align="center" class="title" width="5%" nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_ID');?></th>
          <?php
          foreach($show_fields as $value){
            foreach($value as $field){
              ?>
              <th align="center" class="title" width="15%"
                nowrap="nowrap"><?php echo $field->field_name;?></th>
              <?php
            }
          }
          ?>
          <th align="center" class="title" width="15%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_ENTITY');?></th>
          <th align="center" class="title" width="15%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_FROM'); ?></th>
          <th align="center" class="title" width="20%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_UNTIL'); ?></th>
          <th align="center" class="title" width="20%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_RETURN'); ?></th>
          <th align="center" class="title" width="15%"
              nowrap="nowrap"><?php echo cck_lang_text('COM_OS_CCK_LABEL_RENT_TO'); ?></th>
        </tr>
        <?php
        if(isset($history_items)){
                $count = count($history_items);
            }else{
                $count = 0;
            }
          for ($i = 0; $i < $count; $i++) {
            $row = & $history_items[$i];
            ?>
            <tr <?php echo ($row->rent_return)? 'style="color:#0C6B00";' : 'style="color:#630712"'?> class="row<?php echo $i % 2; ?>">
              <td align="center"><?php echo ($i+1); ?></td>
              <td align="center"><?php echo $row->eiid; ?></td>
  <!-- **************************************************************** -->
              <?php
                foreach($show_fields as $key => $value){
                  foreach($value as $field){
                    // $html = '';
                    if($row->fk_eid != $key){
                      echo'<td></td>';
                      continue;
                    }
                    if($field->field_type == 'categoryfield'){
                      echo "<td align='left'>$row->category</td>";
                      continue;
                    }
                    ?>
                    <td align="left">
                      <?php
                      $entityInstance = new os_cckEntityInstance($db->_db);
                      $entityInstance->load($row->eiid);
                      $value = $entityInstance->getFieldValue($field);
                      ?>
                      <div style="float:left; margin-right:15px";>
                          <span class="col_box" style="display:block;
                          <?php echo ($field->field_type=='imagefield'
                                      && isset($field->options['width'])
                                      && isset($field->options['height']))? 'width:'.$field->options['width'].'px; height:'.$field->options['height'].'px;':'';?>">
                              <?php
                                  // ob_start();
                                    require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                                    // $html .= ob_get_contents();
                                  // ob_end_clean();
                                  // echo $html;
                              ?>
                          </span>
                      </div>
                    </td>
                    <?php
                  }
                }
              ?>
  <!-- **************************************************************** -->
              <td align="center"><?php echo $row->entity; ?></td>
              <td align="center"><?php echo $row->rent_from ?></td>
              <td align="center"><?php echo $row->rent_until ?></td>
              <td align="center"><?php echo ($row->rent_return)?$row->rent_return : '<b>In Rent</b>'?></td>
              <td align="center"><?php echo ($row->user_name || $row->user_email)?
                                            $row->user_name . ":  " . $row->user_email:'' ?>
              </td>
          </tr>
        <?php
        }//end for
        ?>
      </table>
      <input type="hidden" name="eiid" value="<?php echo $eiid_fordate?>"/>
      <input type="hidden" name="option" value="<?php echo $option; ?>"/>
      <input type="hidden" name="task" value="save_rent"/>
      <input type="hidden" name="boxchecked" value="1"/>
      <input type="hidden" name="save" value="1"/>
<!--    </form>-->
    <?php
    $table_html = ob_get_contents();
    ob_end_clean();
    $table->set_custom_html($table_html);
    echo $table->viewTable();
    ?>
    <script>
    var user_array = new Array();
  <?php
    foreach ($user_array as $user_data) {
  ?>
      user_array["<?php echo $user_data->value ?>"] = new Array();
      user_array["<?php echo $user_data->value ?>"]['name'] = "<?php echo $user_data->text ?>";
      user_array["<?php echo $user_data->value ?>"]['email'] = "<?php echo $user_data->email ?>";
  <?php
    }
   ?> 
      function fill_user(id){
        if(user_array[id] && user_array[id]['name'] && user_array[id]['email']){
          form = document.<?php echo $form_name; ?>;
          form.user_name.value = user_array[id]['name'];
          form.user_email.value = user_array[id]['email'];
          form.user_name.readOnly = true;
          form.user_email.readOnly = true;
        }else{
          form.user_name.value = '';
          form.user_email.value = '';
          form.user_name.readOnly = false;
          form.user_email.readOnly = false;
        }
      }

     
//        submitbutton = function(pressbutton) {
//            if(pressbutton == 'cancel'){
//                window.history.back();
//            }
//            
//        }
    </script>
    <?php
   
  }

} 
