<?
$to_input_datetime = function( $datetime ) {
  if ( !$datetime )
    return '';

  $timestamp = strtotime( (string)$datetime );
  if ( $timestamp === false )
    return '';

  return date( 'Y-m-d\TH:i', $timestamp );
};

$resolve_user_name = function( $user_id ) {
  static $cache = [];
  $user_id = (int)$user_id;

  if ( !isset( $cache[ $user_id ] ) )
  {
    $details = \factory\Users::user_details( $user_id );
    $name = 'Nieznany użytkownik';

    if ( is_array( $details ) )
    {
      $full_name = trim( trim( (string)( $details['name'] ?? '' ) ) . ' ' . trim( (string)( $details['surname'] ?? '' ) ) );
      if ( $full_name !== '' )
        $name = $full_name;
    }

    $cache[ $user_id ] = $name;
  }

  return $cache[ $user_id ];
};
?>
<div class="work-time-logs-popup">
  <div class="mb10">
    <div><b>Zadanie:</b> <?= htmlspecialchars( (string)( $this -> task['name'] ?? '' ), ENT_QUOTES, 'UTF-8' );?></div>
    <div><b>ID:</b> <?= (int)( $this -> task['id'] ?? 0 );?></div>
  </div>

  <? if ( is_array( $this -> task_works ) and count( $this -> task_works ) ):?>
    <div class="table-responsive">
      <table class="table table-sm table-striped mb0">
        <thead>
        <tr>
          <th>Użytkownik</th>
          <th style="width: 220px;">Start</th>
          <th style="width: 220px;">Koniec</th>
          <th class="text-center" style="width: 120px;">Akcja</th>
        </tr>
        </thead>
        <tbody>
        <? foreach ( $this -> task_works as $work ):?>
          <tr class="js-work-log-row" data-work-id="<?= (int)$work['id'];?>">
            <td><?= htmlspecialchars( $resolve_user_name( $work['user_id'] ), ENT_QUOTES, 'UTF-8' );?></td>
            <td>
              <input
                type="datetime-local"
                class="form-control js-work-log-start"
                value="<?= htmlspecialchars( $to_input_datetime( $work['date_start'] ), ENT_QUOTES, 'UTF-8' );?>"
              >
            </td>
            <td>
              <input
                type="datetime-local"
                class="form-control js-work-log-end"
                value="<?= htmlspecialchars( $to_input_datetime( $work['date_end'] ), ENT_QUOTES, 'UTF-8' );?>"
              >
            </td>
            <td class="text-center">
              <a href="#" class="js-save-work-log btn btn-xs btn-primary" task_work_id="<?= (int)$work['id'];?>">zapisz</a>
            </td>
          </tr>
        <? endforeach;?>
        </tbody>
      </table>
    </div>
  <? else:?>
    <div class="alert alert-info mb0">Brak wpisów time trackingu dla tego zadania.</div>
  <? endif;?>
</div>
